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(discourse): add admin user, membership, activity and badge tables (#105922)

Tom Owers29b3a9e6f3ea
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 4d8bd567acb2..1487cdc34b28 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2520,21 +2520,21 @@ Note: The live docs page returns Cloudflare 403 to non-browser clients and the s
## Discourse — gaps
-Today (6): `categories`, `groups`, `posts`, `tags`, `topics`, `users`
+Today (10): `admin_users`, `badges`, `categories`, `group_members`, `groups`, `posts`, `tags`, `topics`, `user_actions`, `users`
Diffed against: <https://docs.discourse.org/openapi.json>
-- [ ] `GET /groups/{name}/members.json` — group↔user membership junction; today groups and users sync but nothing links them (high)
-- [ ] `GET /admin/users.json and /admin/users/list/{flag}.json` — full user records (email, last_seen_at, trust_level, suspended state) — /directory_items.json only exposes a period-windowed public subset (high)
-- [ ] `GET /user_actions.json` — per-user activity stream (likes, replies, posts) — the event table for community engagement analysis (medium)
-- [ ] `GET /admin/badges.json` — lookup table resolving badge IDs on user badges (medium)
+- [x] `GET /groups/{name}/members.json` — group↔user membership junction; today groups and users sync but nothing links them (high)
+- [x] `GET /admin/users.json and /admin/users/list/{flag}.json` — full user records (email, last_seen_at, trust_level, suspended state) — /directory_items.json only exposes a period-windowed public subset (high)
+- [x] `GET /user_actions.json` — per-user activity stream (likes, replies, posts) — the event table for community engagement analysis (medium)
+- [x] `GET /admin/badges.json` — lookup table resolving badge IDs on user badges (medium)
- [ ] `GET /user-badges/{username}.json` — user↔badge grants with granted_at; the gamification/engagement fact table (medium)
- [ ] `GET /tag_groups.json` — lookup that groups the tags table into categories (medium)
- [ ] `GET /t/{id}/posts.json` — authoritative topic→post ordering; the /posts.json id-walk can miss posts in long topics (low)
- [ ] `GET /notifications.json` — notification events per user (low)
- [ ] `GET /discourse-post-event/events.json` — calendar/event plugin records for communities that run events (low)
-Note: The topics table is backed by /latest.json, which is a rolling recency feed rather than a full topic list — /c/{slug}/{id}.json (category topics) or /top.json would broaden historical coverage. Nothing is discovered dynamically; the endpoint set is static in settings.py.
+Note: `/admin/users/list/{flag}.json` is the same user records as `/admin/users.json` filtered by a status flag, so it is served by the one `admin_users` table rather than a table per flag. Email addresses are not synced: `show_emails=true` writes a staff action log entry per request, which would bury the customer's own audit log. The topics table is backed by /latest.json, which is a rolling recency feed rather than a full topic list — /c/{slug}/{id}.json (category topics) or /top.json would broaden historical coverage. Nothing is discovered dynamically; the endpoint set is static in settings.py.
## Dixa — gaps
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
index a9c345587f2f..5d27c4282cf5 100644
--- 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
@@ -121,4 +121,101 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"time_read": "Total time (in seconds) this user has spent reading.",
},
},
+ "group_members": {
+ "description": "One row per user in a group, linking the groups table to the users who belong to it. Group owners are included.",
+ "docs_url": "https://docs.discourse.org/#tag/Groups/operation/listGroupMembers",
+ "columns": {
+ "id": "id of the member user.",
+ "group_id": "id of the group the membership belongs to.",
+ "group_name": "Internal name of the group the membership belongs to.",
+ "username": "The member's unique username.",
+ "name": "The member's display name.",
+ "title": "The member's custom title, if any.",
+ "added_at": "When the user was added to the group.",
+ "last_posted_at": "When the member last posted anywhere on the forum.",
+ "last_seen_at": "When the member was last seen on the forum.",
+ "timezone": "The member's configured timezone.",
+ },
+ },
+ "admin_users": {
+ "description": "The full member list from the admin API, including accounts the public user directory leaves out. Email addresses are not synced.",
+ "docs_url": "https://docs.discourse.org/#tag/Users/operation/adminListUsers",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "username": "The user's unique username.",
+ "name": "The user's display name.",
+ "active": "Whether the account has been activated.",
+ "admin": "Whether the user has admin access.",
+ "moderator": "Whether the user has moderator access.",
+ "staged": "Whether the account was created by Discourse on the user's behalf (e.g. from an inbound email) and has never been claimed.",
+ "created_at": "When the account was created.",
+ "last_seen_at": "When the user was last seen on the forum.",
+ "last_emailed_at": "When Discourse last sent the user an email.",
+ "trust_level": "Discourse trust level, 0 (new) through 4 (leader).",
+ "manual_locked_trust_level": "Trust level an admin has pinned the user to, if any.",
+ "title": "The user's custom title, if any.",
+ "time_read": "Total time (in seconds) the user has spent reading.",
+ "days_visited": "Number of distinct days the user has visited the forum.",
+ "posts_read_count": "Number of posts the user has read.",
+ "topics_entered": "Number of distinct topics the user has viewed.",
+ "post_count": "Number of posts the user has made.",
+ },
+ },
+ "user_actions": {
+ "description": "One row per public action in a member's activity stream: likes given and received, new topics, replies, mentions, quotes and edits. Actions inside private message topics are excluded, and post text is not synced. Post bodies live in the posts table.",
+ "docs_url": "https://docs.discourse.org/#tag/Users/operation/listUserActions",
+ "columns": {
+ "action_type": "What the action was: 1 like, 2 was liked, 4 new topic, 5 reply, 6 response, 7 mention, 9 quote, 11 edit.",
+ "created_at": "When the action happened.",
+ "target_user_id": "id of the user whose activity stream this row belongs to.",
+ "target_username": "Username of the user whose activity stream this row belongs to.",
+ "target_name": "Display name of the user whose activity stream this row belongs to.",
+ "acting_user_id": "id of the user who performed the action.",
+ "acting_username": "Username of the user who performed the action.",
+ "acting_name": "Display name of the user who performed the action.",
+ "user_id": "id of the user who wrote the post or topic the action was aimed at.",
+ "username": "Username of the user who wrote the post or topic the action was aimed at.",
+ "name": "Display name of the user who wrote the post or topic the action was aimed at.",
+ "topic_id": "id of the topic the action was aimed at.",
+ "title": "Title of that topic.",
+ "slug": "URL-safe identifier of that topic.",
+ "category_id": "id of the category that topic belongs to.",
+ "post_number": "Position within the topic of the post the action was aimed at. 1 when the action targets the topic itself.",
+ "post_id": "id of the post the action was aimed at, when the action targets a post.",
+ "reply_to_post_number": "Post number this post replies to. Only set on reply actions.",
+ "action_code": "Small-action code for posts that record an event (e.g. a topic being closed) rather than content.",
+ "post_type": "Type of the target post: regular, moderator action, small action, or whisper.",
+ "deleted": "Whether the target post or topic has been deleted.",
+ "hidden": "Whether the target post has been hidden.",
+ "closed": "Whether the target topic is closed to new replies.",
+ "archived": "Whether the target topic has been archived.",
+ },
+ },
+ "badges": {
+ "description": "A badge that can be granted to members, used to resolve the badge IDs carried on user badge grants.",
+ "docs_url": "https://docs.discourse.org/#tag/Badges/operation/adminListBadges",
+ "columns": {
+ "id": "Unique identifier for the badge.",
+ "name": "Display name of the badge.",
+ "slug": "URL-safe identifier for the badge.",
+ "description": "Short description of what the badge is for.",
+ "long_description": "Full description shown on the badge page.",
+ "grant_count": "Number of times the badge has been granted.",
+ "badge_type_id": "id of the badge type, which sets the badge's colour (gold, silver, bronze).",
+ "badge_grouping_id": "id of the group the badge is listed under on the badges page.",
+ "enabled": "Whether the badge is currently being granted.",
+ "listable": "Whether the badge appears on the public badges page.",
+ "system": "Whether the badge ships with Discourse rather than being created by an admin.",
+ "manually_grantable": "Whether staff can grant the badge by hand.",
+ "multiple_grant": "Whether one user can hold the badge more than once.",
+ "allow_title": "Whether holders can use the badge name as their title.",
+ "auto_revoke": "Whether Discourse revokes the badge when its conditions stop holding.",
+ "target_posts": "Whether the badge is granted against a specific post.",
+ "show_posts": "Whether the granting post is shown on the badge page.",
+ "icon": "Font Awesome icon shown for the badge.",
+ "image_url": "URL of the custom image shown for the badge, if one is set.",
+ "trigger": "Event that makes Discourse re-evaluate the badge query.",
+ "query": "SQL query that decides who the badge is granted to, for custom badges.",
+ },
+ },
}
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
index dd22ce6f0200..2202f01a8b44 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/discourse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/discourse.py
@@ -1,6 +1,6 @@
import re
-import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterable, Iterator
+from datetime import datetime
from typing import Any, Optional
from urllib.parse import urlparse
@@ -8,7 +8,9 @@ import requests
from requests import PreparedRequest, Request, Response
from posthog.cloud_utils import is_cloud
+from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
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 (
@@ -18,16 +20,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.fanout import (
+ DependentEndpointConfig,
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
+ OffsetPaginator,
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ IncrementalConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.settings import (
DISCOURSE_ENDPOINTS,
POSTS_PAGE_SIZE,
+ USER_ACTION_PUBLIC_TYPES,
+ DiscourseEndpointConfig,
)
REQUEST_TIMEOUT_SECONDS = 30
@@ -39,12 +52,15 @@ class DiscourseHostNotAllowedError(Exception):
pass
+@frozen
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
+ # Fan-out endpoints resume on the shape `build_dependent_resource` checkpoints: which
+ # parents finished and where the current one stopped.
+ fanout_state: Optional[dict[str, Any]] = None
def normalize_base_url(base_url: str) -> str:
@@ -169,6 +185,37 @@ class DiscoursePostsPaginator(BasePaginator):
return f"DiscoursePostsPaginator(before={self._before}, stop_at_or_before={self._stop_at_or_before})"
+class DiscourseUserActionsPaginator(OffsetPaginator):
+ """Offset paginator for `/user_actions.json`, stopping once a page predates the watermark.
+
+ The endpoint takes no `since` filter and orders each user's stream newest-first, so an
+ incremental sync walks a user backward only until every row on a page is at or before the
+ last-synced `created_at`. Without that, each sync would re-read every user's whole history,
+ and the stream is fetched once per user, so the cost multiplies by the member count.
+ """
+
+ def __init__(self, limit: int, stop_at_or_before: Optional[datetime] = None) -> None:
+ # The response carries no total, so termination is the short/empty page check.
+ super().__init__(limit=limit, total_path=None)
+ self._stop_at_or_before = stop_at_or_before
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if not self._has_next_page or self._stop_at_or_before is None or not data:
+ return
+
+ timestamps = [
+ parsed
+ for row in data
+ if isinstance(row, dict) and (parsed := parse_datetime_value(row.get("created_at"))) is not None
+ ]
+ if timestamps and max(timestamps) <= self._stop_at_or_before:
+ self._has_next_page = False
+
+ def __str__(self) -> str:
+ return f"DiscourseUserActionsPaginator(offset={self.offset}, 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.
@@ -184,6 +231,28 @@ def _flatten_directory_item(item: dict[str, Any]) -> dict[str, Any]:
return item
+# The admin identity reads whispers plus hidden and deleted posts, so post text on an activity
+# row can be content the same warehouse reader cannot open in Discourse. Post bodies belong in
+# the posts table, which a user chooses separately.
+_POST_CONTENT_FIELDS = ("excerpt", "edit_reason")
+
+
+def _public_activity_rows(batch: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Reduce an activity page to public actions, without their post text.
+
+ `USER_ACTION_PUBLIC_TYPES` explains why the action types are narrowed here instead of in the
+ request, and `_POST_CONTENT_FIELDS` why the text is dropped.
+ """
+ rows: list[dict[str, Any]] = []
+ for row in batch:
+ if row.get("action_type") not in USER_ACTION_PUBLIC_TYPES:
+ continue
+ for field_name in _POST_CONTENT_FIELDS:
+ row.pop(field_name, None)
+ rows.append(row)
+ return rows
+
+
def _coerce_incremental_cursor(value: Any) -> Optional[int]:
if value is None:
return None
@@ -193,6 +262,61 @@ def _coerce_incremental_cursor(value: Any) -> Optional[int]:
return None
+def _paginator_for(endpoint_config: DiscourseEndpointConfig, watermark: Any = None) -> BasePaginator:
+ if endpoint_config.name == "posts":
+ return DiscoursePostsPaginator(stop_at_or_before=_coerce_incremental_cursor(watermark))
+ if endpoint_config.name == "user_actions":
+ return DiscourseUserActionsPaginator(
+ limit=endpoint_config.page_size, stop_at_or_before=parse_datetime_value(watermark)
+ )
+ if endpoint_config.name == "group_members":
+ return OffsetPaginator(limit=endpoint_config.page_size, total_path="meta.total")
+ if endpoint_config.paginated:
+ return PageNumberPaginator(base_page=endpoint_config.first_page, page_param="page")
+ return SinglePagePaginator()
+
+
+def _endpoint_extra(endpoint_config: DiscourseEndpointConfig, watermark: Any = None) -> Endpoint:
+ """Endpoint keys that are the same whether the endpoint is fetched directly or fanned out.
+
+ `path` and `params` are left out because the fan-out builder derives both and rejects them
+ here. So is `data_selector_malformed_retryable`, which the framework reads only on a
+ top-level resource, so setting it on a fan-out child would be dead config.
+ """
+ return {
+ "data_selector": endpoint_config.data_selector,
+ "paginator": _paginator_for(endpoint_config, watermark),
+ }
+
+
+# A 200 whose body isn't the expected list shape is treated as a transient glitch and retried,
+# rather than silently syncing 0 rows.
+_RETRY_MALFORMED_BODY: Endpoint = {"data_selector_malformed_retryable": True}
+
+
+def _no_server_side_window(_incremental_field: str) -> Optional[IncrementalConfig]:
+ """Discourse exposes no server-side time filter, so no cursor binds to the child request.
+
+ Returning None still leaves the child on a merge write disposition, which is what lets the
+ paginator's own watermark bound the walk instead.
+ """
+ return None
+
+
+def _client_config(normalized_base_url: str, api_key: str, api_username: str) -> ClientConfig:
+ return {
+ "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,
+ }
+
+
def discourse_source(
base_url: str,
api_key: str,
@@ -203,26 +327,14 @@ def discourse_source(
resumable_source_manager: ResumableSourceManager[DiscourseResumeConfig],
should_use_incremental_field: bool,
db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str] = None,
) -> SourceResponse:
endpoint_config = DISCOURSE_ENDPOINTS[endpoint]
normalized_base_url = normalize_base_url(base_url)
+ client_config = _client_config(normalized_base_url, api_key, api_username)
+ watermark = db_incremental_field_last_value if should_use_incremental_field else None
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
@@ -230,15 +342,83 @@ def discourse_source(
# (merge dedupes on primary key) rather than skipping it.
if not state:
return
+ if endpoint_config.fanout is not None:
+ resumable_source_manager.save_state(DiscourseResumeConfig(fanout_state=state))
+ return
resumable_source_manager.save_state(DiscourseResumeConfig(page=state.get("page"), before=state.get("before")))
+ def build_resource() -> Iterable[list[dict[str, Any]]]:
+ if endpoint_config.fanout is not None:
+ return _fanout_resource(
+ endpoint_config=endpoint_config,
+ fanout=endpoint_config.fanout,
+ client_config=client_config,
+ team_id=team_id,
+ job_id=job_id,
+ watermark=watermark,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume_config.fanout_state if resume_config else None,
+ )
+ return _flat_resource(
+ endpoint_config=endpoint_config,
+ client_config=client_config,
+ team_id=team_id,
+ job_id=job_id,
+ watermark=watermark,
+ should_use_incremental_field=should_use_incremental_field,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=_flat_initial_state(endpoint_config, resume_config),
+ )
+
+ 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)
+ for batch in build_resource():
+ rows = _public_activity_rows(batch) if endpoint == "user_actions" else batch
+ if rows:
+ yield rows
+
+ 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 _flat_initial_state(
+ endpoint_config: DiscourseEndpointConfig, resume_config: Optional[DiscourseResumeConfig]
+) -> Optional[dict[str, Any]]:
+ if resume_config is None:
+ return None
+ if endpoint_config.name == "posts":
+ return {"before": resume_config.before} if resume_config.before is not None else None
+ return {"page": resume_config.page} if resume_config.page is not None else None
+
+
+def _flat_resource(
+ *,
+ endpoint_config: DiscourseEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+ watermark: Any,
+ should_use_incremental_field: bool,
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_paginator_state: Optional[dict[str, Any]],
+) -> Iterable[list[dict[str, Any]]]:
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,
+ **_RETRY_MALFORMED_BODY,
+ **_endpoint_extra(endpoint_config, watermark),
}
if endpoint_config.extra_params:
endpoint_dict["params"] = dict(endpoint_config.extra_params)
@@ -250,61 +430,68 @@ def discourse_source(
)
resource: EndpointResource = {
- "name": endpoint,
+ "name": endpoint_config.name,
"endpoint": endpoint_dict,
"write_disposition": write_disposition,
"table_format": "delta",
}
- if endpoint == "users":
+ if endpoint_config.name == "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,
- },
+ "client": client_config,
"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 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=resume_hook,
+ initial_paginator_state=initial_paginator_state,
+ )
- 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 _fanout_resource(
+ *,
+ endpoint_config: DiscourseEndpointConfig,
+ fanout: DependentEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+ watermark: Any,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_paginator_state: Optional[dict[str, Any]],
+) -> Iterable[list[dict[str, Any]]]:
+ parent_config = DISCOURSE_ENDPOINTS[fanout.parent_name]
+
+ return build_dependent_resource(
+ endpoint_configs=DISCOURSE_ENDPOINTS,
+ child_endpoint=endpoint_config.name,
+ fanout=fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=watermark,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=_no_server_side_window,
+ parent_endpoint_extra={**_RETRY_MALFORMED_BODY, **_endpoint_extra(parent_config)},
+ child_endpoint_extra=_endpoint_extra(endpoint_config, watermark),
+ # Every paginator here sends its own page size, so the builder must not add one.
+ page_size_param=None,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_paginator_state,
)
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
index 1f278d14d214..181c6f156890 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/discourse/settings.py
@@ -1,6 +1,11 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Any, Literal, Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Verified against a live instance (meta.discourse.org): /latest.json returns 30 topics/page,
@@ -9,32 +14,107 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# never signals a total, so its cursor paginator needs the page size to decide "last page".
POSTS_PAGE_SIZE = 50
+# /admin/users.json is fixed at 100 rows/page server-side and takes no page-size param.
+ADMIN_USERS_PAGE_SIZE = 100
+
+# /groups/{name}/members.json caps `limit` at 1000, and /user_actions.json caps it at 100.
+GROUP_MEMBERS_PAGE_SIZE = 1000
+USER_ACTIONS_PAGE_SIZE = 100
+
+# Ascending by creation date keeps page boundaries stable while the sync runs: a user who
+# registers mid-sync lands on the last page instead of shifting every page after them.
+ADMIN_USERS_PARAMS = {"order": "created", "asc": "true"}
-@dataclass
+# Public UserAction types: 1 like, 2 was_liked, 4 new_topic, 5 reply, 6 response, 7 mention,
+# 9 quote, 11 edit.
+#
+# This allowlist is applied to the returned rows, not sent as the `filter` query param.
+# Discourse excludes private message topics from the stream only when `filter` is blank, and for
+# an admin identity a non-blank `filter` removes that exclusion entirely. Sending the allowlist
+# would therefore pull replies, likes and quotes made inside private message topics into the
+# table, carrying their titles and excerpts. Leaving `filter` off keeps the topic-level
+# exclusion, and the action types are narrowed afterwards.
+USER_ACTION_PUBLIC_TYPES = frozenset({1, 2, 4, 5, 6, 7, 9, 11})
+
+
+@frozen
class DiscourseEndpointConfig:
name: str
path: str
- # jsonpath into the response body where the list of records lives.
+ # jsonpath into the response body where the list of records lives. "$" for the endpoints
+ # that answer with a bare array.
data_selector: str
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # The incremental field to fall back on when the user's schema settings name none.
+ default_incremental_field: Optional[str] = None
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
+ # First page number the endpoint accepts. The public list endpoints are 0-based;
+ # /admin/users.json is 1-based (it clamps page 0 to page 1, so a 0-based walk would fetch
+ # the first 100 users twice).
+ first_page: int = 0
+ # Rows per page for the endpoints whose paginator sends an explicit page size. 0 where the
+ # API fixes the page size itself.
+ page_size: int = 0
# 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.
+ # accepted alongside `before` cursor pagination (verified live); user actions are ordered
+ # `created_at desc` server-side. 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)
+ # Set on endpoints that are fetched once per row of a parent endpoint.
+ fanout: Optional[DependentEndpointConfig] = None
+
+# Members are addressed by group name, and Discourse restricts group names to word characters,
+# so the name needs no percent-encoding before it goes into the path.
+GROUP_MEMBERS_FANOUT = DependentEndpointConfig(
+ parent_name="groups",
+ resolve_param="name",
+ resolve_field="name",
+ include_from_parent=["id", "name"],
+ parent_field_renames={"id": "group_id", "name": "group_name"},
+ # `order=added_at` sorts on the membership row's own creation time, which never changes, so
+ # offset pages can't shift under the sync the way the default username ordering can.
+ child_params={"order": "added_at", "asc": "true"},
+ # A group whose member list is restricted answers 403, and one renamed or deleted between
+ # the listing and this fetch answers 404. Every other group still has members worth syncing,
+ # so skip the group rather than failing the whole table.
+ child_response_actions=[
+ {"status_code": 403, "action": "ignore"},
+ {"status_code": 404, "action": "ignore"},
+ ],
+)
-# 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).
+# `/user_actions.json` requires a username, so the activity stream is fetched once per user.
+# The parent is `admin_users` rather than `users`, because `users` is backed by the
+# period-windowed public directory and would miss anyone outside that window.
+USER_ACTIONS_FANOUT = DependentEndpointConfig(
+ parent_name="admin_users",
+ resolve_param="username",
+ resolve_field="username",
+ # The payload's own `target_user_id` is the user whose stream the row came from, so there
+ # is nothing left to carry over from the parent row.
+ include_from_parent=[],
+ parent_params=dict(ADMIN_USERS_PARAMS),
+ # No `filter` param: see USER_ACTION_PUBLIC_TYPES for why the action types are narrowed
+ # after the response instead.
+ # Discourse answers 404 (not 403) both for a profile the key cannot see and for a user
+ # deleted between the listing and this fetch.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+)
+
+
+# Discourse Admin API endpoints. Only `posts` and `user_actions` have a reliable incremental
+# cursor, because both are returned newest-first and are walked back only as far as the watermark.
+# 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",
@@ -64,6 +144,7 @@ DISCOURSE_ENDPOINTS: dict[str, DiscourseEndpointConfig] = {
"field_type": IncrementalFieldType.Integer,
}
],
+ default_incremental_field="id",
paginated=True,
sort_mode="desc",
partition_key="created_at",
@@ -80,6 +161,19 @@ DISCOURSE_ENDPOINTS: dict[str, DiscourseEndpointConfig] = {
data_selector="groups",
paginated=True,
),
+ "group_members": DiscourseEndpointConfig(
+ name="group_members",
+ path="/groups/{name}/members.json",
+ # `owners` in the same response is a subset of `members`, not an addition, so syncing
+ # `members` alone covers every membership.
+ data_selector="members",
+ # The member id is a user id, unique only within the group's roster.
+ primary_keys=["group_id", "id"],
+ paginated=True,
+ partition_key="added_at",
+ page_size=GROUP_MEMBERS_PAGE_SIZE,
+ fanout=GROUP_MEMBERS_FANOUT,
+ ),
"users": DiscourseEndpointConfig(
name="users",
path="/directory_items.json",
@@ -89,6 +183,50 @@ DISCOURSE_ENDPOINTS: dict[str, DiscourseEndpointConfig] = {
extra_params={"period": "all", "order": "likes_received"},
paginated=True,
),
+ "admin_users": DiscourseEndpointConfig(
+ name="admin_users",
+ path="/admin/users.json",
+ # The response is a bare array of user records.
+ data_selector="$",
+ paginated=True,
+ first_page=1,
+ page_size=ADMIN_USERS_PAGE_SIZE,
+ partition_key="created_at",
+ # `show_emails=true` is available but deliberately not sent: it writes a staff action log
+ # entry per request, so a sync of a large forum would bury the customer's own audit log.
+ extra_params=dict(ADMIN_USERS_PARAMS),
+ ),
+ "user_actions": DiscourseEndpointConfig(
+ name="user_actions",
+ # The user is selected by query param rather than by path segment, and the fan-out
+ # builder binds resolve params in the path only, so the param is written into the path.
+ path="/user_actions.json?username={username}",
+ data_selector="user_actions",
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ default_incremental_field="created_at",
+ # The stream carries no id of its own. These five columns are what Discourse's own
+ # unique index on user_actions is built from, with `post_number` standing in for the
+ # nullable target post id so no merge key can be null.
+ primary_keys=["target_user_id", "acting_user_id", "action_type", "topic_id", "post_number"],
+ paginated=True,
+ sort_mode="desc",
+ partition_key="created_at",
+ page_size=USER_ACTIONS_PAGE_SIZE,
+ fanout=USER_ACTIONS_FANOUT,
+ ),
+ "badges": DiscourseEndpointConfig(
+ name="badges",
+ path="/admin/badges.json",
+ data_selector="badges",
+ paginated=False,
+ ),
}
ENDPOINTS = tuple(DISCOURSE_ENDPOINTS.keys())
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 ad382a88465d..c22ef0af1877 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
@@ -57,9 +57,11 @@ class DiscourseSource(ResumableSource[DiscourseSourceConfig, DiscourseResumeConf
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.
+ caption="""Connect your Discourse community forum to sync categories, topics, posts, tags, groups, group members, badges, and user activity 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`.""",
+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 API username must be an admin account, because the admin users and badges tables read admin-only endpoints. The instance URL is your forum's address, e.g. `https://yourforum.discourse.group`.
+
+The user activity table is fetched once per member, so it takes longer to sync than the others.""",
iconPath="/static/services/discourse.png",
docsUrl="https://posthog.com/docs/cdp/sources/discourse",
fields=cast(
@@ -150,4 +152,5 @@ Generate an Admin API key under **Admin > API > Keys** on your Discourse instanc
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,
+ incremental_field=inputs.incremental_field,
)
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
index b7b27c64ae8e..1531ccc83d66 100644
--- 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
@@ -1,4 +1,5 @@
import json
+from datetime import UTC, datetime
from typing import Any, Optional
import pytest
@@ -16,12 +17,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.
DiscourseHostNotAllowedError,
DiscoursePostsPaginator,
DiscourseResumeConfig,
+ DiscourseUserActionsPaginator,
_flatten_directory_item,
discourse_source,
hostname_of,
normalize_base_url,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.discourse.settings import USER_ACTIONS_PAGE_SIZE
# 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"
@@ -90,6 +93,12 @@ def _wire(session: MagicMock, responses: list[requests.Response]) -> list[dict[s
return param_snapshots
+def _urls(session: MagicMock) -> list[str]:
+ """URLs of every request the run prepared. Unlike ``request.params``, ``request.url`` is not
+ mutated between pages, so it can be read after the run."""
+ return [call.args[0].url for call in session.prepare_request.call_args_list]
+
+
def _rows(source_response: Any) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
@@ -101,6 +110,7 @@ def _source(
base_url: str = BASE_URL,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
) -> Any:
return discourse_source(
base_url=base_url,
@@ -112,9 +122,23 @@ def _source(
resumable_source_manager=manager,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
)
+def _action(created_at: str, **overrides: Any) -> dict[str, Any]:
+ row = {
+ "action_type": 5,
+ "created_at": created_at,
+ "target_user_id": 7,
+ "acting_user_id": 9,
+ "topic_id": 3,
+ "post_number": 2,
+ }
+ row.update(overrides)
+ return row
+
+
class TestNormalizeAndHostname:
@parameterized.expand(
[
@@ -423,6 +447,279 @@ class TestPipelineTransport:
assert rows == [_post(1)]
+class TestDiscourseUserActionsPaginator:
+ WATERMARK = datetime(2026, 3, 1, tzinfo=UTC)
+
+ def _page(self, rows: list[dict[str, Any]], watermark: Optional[datetime]) -> DiscourseUserActionsPaginator:
+ paginator = DiscourseUserActionsPaginator(limit=USER_ACTIONS_PAGE_SIZE, stop_at_or_before=watermark)
+ paginator.update_state(_json_response({"user_actions": rows}), data=rows)
+ return paginator
+
+ @parameterized.expand([("short_page", 1, False), ("full_page", USER_ACTIONS_PAGE_SIZE, True)])
+ def test_full_refresh_walks_on_only_while_pages_stay_full(
+ self, _name: str, row_count: int, expects_next_page: bool
+ ) -> None:
+ rows = [_action("2026-01-01T00:00:00.000Z")] * row_count
+ assert self._page(rows, None).has_next_page is expects_next_page
+
+ @parameterized.expand(
+ [
+ # The whole page is already synced, so this user's walk is done.
+ ("page_predates_the_watermark", ["2026-02-28T12:00:00.000Z"] * USER_ACTIONS_PAGE_SIZE, False),
+ # Only the first row is newer, but the rest of the stream still has to be walked.
+ (
+ "page_still_holds_newer_rows",
+ ["2026-03-05T00:00:00.000Z"] + ["2026-02-01T00:00:00.000Z"] * (USER_ACTIONS_PAGE_SIZE - 1),
+ True,
+ ),
+ # Nothing on the page can be compared against the watermark, so it proves nothing
+ # about how far back the walk has got.
+ ("unparsable_timestamps", ["not-a-date"] * USER_ACTIONS_PAGE_SIZE, True),
+ ]
+ )
+ def test_incremental_stops_only_once_a_whole_page_predates_the_watermark(
+ self, _name: str, created_ats: list[str], expects_next_page: bool
+ ) -> None:
+ rows = [_action(created_at) for created_at in created_ats]
+ assert self._page(rows, self.WATERMARK).has_next_page is expects_next_page
+
+
+class TestAdminUsers:
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_reads_the_bare_array_body_and_starts_at_page_one(self, MockSession: Any, _safe: Any) -> None:
+ # Discourse clamps page 0 to page 1, so a 0-based walk would sync the first 100 users twice.
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _json_response([{"id": 1, "username": "alice"}]),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "admin_users"))
+ assert rows == [{"id": 1, "username": "alice"}]
+ assert [p["page"] for p in params] == [1, 2]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_sorts_ascending_by_creation_date_and_never_asks_for_emails(self, MockSession: Any, _safe: Any) -> None:
+ # `show_emails=true` writes a staff action log entry per request, so a sync of a large
+ # forum would bury the customer's own audit log.
+ session = MockSession.return_value
+ params = _wire(session, [_json_response([])])
+
+ _rows(_source(_make_manager(), "admin_users"))
+ assert params[0]["order"] == "created"
+ assert params[0]["asc"] == "true"
+ assert "show_emails" not in params[0]
+
+
+class TestBadges:
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_syncs_only_the_badges_list_from_the_multi_key_body(self, MockSession: Any, _safe: Any) -> None:
+ # The response also carries badge_types, badge_groupings and admin_badges; only the
+ # badge records belong in the table.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _json_response(
+ {
+ "badges": [{"id": 1, "name": "Welcome"}],
+ "badge_types": [{"id": 3, "name": "Bronze"}],
+ "badge_groupings": [{"id": 1, "name": "Getting Started"}],
+ "admin_badges": {"badge_ids": [1]},
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "badges"))
+ assert rows == [{"id": 1, "name": "Welcome"}]
+ assert session.send.call_count == 1
+
+
+class TestGroupMembers:
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_groups_and_stamps_the_group_onto_each_member(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _json_response({"groups": [{"id": 41, "name": "staff"}, {"id": 42, "name": "moderators"}]}),
+ _json_response({"members": [{"id": 1, "username": "alice"}], "meta": {"total": 1}}),
+ _json_response({"members": [{"id": 2, "username": "bob"}], "meta": {"total": 1}}),
+ _json_response({"groups": []}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "group_members"))
+ assert rows == [
+ {"id": 1, "username": "alice", "group_id": 41, "group_name": "staff"},
+ {"id": 2, "username": "bob", "group_id": 42, "group_name": "moderators"},
+ ]
+ # The membership row's own creation time is the only ordering that can't shift under an
+ # offset walk while the sync runs.
+ assert params[1]["order"] == "added_at"
+ assert params[1]["asc"] == "true"
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_walks_offset_pages_within_one_group(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ page1 = [{"id": member_id} for member_id in range(1000)]
+ params = _wire(
+ session,
+ [
+ _json_response({"groups": [{"id": 41, "name": "staff"}]}),
+ _json_response({"members": page1, "meta": {"total": 1001}}),
+ _json_response({"members": [{"id": 1000}], "meta": {"total": 1001}}),
+ _json_response({"groups": []}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "group_members"))
+ assert len(rows) == 1001
+ assert [p["offset"] for p in params[1:3]] == [0, 1000]
+
+ @parameterized.expand([("restricted_roster", 403), ("group_gone", 404)])
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_skips_a_group_whose_roster_cannot_be_read(
+ self, _name: str, status: int, MockSession: Any, _safe: Any
+ ) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _json_response({"groups": [{"id": 41, "name": "secret"}, {"id": 42, "name": "staff"}]}),
+ _json_response({"errors": ["nope"]}, status_code=status),
+ _json_response({"members": [{"id": 2}], "meta": {"total": 1}}),
+ _json_response({"groups": []}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "group_members"))
+ assert rows == [{"id": 2, "group_id": 42, "group_name": "staff"}]
+
+
+class TestUserActions:
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_admin_users_without_a_server_side_action_filter(self, MockSession: Any, _safe: Any) -> None:
+ # Discourse drops private message topics from the stream only while `filter` is blank,
+ # and for an admin identity a non-blank `filter` removes the exclusion entirely. Sending
+ # one would pull replies and likes made inside private messages into the table.
+ session = MockSession.return_value
+ action = _action("2026-03-05T00:00:00.000Z")
+ params = _wire(
+ session,
+ [
+ _json_response([{"id": 7, "username": "alice"}]),
+ _json_response({"user_actions": [action]}),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "user_actions"))
+ assert rows == [action]
+ assert _urls(session)[1] == f"{BASE_URL}/user_actions.json?username=alice"
+ assert "filter" not in params[1]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_narrows_to_public_actions_and_drops_post_text(self, MockSession: Any, _safe: Any) -> None:
+ # With no server-side filter the stream carries every action type, and the admin
+ # identity also reads whispers and hidden posts, so both narrowing steps run over the
+ # response instead.
+ session = MockSession.return_value
+ reply = _action("2026-03-05T00:00:00.000Z", excerpt="post body", edit_reason="typo")
+ private_message = _action("2026-03-04T00:00:00.000Z", action_type=12)
+ _wire(
+ session,
+ [
+ _json_response([{"id": 7, "username": "alice"}]),
+ _json_response({"user_actions": [reply, private_message]}),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "user_actions"))
+ assert rows == [_action("2026-03-05T00:00:00.000Z")]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_incremental_stops_walking_a_user_at_the_watermark(self, MockSession: Any, _safe: Any) -> None:
+ session = MockSession.return_value
+ page = [_action("2026-02-28T12:00:00.000Z")] * USER_ACTIONS_PAGE_SIZE
+ _wire(
+ session,
+ [
+ _json_response([{"id": 7, "username": "alice"}]),
+ _json_response({"user_actions": page}),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(
+ _source(
+ _make_manager(),
+ "user_actions",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ db_incremental_field_last_value="2026-03-01T00:00:00Z",
+ )
+ )
+ assert len(rows) == USER_ACTIONS_PAGE_SIZE
+ # One parent page, one child page, one terminal parent page: the child never walked on.
+ assert session.send.call_count == 3
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_ignores_the_stored_watermark_and_walks_the_whole_stream(
+ self, MockSession: Any, _safe: Any
+ ) -> None:
+ session = MockSession.return_value
+ page1 = [_action("2026-01-01T00:00:00.000Z")] * USER_ACTIONS_PAGE_SIZE
+ params = _wire(
+ session,
+ [
+ _json_response([{"id": 7, "username": "alice"}]),
+ _json_response({"user_actions": page1}),
+ _json_response({"user_actions": [_action("2025-01-01T00:00:00.000Z")]}),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "user_actions", db_incremental_field_last_value="2026-03-01T00:00:00Z"))
+ assert len(rows) == USER_ACTIONS_PAGE_SIZE + 1
+ assert [p["offset"] for p in params[1:3]] == [0, USER_ACTIONS_PAGE_SIZE]
+
+ @patch(IS_HOST_SAFE_PATCH, return_value=(True, None))
+ @patch(CLIENT_SESSION_PATCH)
+ def test_skips_a_user_whose_stream_is_not_visible(self, MockSession: Any, _safe: Any) -> None:
+ # Discourse answers 404 both for a hidden profile and for a user deleted between the
+ # listing and this fetch; either way the other users still have activity worth syncing.
+ session = MockSession.return_value
+ action = _action("2026-03-05T00:00:00.000Z")
+ _wire(
+ session,
+ [
+ _json_response([{"id": 7, "username": "hidden"}, {"id": 8, "username": "alice"}]),
+ _json_response({"errors": ["nope"]}, status_code=404),
+ _json_response({"user_actions": [action]}),
+ _json_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), "user_actions"))
+ assert rows == [action]
+
+
class TestErrorHandling:
@parameterized.expand([("rate_limited", 429), ("server_error", 500), ("unavailable", 503)])
@patch("tenacity.nap.time.sleep")