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 bettermode import source (#71239)

Tom Owersdbda3a1491a3
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 426f6f20d5c3..4b54987b7bb1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -79,6 +79,7 @@ the row lists both.
| baseten | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
| better_stack | HTTP | requests | ✅ |
+| bettermode | HTTP (GraphQL) | requests | ✅ |
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
@@ -604,7 +605,6 @@ doesn't conflict with concurrent PRs.
- babelforce
- backblaze
- basecamp
-- bettermode
- bigcommerce
- bitly
- bitrise
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py
new file mode 100644
index 000000000000..ce1456a52f18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/bettermode.py
@@ -0,0 +1,370 @@
+import json
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+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.bettermode.settings import (
+ BETTERMODE_ENDPOINTS,
+ BettermodeEndpointConfig,
+)
+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
+
+# Bettermode serves one GraphQL endpoint per hosting region.
+BETTERMODE_HOSTS = {
+ "us": "https://api.bettermode.com",
+ "eu": "https://api.bettermode.de",
+}
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Page size when enumerating parent post ids for the replies fan-out — id-only nodes are
+# cheap in Bettermode's query-cost model, so the maximum-ish page keeps request count low.
+PARENT_PAGE_SIZE = 100
+
+_TOKEN_QUERY = """
+query AppToken($networkId: String!) {
+ limitedToken(context: NETWORK, networkId: $networkId, entityId: $networkId) {
+ accessToken
+ }
+}
+"""
+
+_PARENT_POSTS_QUERY = """
+query ParentPosts($limit: Int!, $after: String) {
+ posts(limit: $limit, after: $after) {
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ nodes {
+ id
+ totalRepliesCount
+ }
+ }
+}
+"""
+
+
+class BettermodeRetryableError(Exception):
+ pass
+
+
+class BettermodeGraphQLError(Exception):
+ """A GraphQL-level error. Bettermode returns these in HTTP 200 bodies with a status code
+ in the error's extensions; the message keeps a stable `Bettermode API error (status N)`
+ prefix that `get_non_retryable_errors` matches on."""
+
+
+class BettermodeResumeConfig:
+ # Relay cursor of the last fully-yielded page within the current connection.
+ after: str | None = None
+ # Replies fan-out bookmark: the parent post currently being processed. A stable post-ID
+ # bookmark (not a positional index) so posts created/deleted between a crash and the
+ # retry can't resume us into the wrong parent. None for top-level endpoints.
+ post_id: str | None = None
+
+
+def _base_url(region: str) -> str:
+ host = BETTERMODE_HOSTS.get(region)
+ if host is None:
+ raise ValueError(f"Invalid Bettermode region: {region}")
+ return host
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor as an ISO 8601 UTC string for a filterBy value."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00.000Z")
+ return str(value)
+
+
+def _execute(
+ session: requests.Session,
+ url: str,
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.post(url, json={"query": query, "variables": variables}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BettermodeRetryableError(f"Bettermode API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"Bettermode API error: status={response.status_code}, body={response.text}")
+ response.raise_for_status()
+
+ body = response.json()
+ errors = body.get("errors")
+ if errors:
+ # GraphQL errors arrive in 200 responses; the real status lives on the error object
+ # (e.g. 401/403 for auth problems, 404 "App not found" for bad client credentials).
+ first = errors[0] if isinstance(errors[0], dict) else {}
+ status = first.get("status") or (first.get("extensions") or {}).get("status")
+ message = "; ".join(str(error.get("message", error)) for error in errors if isinstance(error, dict))
+ raise BettermodeGraphQLError(f"Bettermode API error (status {status}): {message}")
+
+ return body.get("data") or {}
+
+
+class _NoopLogger:
+ def error(self, *args: Any, **kwargs: Any) -> None:
+ return None
+
+
+def get_access_token(region: str, client_id: str, client_secret: str, network_id: str) -> str:
+ """Mint an app access token (a ~30-day JWT) via the `limitedToken` query.
+
+ The exchange authenticates with HTTP Basic auth of the app's client id/secret; the app
+ must be published and installed on the target community or Bettermode responds with a
+ 403 in the GraphQL errors.
+ """
+ session = make_tracked_session(redact_values=(client_secret,), capture=False)
+ session.auth = (client_id, client_secret)
+ data = _execute(session, _base_url(region), _TOKEN_QUERY, {"networkId": network_id}, _NoopLogger()) # type: ignore[arg-type]
+ token = (data.get("limitedToken") or {}).get("accessToken")
+ if not token:
+ raise BettermodeGraphQLError("Bettermode API error (status None): token exchange returned no accessToken")
+ return token
+
+
+def _get_authed_session(region: str, client_id: str, client_secret: str, network_id: str) -> requests.Session:
+ token = get_access_token(region, client_id, client_secret, network_id)
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {token}"}, redact_values=(token, client_secret), capture=False
+ )
+
+
+def validate_credentials(region: str, client_id: str, client_secret: str, network_id: str) -> tuple[bool, str | None]:
+ """One cheap probe: minting the app token validates the client id/secret, the network id,
+ and that the app is installed on the community."""
+ try:
+ get_access_token(region, client_id, client_secret, network_id)
+ return True, None
+ except BettermodeGraphQLError as e:
+ return False, str(e)
+ except Exception:
+ return False, "Could not reach the Bettermode API"
+
+
+def _build_query(config: BettermodeEndpointConfig) -> str:
+ args = {"limit": "Int!", "after": "String", **config.extra_args}
+ declarations = ", ".join(f"${name}: {gql_type}" for name, gql_type in args.items())
+ call_args = ", ".join(f"{name}: ${name}" for name in args)
+ return f"""
+query ({declarations}) {{
+ {config.query_field}({call_args}) {{
+ pageInfo {{
+ endCursor
+ hasNextPage
+ }}
+ nodes {{
+{config.node_fields}
+ }}
+ }}
+}}
+"""
+
+
+def _build_post_variables(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ """Sort and (when incremental) filter variables for the `posts` connection.
+
+ An explicit `orderBy` keeps pagination deterministic across pages. The filter value is a
+ JSON-encoded ISO datetime — the format Bettermode's own frontend passes — and `gte`
+ re-fetches the boundary row so records sharing the watermark are never skipped (merge
+ dedupes on the primary key).
+ """
+ filter_field = incremental_field or "createdAt"
+ variables: dict[str, Any] = {"orderBy": filter_field, "reverse": False}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ variables["filterBy"] = [
+ {
+ "key": filter_field,
+ "operator": "gte",
+ "value": json.dumps(_format_datetime(db_incremental_field_last_value)),
+ }
+ ]
+ return variables
+
+
+def _make_execute(session: requests.Session, url: str, logger: FilteringBoundLogger):
+ @retry(
+ retry=retry_if_exception_type((BettermodeRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+ )
+ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:
+ return _execute(session, url, query, variables, logger)
+
+ return execute
+
+
+def _iter_connection(
+ execute: Any,
+ query: str,
+ query_field: str,
+ base_variables: dict[str, Any],
+ page_size: int,
+ after: str | None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Walk one Relay-style connection, yielding `(nodes, next_cursor)` per page.
+
+ `next_cursor` is None on the final page so callers know not to persist resume state
+ past the end of the connection.
+ """
+ while True:
+ data = execute(query, {**base_variables, "limit": page_size, "after": after})
+ connection = data.get(query_field) or {}
+ nodes = connection.get("nodes") or []
+ page_info = connection.get("pageInfo") or {}
+ has_next = bool(page_info.get("hasNextPage"))
+ end_cursor = page_info.get("endCursor")
+ next_cursor = end_cursor if has_next and end_cursor and nodes else None
+
+ if nodes:
+ yield nodes, next_cursor
+
+ if next_cursor is None:
+ break
+ after = next_cursor
+
+
+def _get_reply_rows(
+ execute: Any,
+ config: BettermodeEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out one `replies(postId: ...)` connection per post that has replies.
+
+ Bettermode has no flat network-wide replies listing, so parents are enumerated with a
+ cheap id-only posts walk first. Only direct replies of listed posts are fetched.
+ """
+ parent_ids: list[str] = []
+ for nodes, _ in _iter_connection(execute, _PARENT_POSTS_QUERY, "posts", {}, PARENT_PAGE_SIZE, None):
+ parent_ids.extend(node["id"] for node in nodes if (node.get("totalRepliesCount") or 0) > 0)
+
+ # Resolve the saved post-ID bookmark to the slice of parents still to process. If the
+ # bookmarked post no longer exists, start over — merge dedupes re-pulled rows on the
+ # primary key. `resume_after` is consumed by the bookmarked parent only.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = parent_ids
+ resume_after: str | None = None
+ if resume is not None and resume.post_id is not None and resume.post_id in parent_ids:
+ remaining = parent_ids[parent_ids.index(resume.post_id) :]
+ resume_after = resume.after
+ logger.debug(f"Bettermode: resuming replies from post_id={resume.post_id}")
+
+ query = _build_query(config)
+ for index, post_id in enumerate(remaining):
+ variables = {"postId": post_id, "orderBy": "createdAt", "reverse": False}
+ for nodes, next_cursor in _iter_connection(
+ execute, query, "replies", variables, config.page_size, resume_after
+ ):
+ yield nodes
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the
+ # last page rather than skipping it — merge dedupes on the primary key.
+ if next_cursor:
+ resumable_source_manager.save_state(BettermodeResumeConfig(after=next_cursor, post_id=post_id))
+ resume_after = None
+
+ # Advance the bookmark so a crash between parents resumes at the next post.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(BettermodeResumeConfig(after=None, post_id=remaining[index + 1]))
+
+
+def get_rows(
+ region: str,
+ client_id: str,
+ client_secret: str,
+ network_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BETTERMODE_ENDPOINTS[endpoint]
+ session = _get_authed_session(region, client_id, client_secret, network_id)
+ execute = _make_execute(session, _base_url(region), logger)
+
+ if config.fan_out_replies:
+ yield from _get_reply_rows(execute, config, resumable_source_manager, logger)
+ return
+
+ base_variables: dict[str, Any] = {}
+ if config.query_field == "posts":
+ base_variables = _build_post_variables(
+ should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ 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"Bettermode: resuming {endpoint} from cursor")
+
+ query = _build_query(config)
+ for nodes, next_cursor in _iter_connection(
+ execute, query, config.query_field, base_variables, config.page_size, after
+ ):
+ yield nodes
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the
+ # primary key) rather than skipping it.
+ if next_cursor:
+ resumable_source_manager.save_state(BettermodeResumeConfig(after=next_cursor))
+
+
+def bettermode_source(
+ region: str,
+ client_id: str,
+ client_secret: str,
+ network_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = BETTERMODE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ client_id=client_id,
+ client_secret=client_secret,
+ network_id=network_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ 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,
+ # Bettermode doesn't document connection ordering guarantees, so the pipeline defers
+ # the incremental watermark commit until a run completes.
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py
new file mode 100644
index 000000000000..2cf64e094b36
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/canonical_descriptions.py
@@ -0,0 +1,127 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_POST_COLUMNS = {
+ "id": "Unique identifier of the post.",
+ "networkId": "ID of the community (network) the post belongs to.",
+ "spaceId": "ID of the space the post was published in.",
+ "postTypeId": "ID of the post type (e.g. discussion, question, article).",
+ "title": "Title of the post.",
+ "slug": "URL slug of the post.",
+ "shortContent": "Truncated rendered content of the post.",
+ "textContent": "Plain-text content of the post.",
+ "status": "Publication status: PUBLISHED, DRAFT, ARCHIVED, BLOCKED, or DELETED.",
+ "language": "Language code of the post content.",
+ "ownerId": "ID of the member who owns the post.",
+ "createdById": "ID of the member who created the post.",
+ "repliedToId": "ID of the parent post when this row is a reply; null for top-level posts.",
+ "repliesCount": "Number of direct replies to the post.",
+ "totalRepliesCount": "Number of replies including nested replies.",
+ "reactionsCount": "Total number of reactions on the post.",
+ "reactions": "Per-reaction summary as a list of {reaction, count} objects.",
+ "isAnonymous": "Whether the post was published anonymously.",
+ "isHidden": "Whether the post is hidden from listings.",
+ "locked": "Whether new replies and reactions are locked.",
+ "tagIds": "IDs of tags applied to the post.",
+ "externalId": "External identifier assigned by an integration, if any.",
+ "createdAt": "Timestamp when the post was created.",
+ "publishedAt": "Timestamp when the post was published.",
+ "updatedAt": "Timestamp when the post was last updated.",
+ "lastActivityAt": "Timestamp of the most recent activity (reply or reaction) on the post.",
+ "relativeUrl": "Path of the post relative to the community domain.",
+ "url": "Full URL of the post.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "members": {
+ "description": "People in the community, including their profile, role, and activity timestamps.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/member/",
+ "columns": {
+ "id": "Unique identifier of the member.",
+ "networkId": "ID of the community (network) the member belongs to.",
+ "name": "Display name of the member.",
+ "username": "Unique username of the member.",
+ "email": "Email address of the member.",
+ "status": "Account status: VERIFIED, UNVERIFIED, or Suspended.",
+ "emailStatus": "Verification status of the member's email address.",
+ "roleId": "ID of the member's network role (e.g. admin, moderator, member).",
+ "teammate": "Whether the member is a staff teammate of the community.",
+ "tagline": "Short bio line shown on the member's profile.",
+ "locale": "Locale of the member.",
+ "timeZone": "Time zone of the member.",
+ "score": "Engagement score of the member.",
+ "flagged": "Whether the member has been flagged for moderation.",
+ "externalId": "External identifier assigned by an integration (e.g. SSO), if any.",
+ "subscribersCount": "Number of members following this member.",
+ "createdAt": "Timestamp when the member joined the community.",
+ "updatedAt": "Timestamp when the member was last updated.",
+ "lastSeenAt": "Timestamp when the member was last seen in the community.",
+ "verifiedAt": "Timestamp when the member verified their account.",
+ "relativeUrl": "Path of the member profile relative to the community domain.",
+ "url": "Full URL of the member profile.",
+ },
+ },
+ "spaces": {
+ "description": "Spaces (groups, channels, or sections) that organize the community's content.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/space/",
+ "columns": {
+ "id": "Unique identifier of the space.",
+ "networkId": "ID of the community (network) the space belongs to.",
+ "name": "Name of the space.",
+ "slug": "URL slug of the space.",
+ "description": "Description of the space.",
+ "type": "Space type: Group, Page, Broadcast, Entity, or PrivateMessage.",
+ "groupId": "ID of the collection/group the space belongs to.",
+ "createdById": "ID of the member who created the space.",
+ "private": "Whether the space is private.",
+ "hidden": "Whether the space is hidden from non-members.",
+ "inviteOnly": "Whether members can only join by invitation.",
+ "nonAdminsCanInvite": "Whether non-admin members can invite others to the space.",
+ "isHomepage": "Whether the space is the community homepage.",
+ "membersCount": "Number of members in the space.",
+ "postsCount": "Number of posts in the space.",
+ "subscribersCount": "Number of members subscribed to the space.",
+ "externalId": "External identifier assigned by an integration, if any.",
+ "createdAt": "Timestamp when the space was created.",
+ "updatedAt": "Timestamp when the space was last updated.",
+ "relativeUrl": "Path of the space relative to the community domain.",
+ "url": "Full URL of the space.",
+ },
+ },
+ "posts": {
+ "description": "Top-level posts published in the community's spaces, including reaction summaries.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/post/",
+ "columns": _POST_COLUMNS,
+ },
+ "replies": {
+ "description": "Direct replies to posts. Replies share the post shape; repliedToId points at the parent post.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/post/",
+ "columns": _POST_COLUMNS,
+ },
+ "tags": {
+ "description": "Tags available for categorizing posts in the community.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/tag/",
+ "columns": {
+ "id": "Unique identifier of the tag.",
+ "title": "Display title of the tag.",
+ "slug": "URL slug of the tag.",
+ "description": "Description of the tag.",
+ },
+ },
+ "moderation_items": {
+ "description": "Items (posts or members) flagged for moderation review, with their resolution status.",
+ "docs_url": "https://developers.bettermode.com/docs/graphql/objects/moderation-item/",
+ "columns": {
+ "id": "Unique identifier of the moderation item.",
+ "status": "Moderation status: REVIEW, ACCEPTED, or REJECTED.",
+ "flaggedBy": "Whether the item was flagged by a MEMBER or by the SYSTEM.",
+ "description": "Reason or description attached to the flag.",
+ "memberId": "ID of the reported member, when the flagged entity is a member.",
+ "spaceId": "ID of the space the flagged content belongs to.",
+ "entity": "The flagged entity as {__typename, id} — a Post or a Member.",
+ "createdAt": "Timestamp when the item was flagged.",
+ "updatedAt": "Timestamp when the item was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py
new file mode 100644
index 000000000000..3df37881f38b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/settings.py
@@ -0,0 +1,209 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# `posts` exposes a genuine server-side timestamp filter: `filterBy` accepts the typed
+# PostListFilterByEnum keys createdAt / publishedAt / updatedAt with a `gte` operator
+# (Bettermode's own frontend filters trending posts with `{key: createdAt, operator: gte}`).
+_POST_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "publishedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "publishedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "updatedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+# Node selections stick to scalars (complexity 0 in Bettermode's query-cost model) plus the
+# small `reactions {reaction count}` summary, keeping each page well under the API's
+# per-query complexity ceiling.
+_MEMBER_NODE_FIELDS = """
+id
+networkId
+name
+username
+email
+status
+emailStatus
+roleId
+teammate
+tagline
+locale
+timeZone
+score
+flagged
+externalId
+subscribersCount
+createdAt
+updatedAt
+lastSeenAt
+verifiedAt
+relativeUrl
+url
+"""
+
+_SPACE_NODE_FIELDS = """
+id
+networkId
+name
+slug
+description
+type
+groupId
+createdById
+private
+hidden
+inviteOnly
+nonAdminsCanInvite
+isHomepage
+membersCount
+postsCount
+subscribersCount
+externalId
+createdAt
+updatedAt
+relativeUrl
+url
+"""
+
+_POST_NODE_FIELDS = """
+id
+networkId
+spaceId
+postTypeId
+title
+slug
+shortContent
+textContent
+status
+language
+ownerId
+createdById
+repliedToId
+repliesCount
+totalRepliesCount
+reactionsCount
+reactions {
+reaction
+count
+}
+isAnonymous
+isHidden
+locked
+tagIds
+externalId
+createdAt
+publishedAt
+updatedAt
+lastActivityAt
+relativeUrl
+url
+"""
+
+_TAG_NODE_FIELDS = """
+id
+title
+slug
+description
+"""
+
+_MODERATION_NODE_FIELDS = """
+id
+status
+flaggedBy
+description
+memberId
+spaceId
+entity {
+__typename
+... on Post {
+id
+}
+... on Member {
+id
+}
+}
+createdAt
+updatedAt
+"""
+
+
+@dataclass
+class BettermodeEndpointConfig:
+ # Root query field on the GraphQL schema (e.g. `posts`, `moderationItems`).
+ query_field: str
+ node_fields: str
+ # Extra GraphQL variables beyond `limit`/`after`: name -> GraphQL type. Declared in the
+ # query document and passed through when present in the request variables.
+ extra_args: dict[str, str] = field(default_factory=dict)
+ page_size: int = 50
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation timestamp for partitioning; None for endpoints with no timestamps.
+ partition_key: str | None = "createdAt"
+ # Fan out one `replies(postId: ...)` connection per post that has replies.
+ fan_out_replies: bool = False
+
+
+BETTERMODE_ENDPOINTS: dict[str, BettermodeEndpointConfig] = {
+ "members": BettermodeEndpointConfig(
+ query_field="members",
+ node_fields=_MEMBER_NODE_FIELDS,
+ ),
+ "spaces": BettermodeEndpointConfig(
+ query_field="spaces",
+ node_fields=_SPACE_NODE_FIELDS,
+ ),
+ "posts": BettermodeEndpointConfig(
+ query_field="posts",
+ node_fields=_POST_NODE_FIELDS,
+ extra_args={
+ "filterBy": "[PostListFilterByInput!]",
+ "orderBy": "PostListOrderByEnum",
+ "reverse": "Boolean",
+ },
+ # Post nodes carry full text content; smaller pages keep response sizes and query
+ # complexity manageable.
+ page_size=30,
+ incremental_fields=_POST_INCREMENTAL_FIELDS,
+ ),
+ "replies": BettermodeEndpointConfig(
+ query_field="replies",
+ node_fields=_POST_NODE_FIELDS,
+ extra_args={
+ "postId": "ID!",
+ "orderBy": "PostListOrderByEnum",
+ "reverse": "Boolean",
+ },
+ page_size=30,
+ fan_out_replies=True,
+ ),
+ "tags": BettermodeEndpointConfig(
+ query_field="tags",
+ node_fields=_TAG_NODE_FIELDS,
+ page_size=100,
+ partition_key=None,
+ ),
+ "moderation_items": BettermodeEndpointConfig(
+ query_field="moderationItems",
+ node_fields=_MODERATION_NODE_FIELDS,
+ ),
+}
+
+ENDPOINTS = tuple(BETTERMODE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BETTERMODE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py
index 3136c09072b6..f5375fd880a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/source.py
@@ -1,30 +1,193 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.bettermode.bettermode import (
+ BettermodeResumeConfig,
+ bettermode_source,
+ validate_credentials as validate_bettermode_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BettermodeSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BettermodeSource(SimpleSource[BettermodeSourceConfig]):
+class BettermodeSource(ResumableSource[BettermodeSourceConfig, BettermodeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BETTERMODE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `region` picks the host the stored client secret is sent to, and `network_id` selects
+ # which community the minted token is scoped to; retargeting either must re-require the
+ # secret so a preserved credential can't be aimed elsewhere without re-entry.
+ return ["region", "network_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BETTERMODE,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
- label="Bettermode (formerly Tribe)",
+ label="Bettermode",
+ keywords=["tribe", "community"],
+ caption="""Connect your Bettermode (formerly Tribe) community to pull members, spaces, posts, replies, tags, and moderation items into the PostHog Data warehouse.
+
+Create an app in the [Bettermode developer portal](https://developers.bettermode.com/), then copy its client ID and client secret. The app must be **published and installed on your community** before tokens can be issued.
+
+Your network ID is your community's unique ID, shown in the developer portal for your community.
+
+If your community is hosted in the EU (eu-central-1), select the EU region so requests go to Bettermode's EU endpoint.""",
iconPath="/static/services/bettermode.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bettermode",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.bettermode.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (api.bettermode.de)", value="eu"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="network_id",
+ label="Network ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Bettermode returns GraphQL errors in HTTP 200 bodies; the transport re-raises
+ # them with a stable `Bettermode API error (status N)` prefix.
+ "Bettermode API error (status 401)": "Bettermode rejected the credentials. Check your client ID, client secret, and network ID, then reconnect.",
+ "Bettermode API error (status 403)": "Your Bettermode app doesn't have access to this community. Make sure the app is published and installed on the community, then reconnect.",
+ "App not found": "Bettermode couldn't find an app with this client ID. Check the client ID and client secret from the developer portal, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BettermodeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "replies":
+ return (
+ "Fetches direct replies of every post that has replies (one request per post), "
+ "so syncs scale with the number of posts in the community"
+ )
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(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: BettermodeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ is_valid, error = validate_bettermode_credentials(
+ config.region, config.client_id, config.client_secret, config.network_id
+ )
+ if is_valid:
+ return True, None
+
+ return False, error or "Invalid Bettermode credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BettermodeResumeConfig]:
+ return ResumableSourceManager[BettermodeResumeConfig](inputs, BettermodeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BettermodeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BettermodeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bettermode_source(
+ region=config.region,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ network_id=config.network_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py
new file mode 100644
index 000000000000..15d0d711d042
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode.py
@@ -0,0 +1,306 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.bettermode import (
+ BettermodeGraphQLError,
+ BettermodeResumeConfig,
+ BettermodeRetryableError,
+ _base_url,
+ _build_query,
+ _execute,
+ _format_datetime,
+ bettermode_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.settings import (
+ BETTERMODE_ENDPOINTS,
+ ENDPOINTS,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.bettermode"
+
+
+def _make_manager(resume_state: BettermodeResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = payload
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ return resp
+
+
+def _token_response(token: str = "jwt-token") -> mock.MagicMock:
+ return _response({"data": {"limitedToken": {"accessToken": token}}})
+
+
+def _page(query_field: str, nodes: list[dict[str, Any]], end_cursor: str | None = None) -> mock.MagicMock:
+ return _response(
+ {
+ "data": {
+ query_field: {
+ "pageInfo": {"endCursor": end_cursor or "cur-end", "hasNextPage": end_cursor is not None},
+ "nodes": nodes,
+ }
+ }
+ }
+ )
+
+
+def _mock_sessions(mock_make_session: mock.MagicMock, data_responses: list[mock.MagicMock]) -> tuple[Any, Any]:
+ """get_rows opens two tracked sessions: one for the token exchange, one for data."""
+ token_session = mock.MagicMock()
+ token_session.post.return_value = _token_response()
+ data_session = mock.MagicMock()
+ data_session.post.side_effect = data_responses
+ mock_make_session.side_effect = [token_session, data_session]
+ return token_session, data_session
+
+
+class TestFormatDatetime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05.000Z"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05.000Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00.000Z"),
+ ("2024-01-02T03:04:05.000Z", "2024-01-02T03:04:05.000Z"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_datetime(value) == expected
+
+
+class TestBaseUrl:
+ def test_regional_hosts(self):
+ assert _base_url("us") == "https://api.bettermode.com"
+ assert _base_url("eu") == "https://api.bettermode.de"
+
+ def test_invalid_region_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("mars")
+
+
+class TestExecute:
+ @pytest.mark.parametrize("status_code", [429, 500, 503])
+ def test_throttle_and_server_errors_are_retryable(self, status_code):
+ session = mock.MagicMock()
+ session.post.return_value = _response({}, status_code=status_code)
+
+ with pytest.raises(BettermodeRetryableError):
+ _execute(session, "https://api.bettermode.com", "query {}", {}, mock.MagicMock())
+
+ @pytest.mark.parametrize(
+ "error, expected_fragment",
+ [
+ ({"message": "Forbidden resource", "status": 403}, "Bettermode API error (status 403)"),
+ ({"message": "Unauthorized", "extensions": {"status": 401}}, "Bettermode API error (status 401)"),
+ ({"message": "App not found", "status": 404}, "App not found"),
+ ],
+ )
+ def test_graphql_errors_raise_with_stable_status_prefix(self, error, expected_fragment):
+ session = mock.MagicMock()
+ session.post.return_value = _response({"errors": [error], "data": None})
+
+ with pytest.raises(BettermodeGraphQLError) as exc_info:
+ _execute(session, "https://api.bettermode.com", "query {}", {}, mock.MagicMock())
+
+ assert expected_fragment in str(exc_info.value)
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_when_token_minted(self, mock_make_session):
+ session = mock.MagicMock()
+ session.post.return_value = _token_response()
+ mock_make_session.return_value = session
+
+ assert validate_credentials("us", "client", "secret", "net") == (True, None)
+ assert session.auth == ("client", "secret")
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_returns_api_error_message(self, mock_make_session):
+ session = mock.MagicMock()
+ session.post.return_value = _response({"errors": [{"message": "App not found", "status": 404}], "data": None})
+ mock_make_session.return_value = session
+
+ is_valid, error = validate_credentials("us", "client", "secret", "net")
+ assert is_valid is False
+ assert error is not None and "App not found" in error
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_on_network_failure(self, mock_make_session):
+ mock_make_session.return_value.post.side_effect = Exception("boom")
+
+ is_valid, error = validate_credentials("us", "client", "secret", "net")
+ assert is_valid is False
+ assert error == "Could not reach the Bettermode API"
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_via_relay_cursors(self, mock_make_session):
+ _, data_session = _mock_sessions(
+ mock_make_session,
+ [
+ _page("members", [{"id": "m1"}, {"id": "m2"}], end_cursor="cur-1"),
+ _page("members", [{"id": "m3"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("us", "client", "secret", "net", "members", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["m1", "m2", "m3"]
+ # Resume state persists only while more pages remain, and only after the yield.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].after == "cur-1"
+ second_variables = data_session.post.call_args_list[1].kwargs["json"]["variables"]
+ assert second_variables["after"] == "cur-1"
+ assert second_variables["limit"] == BETTERMODE_ENDPOINTS["members"].page_size
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_data_requests_carry_bearer_of_minted_token(self, mock_make_session):
+ _mock_sessions(mock_make_session, [_page("members", [])])
+
+ list(get_rows("us", "client", "secret", "net", "members", mock.MagicMock(), _make_manager()))
+
+ data_session_headers = mock_make_session.call_args_list[1].kwargs["headers"]
+ assert data_session_headers == {"Authorization": "Bearer jwt-token"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_make_session):
+ _, data_session = _mock_sessions(mock_make_session, [_page("members", [])])
+
+ manager = _make_manager(BettermodeResumeConfig(after="cur-resume"))
+ list(get_rows("us", "client", "secret", "net", "members", mock.MagicMock(), manager))
+
+ variables = data_session.post.call_args.kwargs["json"]["variables"]
+ assert variables["after"] == "cur-resume"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_posts_filter_is_json_encoded_gte(self, mock_make_session):
+ _, data_session = _mock_sessions(mock_make_session, [_page("posts", [])])
+
+ list(
+ get_rows(
+ "us",
+ "client",
+ "secret",
+ "net",
+ "posts",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ incremental_field="publishedAt",
+ )
+ )
+
+ variables = data_session.post.call_args.kwargs["json"]["variables"]
+ # The filter value must be a JSON-encoded ISO string — the format Bettermode expects.
+ assert variables["filterBy"] == [
+ {"key": "publishedAt", "operator": "gte", "value": '"2024-01-02T00:00:00.000Z"'}
+ ]
+ assert variables["orderBy"] == "publishedAt"
+ assert variables["reverse"] is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_full_refresh_posts_has_no_filter(self, mock_make_session):
+ _, data_session = _mock_sessions(mock_make_session, [_page("posts", [])])
+
+ list(get_rows("us", "client", "secret", "net", "posts", mock.MagicMock(), _make_manager()))
+
+ variables = data_session.post.call_args.kwargs["json"]["variables"]
+ assert "filterBy" not in variables
+ assert variables["orderBy"] == "createdAt"
+
+
+class TestRepliesFanOut:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_fans_out_only_over_posts_with_replies(self, mock_make_session):
+ _, data_session = _mock_sessions(
+ mock_make_session,
+ [
+ # Parent enumeration: p2 has no replies and must be skipped.
+ _page(
+ "posts",
+ [
+ {"id": "p1", "totalRepliesCount": 2},
+ {"id": "p2", "totalRepliesCount": 0},
+ {"id": "p3", "totalRepliesCount": 1},
+ ],
+ ),
+ _page("replies", [{"id": "r1"}], end_cursor="cur-r1"),
+ _page("replies", [{"id": "r2"}]),
+ _page("replies", [{"id": "r3"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("us", "client", "secret", "net", "replies", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["r1", "r2", "r3"]
+ reply_calls = data_session.post.call_args_list[1:]
+ assert [call.kwargs["json"]["variables"]["postId"] for call in reply_calls] == ["p1", "p1", "p3"]
+ # Mid-post page checkpoint, then a bookmark advancing to the next parent.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert [(state.after, state.post_id) for state in saved] == [("cur-r1", "p1"), (None, "p3")]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_bookmarked_post(self, mock_make_session):
+ _, data_session = _mock_sessions(
+ mock_make_session,
+ [
+ _page("posts", [{"id": "p1", "totalRepliesCount": 2}, {"id": "p3", "totalRepliesCount": 1}]),
+ _page("replies", [{"id": "r3"}]),
+ ],
+ )
+
+ manager = _make_manager(BettermodeResumeConfig(after="cur-mid", post_id="p3"))
+ list(get_rows("us", "client", "secret", "net", "replies", mock.MagicMock(), manager))
+
+ reply_calls = data_session.post.call_args_list[1:]
+ assert len(reply_calls) == 1
+ variables = reply_calls[0].kwargs["json"]["variables"]
+ assert variables["postId"] == "p3"
+ assert variables["after"] == "cur-mid"
+
+
+class TestBettermodeSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = BETTERMODE_ENDPOINTS[endpoint]
+ response = bettermode_source("us", "client", "secret", "net", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Connection ordering is undocumented — watermark commits only at run end.
+ assert response.sort_mode == "desc"
+ 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
+
+
+class TestQueryDocuments:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_query_declares_every_variable_it_passes(self, endpoint):
+ config = BETTERMODE_ENDPOINTS[endpoint]
+ query = _build_query(config)
+
+ assert f"{config.query_field}(" in query
+ for arg_name, gql_type in {"limit": "Int!", "after": "String", **config.extra_args}.items():
+ assert f"${arg_name}: {gql_type}" in query
+ assert f"{arg_name}: ${arg_name}" in query
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode_source.py
new file mode 100644
index 000000000000..27375f0c28e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bettermode/tests/test_bettermode_source.py
@@ -0,0 +1,169 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.bettermode import (
+ BettermodeResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.source import BettermodeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BettermodeSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBettermodeSource:
+ def setup_method(self):
+ self.source = BettermodeSource()
+ self.team_id = 123
+ self.config = BettermodeSourceConfig(region="us", client_id="client", client_secret="secret", network_id="net")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BETTERMODE
+
+ def test_get_source_config_ships_released(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Bettermode"
+ assert config.label == "Bettermode"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/bettermode.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["region", "client_id", "client_secret", "network_id"]
+
+ def test_region_field_is_a_select_with_default(self):
+ config = self.source.get_source_config
+ region_field = next(f for f in config.fields if f.name == "region")
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "eu"}
+
+ def test_connection_host_fields_gate_credential_retargeting(self):
+ # Removing either field lets an editor retarget the preserved client secret at a
+ # different host/community without re-entering it.
+ assert self.source.connection_host_fields == ["region", "network_id"]
+
+ def test_client_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "Bettermode API error (status 401): Unauthorized",
+ "Bettermode API error (status 403): Forbidden resource",
+ "Bettermode API error (status 404): App not found",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "Bettermode API error (retryable): status=429",
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only `posts` has a server-side timestamp filter; everything else is full refresh.
+ assert incremental == {"posts"}
+
+ def test_posts_schema_advertises_timestamp_cursors(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["posts"].incremental_fields == INCREMENTAL_FIELDS["posts"]
+ assert [f["field"] for f in schemas["posts"].incremental_fields] == ["createdAt", "publishedAt", "updatedAt"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["posts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "posts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ (
+ (False, "Bettermode API error (status 404): App not found"),
+ False,
+ "Bettermode API error (status 404): App not found",
+ ),
+ ((False, None), False, "Invalid Bettermode credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.source.validate_bettermode_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ 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("us", "client", "secret", "net")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BettermodeResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.source.bettermode_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bm_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "posts"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ inputs.incremental_field = "createdAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bm_source.assert_called_once()
+ kwargs = mock_bm_source.call_args.kwargs
+ assert kwargs["region"] == "us"
+ assert kwargs["client_id"] == "client"
+ assert kwargs["client_secret"] == "secret"
+ assert kwargs["network_id"] == "net"
+ assert kwargs["endpoint"] == "posts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+ assert kwargs["incremental_field"] == "createdAt"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bettermode.source.bettermode_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_bm_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "posts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_bm_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index e57288996203..7dc3c7cdc45e 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
@@ -533,7 +533,10 @@ class BetterStackSourceConfig(config.Config):
@config.config
class BettermodeSourceConfig(config.Config):
- pass
+ client_id: str
+ client_secret: str
+ network_id: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config