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): add Discourse source (#73192)

Tom Owers2b25a75a4815
diff --git a/frontend/public/services/discourse.png b/frontend/public/services/discourse.png
index 51d0ff540f67..493403790800 100644
Binary files a/frontend/public/services/discourse.png and b/frontend/public/services/discourse.png differ
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 fa3f9f56cd15..297a37161047 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -192,6 +192,7 @@ the row lists both.
| devin_ai | HTTP | requests | ✅ |
| ding_connect | HTTP | requests | ✅ |
| digitalocean | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| discourse | HTTP | requests + `rest_source.RESTClient` | ✅ |
| dixa | HTTP | requests | ✅ |
| dockerhub | HTTP | requests | ✅ |
| docuseal | HTTP | requests | ✅ |
@@ -871,7 +872,6 @@ doesn't conflict with concurrent PRs.
- develocity
- dialpad
- discord
-- discourse
- display_video_360
- docusign
- dodopayments
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/canonical_descriptions.py
new file mode 100644
index 000000000000..a9c345587f2f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/canonical_descriptions.py
@@ -0,0 +1,124 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "categories": {
+ "description": "A category groups related topics together, e.g. Support, Feature Requests, or Announcements.",
+ "docs_url": "https://docs.discourse.org/#tag/Categories/operation/listCategories",
+ "columns": {
+ "id": "Unique identifier for the category.",
+ "name": "Display name of the category.",
+ "slug": "URL-safe identifier for the category.",
+ "color": "Hex color used for the category badge.",
+ "text_color": "Hex color used for text on the category badge.",
+ "description": "HTML description of the category shown on the category page.",
+ "description_text": "Plain-text version of the category description.",
+ "topic_count": "Number of topics currently in the category.",
+ "post_count": "Number of posts currently in the category.",
+ "position": "Display order of the category relative to its siblings.",
+ "parent_category_id": "id of the parent category, if this is a subcategory.",
+ "read_restricted": "Whether the category is only visible to specific groups.",
+ "topic_url": 'Path to the category\'s pinned "about this category" topic.',
+ },
+ },
+ "topics": {
+ "description": "A discussion thread. Returned from the site's latest-activity topic list, so it covers every topic that has had activity.",
+ "docs_url": "https://docs.discourse.org/#tag/Topics/operation/listLatestTopics",
+ "columns": {
+ "id": "Unique identifier for the topic.",
+ "title": "Topic title.",
+ "fancy_title": "Title with Markdown/emoji rendered to HTML entities.",
+ "slug": "URL-safe identifier for the topic.",
+ "posts_count": "Number of posts (replies + original post) in the topic.",
+ "reply_count": "Number of replies to the original post.",
+ "highest_post_number": "Post number of the most recent post in the topic.",
+ "created_at": "When the topic was created.",
+ "last_posted_at": "When the most recent post in the topic was made.",
+ "bumped_at": "When the topic was last bumped to the top of its list.",
+ "archetype": 'Topic type, e.g. "regular" or "private_message".',
+ "pinned": "Whether the topic is pinned within its category.",
+ "pinned_globally": "Whether the topic is pinned across the whole site.",
+ "visible": "Whether the topic is visible (unlisted topics are hidden from lists).",
+ "closed": "Whether new replies are disallowed.",
+ "archived": "Whether the topic has been archived (read-only).",
+ "views": "Number of times the topic has been viewed.",
+ "like_count": "Total number of likes across all posts in the topic.",
+ "category_id": "id of the category this topic belongs to.",
+ "last_poster_username": "Username of the most recent poster.",
+ },
+ },
+ "posts": {
+ "description": "A single post (the original post or a reply) within a topic, from the site-wide post stream.",
+ "docs_url": "https://docs.discourse.org/#tag/Posts/operation/listPosts",
+ "columns": {
+ "id": "Unique identifier for the post.",
+ "topic_id": "id of the topic this post belongs to.",
+ "topic_slug": "URL-safe identifier of the parent topic.",
+ "topic_title": "Title of the parent topic at fetch time.",
+ "post_number": "1-based position of the post within its topic.",
+ "user_id": "id of the user who authored the post.",
+ "username": "Username of the post's author.",
+ "cooked": "Rendered HTML body of the post.",
+ "raw": "Raw Markdown source of the post body, when available.",
+ "created_at": "When the post was created.",
+ "updated_at": "When the post was last edited.",
+ "reply_count": "Number of direct replies to this post.",
+ "reply_to_post_number": "Post number this post is a direct reply to, if any.",
+ "category_id": "id of the category the parent topic belongs to.",
+ "like_count": "Number of likes this post has received (also under actions_summary).",
+ "hidden": "Whether the post has been hidden (e.g. by flags).",
+ "deleted_at": "When the post was deleted, if applicable.",
+ "wiki": "Whether the post is editable by any trusted user (a wiki post).",
+ },
+ },
+ "tags": {
+ "description": "A tag that can be applied to topics to aid discovery and filtering.",
+ "docs_url": "https://docs.discourse.org/#tag/Tags/operation/listTags",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "name": "Tag name as it appears on topics.",
+ "text": "Display text of the tag (usually equal to name).",
+ "description": "Optional description of what the tag means.",
+ "count": "Number of topics currently carrying this tag.",
+ "pm_only": "Whether the tag can only be applied to personal messages.",
+ "target_tag": "The canonical tag this tag is a synonym for, if any.",
+ },
+ },
+ "groups": {
+ "description": "A user group, used for permissions, mentions, and messaging.",
+ "docs_url": "https://docs.discourse.org/#tag/Groups/operation/listGroups",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "Internal group name (used in @mentions and URLs).",
+ "full_name": "Human-readable display name of the group.",
+ "user_count": "Number of members in the group.",
+ "automatic": "Whether the group is system-managed (e.g. Trust Level groups) rather than user-created.",
+ "visibility_level": "Who can see the group: 0 public, 1 logged-in users, 2 members/owners, 3 staff.",
+ "public_admission": "Whether users can join the group without approval.",
+ "public_exit": "Whether users can leave the group without approval.",
+ "bio_cooked": "Rendered HTML of the group's bio/description.",
+ },
+ },
+ "users": {
+ "description": "A forum member and their aggregate activity stats, from the public user directory leaderboard.",
+ "docs_url": "https://docs.discourse.org/#tag/Users/operation/listUserDirectoryItems",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "username": "The user's unique username.",
+ "name": "The user's display name.",
+ "admin": "Whether the user has admin (staff) access.",
+ "trust_level": "Discourse trust level, 0 (new) through 4 (leader).",
+ "title": "The user's custom title, if any (often granted by a group).",
+ "likes_received": "Total number of likes this user's posts have received.",
+ "likes_given": "Total number of likes this user has given to other posts.",
+ "topic_count": "Number of topics this user has created.",
+ "post_count": "Number of posts this user has made.",
+ "topics_entered": "Number of distinct topics this user has viewed.",
+ "posts_read": "Number of posts this user has read.",
+ "days_visited": "Number of distinct days this user has visited the forum.",
+ "solutions": "Number of accepted-answer posts this user has authored.",
+ "time_read": "Total time (in seconds) this user has spent reading.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/discourse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/discourse.py
new file mode 100644
index 000000000000..5dfefc1f1f67
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/discourse.py
@@ -0,0 +1,377 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+import requests
+from requests import PreparedRequest, Request, Response
+
+from posthog.cloud_utils import is_cloud
+
+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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ Endpoint,
+ EndpointResource,
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.settings import (
+ DISCOURSE_ENDPOINTS,
+ POSTS_PAGE_SIZE,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+HOST_NOT_ALLOWED_ERROR = "Discourse instance URL is not allowed"
+
+
+class DiscourseHostNotAllowedError(Exception):
+ pass
+
+
+class DiscourseResumeConfig:
+ # Next page to fetch for `PageNumberPaginator`-based endpoints (topics, groups, users).
+ page: Optional[int] = None
+ # Next `before=<post_id>` cursor for the posts endpoint's descending id walk.
+ before: Optional[int] = None
+
+
+def normalize_base_url(base_url: str) -> str:
+ url = base_url.strip()
+ if url and "://" not in url:
+ url = f"https://{url}"
+ return url.rstrip("/")
+
+
+def _validated_hostname(base_url: str) -> Optional[str]:
+ """Hostname of the normalized instance URL, or None when the URL is malformed or ambiguous.
+
+ SSRF guard: urlparse treats a backslash as ordinary userinfo and an "@" as a userinfo
+ separator, but urllib3/requests treat the backslash as an authority separator, so
+ `https://127.0.0.1\\@example.com` validates as example.com yet connects to 127.0.0.1. A
+ legitimate instance URL has no userinfo, so reject either construct outright.
+ """
+ if "\\" in base_url or "%5c" in base_url.lower():
+ return None
+ parsed = urlparse(base_url)
+ if parsed.scheme not in ("http", "https") or "@" in parsed.netloc:
+ return None
+ # The API key rides in a header on every request, so plaintext http would leak it to any
+ # network observer once it egresses over the public internet. Self-hosted operators control
+ # their own network path, so http stays allowed there (mirrors Unleash/Gitea).
+ if parsed.scheme == "http" and is_cloud():
+ return None
+ hostname = parsed.hostname
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return None
+ return hostname
+
+
+def hostname_of(base_url: str) -> Optional[str]:
+ return _validated_hostname(normalize_base_url(base_url))
+
+
+def _check_host(base_url: str, team_id: int) -> None:
+ hostname = hostname_of(base_url)
+ if not hostname:
+ raise DiscourseHostNotAllowedError("Invalid Discourse instance URL")
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ raise DiscourseHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+
+class DiscourseAuth(AuthConfigBase):
+ """Discourse's admin API auth: `Api-Key` + `Api-Username` headers (no Bearer/Basic scheme).
+
+ Query-param auth (`?api_key=`) was removed by Discourse in 2020, so header auth is the only
+ supported method — no built-in framework auth type carries two header values, hence this
+ custom auth class.
+ """
+
+ def __init__(self, api_key: str, api_username: str) -> None:
+ self.api_key = api_key
+ self.api_username = api_username
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ request.headers["Api-Key"] = self.api_key
+ request.headers["Api-Username"] = self.api_username
+ return request
+
+ def secret_values(self) -> tuple[str, ...]:
+ return (self.api_key,) if self.api_key else ()
+
+
+class DiscoursePostsPaginator(BasePaginator):
+ """Cursor paginator for `/posts.json`, walking backward via `before=<post_id>`.
+
+ Discourse's global post firehose returns posts newest-first with no `since`/`after` filter,
+ so an incremental sync instead walks backward from the newest post and stops once a whole
+ page is at or before the last-synced post id (the watermark) — otherwise every incremental
+ sync would re-walk the full post history. A full-refresh sync (no watermark) walks all the
+ way back until a page comes back shorter than the fixed page size.
+ """
+
+ def __init__(self, stop_at_or_before: Optional[int] = None) -> None:
+ super().__init__()
+ self._before: Optional[int] = None
+ self._stop_at_or_before = stop_at_or_before
+
+ def init_request(self, request: Request) -> None:
+ if self._before is not None:
+ if request.params is None:
+ request.params = {}
+ request.params["before"] = self._before
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data:
+ self._has_next_page = False
+ return
+
+ ids = [item["id"] for item in data if isinstance(item, dict) and isinstance(item.get("id"), int)]
+ if not ids:
+ self._has_next_page = False
+ return
+
+ oldest_in_page = min(ids)
+ self._before = oldest_in_page
+ self._has_next_page = len(data) >= POSTS_PAGE_SIZE
+
+ if self._has_next_page and self._stop_at_or_before is not None and oldest_in_page <= self._stop_at_or_before:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ if self._before is not None:
+ if request.params is None:
+ request.params = {}
+ request.params["before"] = self._before
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"before": self._before} if self._has_next_page and self._before is not None else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ before = state.get("before")
+ if before is not None:
+ self._before = int(before)
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"DiscoursePostsPaginator(before={self._before}, stop_at_or_before={self._stop_at_or_before})"
+
+
+def _flatten_directory_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Lift the nested `user` object's fields onto the row so the users table isn't a blob column.
+
+ The outer `id` already equals `user.id`, so the nested copy is dropped rather than
+ overwriting the (identical) outer value.
+ """
+ user = item.pop("user", None)
+ if isinstance(user, dict):
+ for key, value in user.items():
+ if key == "id":
+ continue
+ item[key] = value
+ return item
+
+
+def _coerce_incremental_cursor(value: Any) -> Optional[int]:
+ if value is None:
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def discourse_source(
+ base_url: str,
+ api_key: str,
+ api_username: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DiscourseResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ endpoint_config = DISCOURSE_ENDPOINTS[endpoint]
+ normalized_base_url = normalize_base_url(base_url)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state: Optional[dict[str, Any]] = None
+
+ if endpoint == "posts":
+ watermark = (
+ _coerce_incremental_cursor(db_incremental_field_last_value) if should_use_incremental_field else None
+ )
+ paginator: BasePaginator = DiscoursePostsPaginator(stop_at_or_before=watermark)
+ if resume_config is not None and resume_config.before is not None:
+ initial_paginator_state = {"before": resume_config.before}
+ elif endpoint_config.paginated:
+ paginator = PageNumberPaginator(base_page=0, page_param="page")
+ if resume_config is not None and resume_config.page is not None:
+ initial_paginator_state = {"page": resume_config.page}
+ else:
+ paginator = SinglePagePaginator()
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion. Save AFTER a page is yielded (see caller) so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ if not state:
+ return
+ resumable_source_manager.save_state(DiscourseResumeConfig(page=state.get("page"), before=state.get("before")))
+
+ endpoint_dict: Endpoint = {
+ "path": endpoint_config.path,
+ "data_selector": endpoint_config.data_selector,
+ # A 200 whose body isn't the expected list shape is treated as a transient glitch and
+ # retried, rather than silently syncing 0 rows.
+ "data_selector_malformed_retryable": True,
+ "paginator": paginator,
+ }
+ if endpoint_config.extra_params:
+ endpoint_dict["params"] = dict(endpoint_config.extra_params)
+
+ write_disposition: Any = "replace"
+ if endpoint_config.incremental_fields:
+ write_disposition = (
+ {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"
+ )
+
+ resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": endpoint_dict,
+ "write_disposition": write_disposition,
+ "table_format": "delta",
+ }
+ if endpoint == "users":
+ # `data_map` is a resource-level key (applied after data_selector, before type
+ # coercion) — not an `endpoint` key.
+ resource["data_map"] = _flatten_directory_item
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": normalized_base_url,
+ "auth": DiscourseAuth(api_key=api_key, api_username=api_username),
+ # The instance URL is user-supplied: pin every request (including pagination) to the
+ # base host and refuse redirects so the credentialed request can't be bounced off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ # Bound every sync request so a host that accepts the connection then stalls can't hold
+ # an import worker indefinitely (the credential probe is already bounded separately).
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ },
+ "resource_defaults": {},
+ "resources": [resource],
+ }
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ # Re-checked at run time (not just at source-create) in case the instance URL was edited
+ # or now resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ _check_host(base_url, team_id)
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ # Incremental filtering is handled by the paginator's own watermark (there is no
+ # declarative `incremental` param on the endpoint — Discourse has no server-side
+ # since-filter to plug into it), so nothing needs to flow through this framework arg.
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ for batch in resource:
+ if batch:
+ yield batch
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1 if endpoint_config.partition_key else None,
+ partition_size=1 if endpoint_config.partition_key else None,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def _get_session(api_key: str, api_username: str) -> requests.Session:
+ # The instance URL is user-supplied, so pin redirects off so host validation and the
+ # outbound request stay on the same target (SSRF defense-in-depth). Redact the key from logs.
+ return make_tracked_session(
+ headers={"Api-Key": api_key, "Api-Username": api_username, "Accept": "application/json"},
+ redact_values=(api_key,),
+ allow_redirects=False,
+ )
+
+
+def _error_message(response: requests.Response) -> Optional[str]:
+ try:
+ body = response.json()
+ if isinstance(body, dict) and isinstance(body.get("errors"), list) and body["errors"]:
+ first = body["errors"][0]
+ if isinstance(first, str):
+ return first
+ except Exception:
+ pass
+ return None
+
+
+def validate_credentials(
+ base_url: str,
+ api_key: str,
+ api_username: str,
+ schema_name: Optional[str] = None,
+ team_id: Optional[int] = None,
+) -> tuple[bool, Optional[str]]:
+ """Probe `/session/current.json` to confirm the key/username pair is genuine.
+
+ At source-create (`schema_name is None`) a 403 is accepted: a scoped API key may not cover
+ this particular probe endpoint even though it's valid for the tables the user wants to sync.
+ A scoped probe (`schema_name` set) treats 403 as a hard failure.
+ """
+ normalized_base_url = normalize_base_url(base_url)
+ hostname = _validated_hostname(normalized_base_url)
+ if not hostname:
+ return False, "Invalid Discourse instance URL"
+
+ # The instance URL is fully customer-controlled, so block hosts that resolve to private/
+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ session = _get_session(api_key, api_username)
+ try:
+ # The session never follows redirects: the validated host could 3xx to an internal
+ # address, defeating the host check above (SSRF).
+ response = session.get(f"{normalized_base_url}/session/current.json", timeout=REQUEST_TIMEOUT_SECONDS)
+ except requests.exceptions.RequestException as e:
+ return False, f"Could not connect to Discourse: {e}"
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, _error_message(response) or "Your Discourse API key does not have the required permissions"
+
+ return False, _error_message(response) or f"Discourse returned HTTP {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/settings.py
new file mode 100644
index 000000000000..1f278d14d214
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/settings.py
@@ -0,0 +1,98 @@
+from dataclasses import dataclass, field
+from typing import Any, Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Verified against a live instance (meta.discourse.org): /latest.json returns 30 topics/page,
+# /groups.json returns 20/page, /directory_items.json returns 50/page — all terminate on the
+# first short/empty page, so no fixed size is needed for those. /posts.json is fixed at 50 and
+# never signals a total, so its cursor paginator needs the page size to decide "last page".
+POSTS_PAGE_SIZE = 50
+
+
+@dataclass
+class DiscourseEndpointConfig:
+ name: str
+ path: str
+ # jsonpath into the response body where the list of records lives.
+ data_selector: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # False for endpoints that return their entire collection in one response (verified live —
+ # re-requesting categories.json/tags.json with a page param returns the identical full list).
+ paginated: bool = False
+ # The order rows actually arrive in. Posts return newest-first with no sort override
+ # accepted alongside `before` cursor pagination (verified live); every other endpoint here
+ # has no incremental field so ordering doesn't affect a watermark.
+ sort_mode: Literal["asc", "desc"] = "asc"
+ # A stable, never-changing datetime field to partition on. None disables partitioning.
+ partition_key: Optional[str] = None
+ # Extra static query params merged into every request (e.g. directory_items' required period).
+ extra_params: dict[str, Any] = field(default_factory=dict)
+
+
+# Discourse Admin API endpoints. Only `posts` has a reliable incremental cursor (a monotonic
+# post id, walked backward via `?before=`) — every other list endpoint here has no server-side
+# `updated_since`/`created_after` filter, so they stay full refresh (see incrementalSupport
+# research notes: topics/users expose timestamps but no since filter).
+DISCOURSE_ENDPOINTS: dict[str, DiscourseEndpointConfig] = {
+ "categories": DiscourseEndpointConfig(
+ name="categories",
+ path="/categories.json",
+ # Bare key (not `[*]`): a `[*]` wildcard over an empty array matches nothing, which
+ # `data_selector_malformed_retryable` would then treat as a malformed body and retry
+ # forever instead of recognizing a legitimate empty/terminal page.
+ data_selector="category_list.categories",
+ paginated=False,
+ ),
+ "topics": DiscourseEndpointConfig(
+ name="topics",
+ path="/latest.json",
+ data_selector="topic_list.topics",
+ paginated=True,
+ partition_key="created_at",
+ ),
+ "posts": DiscourseEndpointConfig(
+ name="posts",
+ path="/posts.json",
+ data_selector="latest_posts",
+ incremental_fields=[
+ {
+ "label": "id",
+ "type": IncrementalFieldType.Integer,
+ "field": "id",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ],
+ paginated=True,
+ sort_mode="desc",
+ partition_key="created_at",
+ ),
+ "tags": DiscourseEndpointConfig(
+ name="tags",
+ path="/tags.json",
+ data_selector="tags",
+ paginated=False,
+ ),
+ "groups": DiscourseEndpointConfig(
+ name="groups",
+ path="/groups.json",
+ data_selector="groups",
+ paginated=True,
+ ),
+ "users": DiscourseEndpointConfig(
+ name="users",
+ path="/directory_items.json",
+ data_selector="directory_items",
+ # `period` is required (the endpoint 400s without it); `order` just needs to be a stable
+ # choice so page boundaries don't shift between requests.
+ extra_params={"period": "all", "order": "likes_received"},
+ paginated=True,
+ ),
+}
+
+ENDPOINTS = tuple(DISCOURSE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DISCOURSE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/source.py
index 0eb954649beb..86f92227537f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/source.py
@@ -1,13 +1,37 @@
-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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.discourse import (
+ DiscourseResumeConfig,
+ discourse_source,
+ validate_credentials as validate_discourse_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.discourse import (
DiscourseSourceConfig,
)
@@ -15,18 +39,120 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DiscourseSource(SimpleSource[DiscourseSourceConfig]):
+class DiscourseSource(ResumableSource[DiscourseSourceConfig, DiscourseResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ api_docs_url = "https://docs.discourse.org"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DISCOURSE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `base_url` is where the stored API key is sent, and `api_username` selects the identity an
+ # All Users key acts as — retargeting either while the key is preserved must re-require the key.
+ return ["base_url", "api_username"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DISCOURSE,
category=DataWarehouseSourceCategory.COMMUNICATION,
label="Discourse",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["forum", "community"],
+ caption="""Connect your Discourse community forum to sync categories, topics, posts, tags, groups, and user stats into the PostHog Data warehouse.
+
+Generate an Admin API key under **Admin > API > Keys** on your Discourse instance (a key scoped to "Global" access, or scoped to read the tables below, both work). The instance URL is your forum's address, e.g. `https://yourforum.discourse.group`.""",
iconPath="/static/services/discourse.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/discourse",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://yourforum.discourse.group",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Admin API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="api_username",
+ label="API username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="system",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "403 Client Error": "Your Discourse API key or username is invalid, or does not have permission to access this resource. Please check the key and username and reconnect.",
+ "invalid_access": "Your Discourse API key or username is invalid, or does not have permission to access this resource. Please check the key and username and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: DiscourseSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: DiscourseSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_discourse_credentials(
+ config.base_url, config.api_key, config.api_username, schema_name, team_id
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DiscourseResumeConfig]:
+ return ResumableSourceManager[DiscourseResumeConfig](inputs, DiscourseResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DiscourseSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DiscourseResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Discourse schema '{inputs.schema_name}'")
+
+ return discourse_source(
+ base_url=config.base_url,
+ api_key=config.api_key,
+ api_username=config.api_username,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse.py
new file mode 100644
index 000000000000..b7b27c64ae8e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse.py
@@ -0,0 +1,537 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse import discourse
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.discourse import (
+ POSTS_PAGE_SIZE,
+ DiscourseHostNotAllowedError,
+ DiscoursePostsPaginator,
+ DiscourseResumeConfig,
+ _flatten_directory_item,
+ discourse_source,
+ hostname_of,
+ normalize_base_url,
+ validate_credentials,
+)
+
+# RESTClient builds its pipeline session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# The runtime host-safety guard resolves DNS; patch it so pipeline tests don't hit the network.
+IS_HOST_SAFE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.discourse.discourse._is_host_safe"
+)
+
+BASE_URL = "https://forum.example.com"
+API_KEY = "secret-key"
+API_USERNAME = "system"
+
+
+def _post(post_id: int) -> dict[str, Any]:
+ return {"id": post_id, "topic_id": 1, "raw": f"post {post_id}"}
+
+
+def _json_response(body: Any, *, status_code: int = 200, location: Optional[str] = None) -> requests.Response:
+ """A real requests.Response so the framework's status/redirect/parse handling behaves as in prod."""
+ resp = requests.Response()
+ resp.status_code = status_code
+ resp.url = f"{BASE_URL}/probe"
+ resp.reason = "OK" if status_code < 400 else "Error"
+ if location is not None:
+ resp.headers["Location"] = location
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _mock_response(status_code: int = 200, json_data: Any = None, is_redirect: bool = False) -> MagicMock:
+ """MagicMock response for the validate_credentials probe helper."""
+ response = MagicMock(spec=requests.Response)
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.is_redirect = is_redirect
+ response.is_permanent_redirect = False
+ response.json.return_value = json_data
+ response.text = str(json_data)
+ return response
+
+
+def _make_manager(resume_state: Optional[DiscourseResumeConfig] = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: MagicMock, responses: list[requests.Response]) -> list[dict[str, Any]]:
+ """Wire a mock session, snapshotting each request's params AT SEND TIME.
+
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
+ run shows only the final state — snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ prepared = MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _source(
+ manager: MagicMock,
+ endpoint: str,
+ *,
+ base_url: str = BASE_URL,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Any:
+ return discourse_source(
+ base_url=base_url,
+ api_key=API_KEY,
+ api_username=API_USERNAME,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
+class TestNormalizeAndHostname:
+ @parameterized.expand(
+ [
+ ("plain", "https://forum.example.com", "https://forum.example.com"),
+ ("trailing_slash", "https://forum.example.com/", "https://forum.example.com"),
+ ("no_scheme", "forum.example.com", "https://forum.example.com"),
+ ("whitespace", " https://forum.example.com ", "https://forum.example.com"),
+ ]
+ )
+ def test_normalize_base_url(self, _name: str, raw: str, expected: str) -> None:
+ assert normalize_base_url(raw) == expected
+
+ def test_hostname_of(self) -> None:
+ assert hostname_of("https://forum.example.com/") == "forum.example.com"
+
+ @parameterized.expand(
+ [
+ ("blank", " "),
+ ("bad_scheme", "ftp://forum.example.com"),
+ ("userinfo", "https://[email protected]"),
+ ("backslash", "https://169.254.169.254\\@forum.example.com"),
+ ("encoded_backslash", "https://169.254.169.254%[email protected]"),
+ ]
+ )
+ def test_hostname_of_rejects_malformed_or_ambiguous_urls(self, _name: str, raw_url: str) -> None:
+ assert hostname_of(raw_url) is None
+
+
+class TestFlattenDirectoryItem:
+ def test_lifts_user_fields_and_drops_duplicate_id(self) -> None:
+ item = {
+ "id": 32,
+ "post_count": 10,
+ "user": {"id": 32, "username": "codinghorror", "name": "Jeff Atwood", "admin": True},
+ }
+ flattened = _flatten_directory_item(item)
+ assert flattened == {
+ "id": 32,
+ "post_count": 10,
+ "username": "codinghorror",
+ "name": "Jeff Atwood",
+ "admin": True,
+ }
+
+ def test_missing_user_key_is_a_noop(self) -> None:
+ item = {"id": 1, "post_count": 5}
+ assert _flatten_directory_item(item) == {"id": 1, "post_count": 5}
+
+
+class TestDiscoursePostsPaginator:
+ def test_full_refresh_stops_on_short_page(self) -> None:
+ paginator = DiscoursePostsPaginator(stop_at_or_before=None)
+ response = _json_response({"latest_posts": [_post(i) for i in range(10, 5, -1)]})
+ paginator.update_state(response, data=[_post(i) for i in range(10, 5, -1)])
+ assert paginator.has_next_page is False
+
+ def test_full_refresh_continues_on_full_page(self) -> None:
+ paginator = DiscoursePostsPaginator(stop_at_or_before=None)
+ data = [_post(i) for i in range(POSTS_PAGE_SIZE, 0, -1)]
+ paginator.update_state(_json_response({"latest_posts": data}), data=data)
+ assert paginator.has_next_page is True
+ assert paginator._before == 1
+
+ def test_stops_at_watermark_within_first_page(self) -> None:
+ # Watermark 80 falls inside the first (newest) page, so the incremental sync should
+ # stop immediately rather than walking further back through already-synced posts.
+ paginator = DiscoursePostsPaginator(stop_at_or_before=80)
+ data = [_post(i) for i in range(129, 79, -1)] # ids 129..80, 50 items
+ assert len(data) == POSTS_PAGE_SIZE
+ paginator.update_state(_json_response({"latest_posts": data}), data=data)
+ assert paginator.has_next_page is False
+
+ def test_empty_page_stops(self) -> None:
+ paginator = DiscoursePostsPaginator(stop_at_or_before=None)
+ paginator.update_state(_json_response({"latest_posts": []}), data=[])
+ assert paginator.has_next_page is False
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = DiscoursePostsPaginator()
+ data = [_post(i) for i in range(POSTS_PAGE_SIZE, 0, -1)]
+ paginator.update_state(_json_response({"latest_posts": data}), data=data)
+ state = paginator.get_resume_state()
+ assert state == {"before": 1}
+
+ resumed = DiscoursePostsPaginator()
+ assert state is not None
+ resumed.set_resume_state(state)
+ assert resumed._before == 1
+ assert resumed.has_next_page is True
+
+
+class TestPipelineTransport:
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_unpaginated_endpoint_fetches_once(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [_json_response({"category_list": {"categories": [{"id": 1, "name": "General"}, {"id": 2}]}})],
+ )
+
+ rows = _rows(_source(_make_manager(), "categories"))
+ assert rows == [{"id": 1, "name": "General"}, {"id": 2}]
+ assert session.send.call_count == 1
+ assert params[0] == {}
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_topics_paginates_and_stops_on_empty_page(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ page1 = [{"id": i} for i in range(30)]
+ params = _wire(
+ session,
+ [
+ _json_response({"topic_list": {"topics": page1}}),
+ _json_response({"topic_list": {"topics": []}}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager, "topics"))
+ assert rows == page1
+ assert [p["page"] for p in params] == [0, 1]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == DiscourseResumeConfig(page=1, before=None)
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_topics_terminates_on_empty_page_even_after_a_short_page(self, MockSession: Any, _safe: Any) -> None:
+ # PageNumberPaginator only stops on a genuinely empty page (verified live against
+ # meta.discourse.org: the API keeps returning 200 with an empty list well past the last
+ # real page rather than a short final page), so a single non-empty short page still
+ # triggers one more request before termination.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _json_response({"topic_list": {"topics": [{"id": 1}]}}),
+ _json_response({"topic_list": {"topics": []}}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager, "topics"))
+ assert rows == [{"id": 1}]
+ assert session.send.call_count == 2
+ manager.save_state.assert_called_once()
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_topics_resumes_from_saved_page(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _json_response({"topic_list": {"topics": [{"id": 99}]}}),
+ _json_response({"topic_list": {"topics": []}}),
+ ],
+ )
+
+ manager = _make_manager(DiscourseResumeConfig(page=3))
+ rows = _rows(_source(manager, "topics"))
+ assert rows == [{"id": 99}]
+ assert [p["page"] for p in params] == [3, 4]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_users_flattens_nested_user_object(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _json_response(
+ {"directory_items": [{"id": 32, "post_count": 10, "user": {"id": 32, "username": "codinghorror"}}]}
+ ),
+ _json_response({"directory_items": []}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "users"))
+ assert rows == [{"id": 32, "post_count": 10, "username": "codinghorror"}]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_users_sends_required_static_params(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_json_response({"directory_items": []})])
+
+ _rows(_source(_make_manager(), "users"))
+ assert params[0]["period"] == "all"
+ assert params[0]["order"] == "likes_received"
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_posts_full_refresh_walks_backward_via_before_cursor(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ page1 = [_post(i) for i in range(POSTS_PAGE_SIZE, 0, -1)]
+ page2 = [_post(i) for i in range(0, -3, -1)]
+ params = _wire(
+ session,
+ [
+ _json_response({"latest_posts": page1}),
+ _json_response({"latest_posts": page2}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager, "posts"))
+ assert rows == page1 + page2
+ assert "before" not in params[0]
+ assert params[1]["before"] == 1
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == DiscourseResumeConfig(page=None, before=1)
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_posts_incremental_stops_at_watermark(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ page1 = [_post(i) for i in range(129, 79, -1)] # ids 129..80
+ _wire(session, [_json_response({"latest_posts": page1})])
+
+ rows = _rows(
+ _source(_make_manager(), "posts", should_use_incremental_field=True, db_incremental_field_last_value=80)
+ )
+ assert rows == page1
+ assert session.send.call_count == 1
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_posts_resumes_from_saved_before_cursor(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_json_response({"latest_posts": [_post(5)]})])
+
+ manager = _make_manager(DiscourseResumeConfig(before=500))
+ rows = _rows(_source(manager, "posts"))
+ assert rows == [_post(5)]
+ assert params[0]["before"] == 500
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_auth_headers_sent_without_bearer_or_basic_scheme(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ captured_auth: list[Any] = []
+
+ def _prepare(request: Any) -> MagicMock:
+ captured_auth.append(request.auth)
+ prepared = MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [_json_response({"category_list": {"categories": []}})]
+
+ _rows(_source(_make_manager(), "categories"))
+
+ prepared_request = requests.Request(method="GET", url=BASE_URL).prepare()
+ captured_auth[0](prepared_request)
+ assert prepared_request.headers["Api-Key"] == API_KEY
+ assert prepared_request.headers["Api-Username"] == API_USERNAME
+ assert "Authorization" not in prepared_request.headers
+
+ def test_blocks_unsafe_hosts(self) -> None:
+ with patch(IS_HOST_SAFE_PATCH, return_value=(False, "blocked")):
+ with pytest.raises(DiscourseHostNotAllowedError):
+ _rows(_source(_make_manager(), "categories", base_url="https://10.0.0.1"))
+
+ def test_blocks_ambiguous_url(self) -> None:
+ with pytest.raises(DiscourseHostNotAllowedError):
+ _rows(_source(_make_manager(), "categories", base_url="https://169.254.169.254\\@forum.example.com"))
+
+ @parameterized.expand(
+ [
+ ("categories", ["id"]),
+ ("topics", ["id"]),
+ ("posts", ["id"]),
+ ("tags", ["id"]),
+ ("groups", ["id"]),
+ ("users", ["id"]),
+ ]
+ )
+ def test_source_returns_declared_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = _source(_make_manager(), endpoint)
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+
+ def test_posts_sort_mode_is_descending(self) -> None:
+ assert _source(_make_manager(), "posts").sort_mode == "desc"
+
+ @parameterized.expand([("categories",), ("tags",), ("groups",), ("users",), ("topics",)])
+ def test_non_post_endpoints_sort_mode_is_ascending(self, endpoint: str) -> None:
+ assert _source(_make_manager(), endpoint).sort_mode == "asc"
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_posts_write_disposition_is_merge_when_incremental(self, MockSession: Any, _safe: Any) -> None:
+ # Verified indirectly: an incremental sync only re-fetches until the watermark, so a
+ # merge (not replace) write disposition is required to avoid dropping older rows. This
+ # is asserted through the resource's resume/merge-relevant behavior rather than digging
+ # into the framework's internal write_disposition config.
+ session = MockSession.return_value
+ _wire(session, [_json_response({"latest_posts": [_post(1)]})])
+ rows = _rows(
+ _source(_make_manager(), "posts", should_use_incremental_field=True, db_incremental_field_last_value=0)
+ )
+ assert rows == [_post(1)]
+
+
+class TestErrorHandling:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("unavailable", 503)])
+ @patch("tenacity.nap.time.sleep")
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_retryable_statuses_are_retried_then_succeed(
+ self, _name: str, status: int, MockSession: Any, _safe: Any, _sleep: Any
+ ) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _json_response({}, status_code=status),
+ _json_response({"category_list": {"categories": [{"id": 1}]}}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "categories"))
+ assert rows == [{"id": 1}]
+ assert session.send.call_count == 2
+
+ @patch("tenacity.nap.time.sleep")
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_persistent_server_error_exhausts_retries(self, MockSession: Any, _safe: Any, _sleep: Any) -> None:
+ session = MockSession.return_value
+ _wire(session, [_json_response({}, status_code=500)] * 5)
+
+ with pytest.raises(RESTClientRetryableError):
+ _rows(_source(_make_manager(), "categories"))
+ assert session.send.call_count == 5
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_permanent_statuses_raise_http_error(self, _name: str, status: int, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ _wire(session, [_json_response({"errors": ["nope"]}, status_code=status)])
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source(_make_manager(), "categories"))
+
+ @parameterized.expand([("moved", 301), ("found", 302), ("temporary", 307)])
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_redirects_are_refused(self, _name: str, status: int, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ _wire(session, [_json_response({}, status_code=status, location="https://evil.example.com")])
+
+ with pytest.raises(ValueError, match="[Rr]edirect"):
+ _rows(_source(_make_manager(), "categories"))
+
+
+class TestValidateCredentials:
+ def _validate(self, monkeypatch: Any, response: MagicMock, schema_name: Optional[str] = None) -> tuple:
+ session = MagicMock()
+ session.get.return_value = response
+ monkeypatch.setattr(discourse, "make_tracked_session", lambda **kwargs: session)
+ monkeypatch.setattr(discourse, "_is_host_safe", lambda host, team_id: (True, None))
+ return validate_credentials(BASE_URL, API_KEY, API_USERNAME, schema_name=schema_name, team_id=1)
+
+ def test_validate_credentials_success(self, monkeypatch: Any) -> None:
+ assert self._validate(monkeypatch, _mock_response(200, {"current_user": {"id": 1}})) == (True, None)
+
+ def test_validate_credentials_rejects_403_for_scoped_probe(self, monkeypatch: Any) -> None:
+ body = {"errors": ["The API username or key is invalid."], "error_type": "invalid_access"}
+ valid, message = self._validate(monkeypatch, _mock_response(403, body), schema_name="posts")
+ assert valid is False
+ assert message == "The API username or key is invalid."
+
+ def test_validate_credentials_accepts_403_at_source_create(self, monkeypatch: Any) -> None:
+ # A scoped API key may not cover the /session/current.json probe even though it's valid
+ # for the tables the user actually wants to sync — source creation must still go through.
+ body = {"errors": ["The API username or key is invalid."], "error_type": "invalid_access"}
+ assert self._validate(monkeypatch, _mock_response(403, body)) == (True, None)
+
+ def test_validate_credentials_rejects_redirects(self, monkeypatch: Any) -> None:
+ valid, _ = self._validate(monkeypatch, _mock_response(200, {}, is_redirect=True))
+ assert valid is False
+
+ def test_validate_credentials_rejects_unsafe_host(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(discourse, "_is_host_safe", lambda host, team_id: (False, "blocked"))
+ valid, message = validate_credentials(BASE_URL, API_KEY, API_USERNAME, team_id=1)
+ assert valid is False
+ assert message == "blocked"
+
+ @parameterized.expand(
+ [
+ ("blank", " "),
+ ("bad_scheme", "ftp://forum.example.com"),
+ ("userinfo", "https://[email protected]"),
+ ("backslash", "https://169.254.169.254\\@forum.example.com"),
+ ]
+ )
+ def test_validate_credentials_rejects_malformed_or_ambiguous_urls(self, _name: str, raw_url: str) -> None:
+ valid, message = validate_credentials(raw_url, API_KEY, API_USERNAME, team_id=1)
+ assert valid is False
+ assert message == "Invalid Discourse instance URL"
+
+ def test_validate_credentials_handles_connection_errors(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ monkeypatch.setattr(discourse, "make_tracked_session", lambda **kwargs: session)
+ monkeypatch.setattr(discourse, "_is_host_safe", lambda host, team_id: (True, None))
+ valid, message = validate_credentials(BASE_URL, API_KEY, API_USERNAME, team_id=1)
+ assert valid is False
+ assert message is not None and "Could not connect to Discourse" in message
+
+ def test_validate_credentials_generic_error_status(self, monkeypatch: Any) -> None:
+ valid, message = self._validate(monkeypatch, _mock_response(500, {}))
+ assert valid is False
+ assert message == "Discourse returned HTTP 500"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse_source.py
new file mode 100644
index 000000000000..40a4b94858a3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/tests/test_discourse_source.py
@@ -0,0 +1,161 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.discourse import DiscourseResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.source import DiscourseSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.discourse import (
+ DiscourseSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestDiscourseSource:
+ def setup_method(self) -> None:
+ self.source = DiscourseSource()
+ self.team_id = 123
+ self.config = DiscourseSourceConfig(
+ base_url="https://forum.example.com", api_key="secret-key", api_username="system"
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DISCOURSE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Discourse"
+ assert config.label == "Discourse"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/discourse"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["base_url", "api_key", "api_username"]
+
+ def test_config_has_no_unreleased_flag(self) -> None:
+ # A finished source must not carry `unreleasedSource` — it hides the connector entirely.
+ assert self.source.get_source_config.unreleasedSource is None
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_api_username_field_is_plain_text(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_username")
+ assert field.type == SourceFieldInputConfigType.TEXT
+ assert field.secret is False
+ assert field.required is True
+
+ def test_connection_host_fields_covers_base_url_and_api_username(self) -> None:
+ # The stored API key is sent to whatever `base_url` points at, and `api_username` selects
+ # the identity an All Users key acts as, so retargeting either must force key re-entry.
+ assert self.source.connection_host_fields == ["base_url", "api_username"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_posts_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["posts"].supports_incremental is True
+ assert [f["field"] for f in schemas["posts"].incremental_fields] == ["id"]
+ for name, schema in schemas.items():
+ if name != "posts":
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["categories"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "categories"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+ @parameterized.expand(
+ [
+ ("403 Client Error: Forbidden for url: https://forum.example.com/session/current.json",),
+ ("invalid_access",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://forum.example.com/latest.json",),
+ ("429 Client Error: Too Many Requests for url: https://forum.example.com/posts.json",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.discourse.source.validate_discourse_credentials"
+ )
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Discourse API key or username")
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="posts")
+ assert result == (False, "Invalid Discourse API key or username")
+ mock_validate.assert_called_once_with(
+ "https://forum.example.com", "secret-key", "system", "posts", self.team_id
+ )
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DiscourseResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.discourse.source.discourse_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "posts"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-123"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 42
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["base_url"] == "https://forum.example.com"
+ assert kwargs["api_key"] == "secret-key"
+ assert kwargs["api_username"] == "system"
+ assert kwargs["endpoint"] == "posts"
+ assert kwargs["team_id"] == self.team_id
+ assert kwargs["job_id"] == "job-123"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 42
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "nope"
+ with pytest.raises(ValueError, match="Unknown Discourse schema"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/discourse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/discourse.py
index bc1bfffb33c3..8f5d6af86c29 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/discourse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/discourse.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class DiscourseSourceConfig(config.Config):
- pass
+ base_url: str
+ api_key: str
+ api_username: str