:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Mighty Networks import source (#84423)
Tom Owersa05632591d5e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mightynetworks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mightynetworks.pyindex 94e3e5ab2c63..f19f871e1446 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mightynetworks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mightynetworks.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MightyNetworksSourceConfig(config.Config):- pass+ network_id: str+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/canonical_descriptions.pynew file mode 100644index 000000000000..845bcaaacb90--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/canonical_descriptions.py@@ -0,0 +1,157 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://docs.mightynetworks.com/admin-api"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Members": {+ "description": "A member of the Network.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "email": "The member's email address.",+ "member_type": "The member's type: 'full' (belongs to the Network) or 'limited' (belongs only to specific spaces).",+ "first_name": "The member's first name.",+ "last_name": "The member's last name.",+ "time_zone": "The member's time zone.",+ "location": "The member's location.",+ "bio": "The member's bio.",+ "referral_count": "Number of referrals made by this member.",+ "avatar": "URL to the member's avatar image.",+ "permalink": "Canonical URL to the member's profile page.",+ "ambassador_level": "The member's ambassador level.",+ },+ },+ "Spaces": {+ "description": "A Space is an organizational unit within a Network, such as a course, group, or forum.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "name": "The Space's name.",+ "collection_id": "The ID of the collection this Space belongs to.",+ },+ },+ "Posts": {+ "description": "Posts are created by members within Spaces.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "creator_id": "The ID of the member that created the post.",+ "space_id": "The ID of the Space where the post was created.",+ "summary": "A short summary of the post's contents.",+ "description": "The post's description.",+ "post_type": "The type of post.",+ "title": "The title of the post.",+ "status": "The post's current status.",+ "published_at": "The date the post was published.",+ "last_activity_at": "The time of the last activity on the post.",+ "content_type": "The type of content attached to the post.",+ "comments_enabled": "Whether comments are enabled on this post.",+ "permalink": "The post's unique address within the Network.",+ },+ },+ "Events": {+ "description": "Events are scheduled gatherings that members can RSVP to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "title": "The event title.",+ "description": "The event description.",+ "permalink": "Full URL to view the event.",+ "recurrence_rule": "RRULE format string for recurring events.",+ "rsvp_enabled": "Whether RSVPs are enabled for this event.",+ "rsvp_closed": "Whether RSVPs are closed.",+ "restricted_event": "Whether this event is restricted to specific members.",+ "post_in_feed": "Whether this event appears in the activity feed.",+ "event_type": "Type of event: 'online_meeting', 'local_meetup', 'zoom_meeting', 'zoom_webinar', etc.",+ "starts_at": "The date and time the event starts, in the event's timezone.",+ "ends_at": "The date and time the event ends, in the event's timezone.",+ "time_zone": "IANA timezone identifier for the event.",+ "location": "Physical location of the event.",+ "link": "External event link URL.",+ "frequency": "Recurrence frequency: 'daily', 'weekly', 'monthly', or 'yearly'.",+ "interval": "Recurrence interval (e.g. 1 for every week, 2 for every 2 weeks).",+ },+ },+ "Plans": {+ "description": "A plan represents a purchasable offering in the Network.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "name": "The plan's name.",+ "description": "The plan's description.",+ "status": "The plan's status (visible, hidden, pending, rejected, archived, legacy).",+ "pricing_type": "The pricing type (free, subscription, one_time, installment, one_time_installment, token_gated, nonpaid).",+ "visible_to_members": "Whether the plan is visible to members.",+ "external": "Whether the plan includes Network membership.",+ "multiple": "Whether the plan includes multiple Spaces.",+ "permalink": "Canonical URL to the plan's about page.",+ },+ },+ "Subscriptions": {+ "description": "A recurring payment subscription to a plan. The record's own id is nested under `subscription.id` in the API response and is hoisted to the row's `id` column.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The subscription's unique ID (hoisted from the nested `subscription` object).",+ "member_id": "The subscriber's integer ID.",+ "created_at": "The date and time the subscriber was created.",+ "updated_at": "The date and time the subscriber was last modified.",+ "email": "The subscriber's email address.",+ "first_name": "The subscriber's first name.",+ "last_name": "The subscriber's last name.",+ "plan": "The subscribed plan (id, name, amount, currency, interval, type, trial availability).",+ "subscription": "Subscription detail (billing period, payment platform, cancellation, and trial dates).",+ },+ },+ "Purchases": {+ "description": "A one-time purchase of a plan by a member. The record's own id, created_at, and updated_at are nested under `purchase.*` in the API response and are hoisted to the row root.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The purchase's unique ID (hoisted from the nested `purchase` object).",+ "created_at": "The date and time the purchase record was created (hoisted from the nested `purchase` object).",+ "updated_at": "The date and time the purchase record was last modified (hoisted from the nested `purchase` object).",+ "member_id": "ID of the member who made the purchase.",+ "member_email": "Email of the member.",+ "plan": "The purchased plan (id, name, amount, currency, interval, type).",+ "purchase": "Purchase detail (tax, payment platform, purchase date).",+ },+ },+ "Tags": {+ "description": "Tags are custom field values used to categorize and label members.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "title": "The title of the tag.",+ "description": "The description of the tag.",+ "color": "The hex color code for the tag.",+ "custom_field_id": "The ID of the custom field this tag belongs to.",+ },+ },+ "Badges": {+ "description": "Badges are custom field values used to recognize and reward members.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "The record's integer ID.",+ "created_at": "The date and time the record was created.",+ "updated_at": "The date and time the record was last modified.",+ "title": "The title of the badge.",+ "description": "The description of the badge.",+ "color": "The hex color code for the badge.",+ "custom_field_id": "The ID of the custom field this badge belongs to.",+ "avatar_url": "URL to the badge image.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/mighty_networks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/mighty_networks.pynew file mode 100644index 000000000000..497daca66c30--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/mighty_networks.py@@ -0,0 +1,182 @@+import dataclasses+from collections.abc import Callable+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.settings import (+ BASE_URL,+ PARTITION_FIELDS,+ PATHS,+ PER_PAGE,+ PRIMARY_KEYS,+)++# Mighty Networks blocks requests without a descriptive User-Agent as bot traffic, returning an+# HTML challenge page with HTTP 403 instead of a JSON error.+USER_AGENT = "PostHog-DataWarehouse/1.0 (+https://posthog.com)"++[email protected](frozen=False)+class MightyNetworksResumeConfig:+ # Next 1-indexed page to fetch. None means "start from page 1".+ next_page: Optional[int] = None+++def _network_url(network_id: str, path: str = "") -> str:+ return f"{BASE_URL}/networks/{network_id}{path}"+++def _flatten_subscription(row: dict[str, Any]) -> dict[str, Any]:+ # The subscription's own id lives under a nested `subscription` object; lift it to the row+ # root so `primary_keys=["id"]` has a flat column to merge on.+ subscription = row.get("subscription")+ if isinstance(subscription, dict) and "id" in subscription:+ row["id"] = subscription["id"]+ return row+++def _flatten_purchase(row: dict[str, Any]) -> dict[str, Any]:+ # Same shape as subscriptions: the purchase's id, created_at and updated_at all live under a+ # nested `purchase` object rather than the row root.+ purchase = row.get("purchase")+ if isinstance(purchase, dict):+ for field in ("id", "created_at", "updated_at"):+ if field in purchase:+ row[field] = purchase[field]+ return row+++_ROW_FIXUPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ "Subscriptions": _flatten_subscription,+ "Purchases": _flatten_purchase,+}+++def _client_config(api_key: str, network_id: str) -> ClientConfig:+ return {+ "base_url": _network_url(network_id),+ "headers": {"User-Agent": USER_AGENT, "Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="meta.total_pages"),+ }+++def mighty_networks_source(+ api_key: str,+ network_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[MightyNetworksResumeConfig],+) -> SourceResponse:+ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key, network_id),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [+ {+ "name": endpoint,+ "write_disposition": "replace",+ "endpoint": {+ "path": PATHS[endpoint],+ "params": {"per_page": PER_PAGE},+ # The docs show two different placeholder envelopes for list responses+ # ("data"/meta and "items"/links); "data" is the one paired with the concrete+ # meta fields (current_page/total_pages/total_count) this paginator relies on,+ # so it's the more likely real field name. Fail loud if that's wrong rather+ # than silently syncing zero rows.+ "data_selector": "data",+ "data_selector_required": True,+ },+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_page:+ initial_paginator_state = {"page": resume.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields+ # the last page (merge dedupes) rather than skipping it.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(MightyNetworksResumeConfig(next_page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ fixup = _ROW_FIXUPS.get(endpoint)+ if fixup is not None:+ resource = resource.add_map(fixup)++ partition_key = PARTITION_FIELDS.get(endpoint)++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS.get(endpoint, ["id"]),+ column_hints=resource.column_hints,+ partition_count=1 if partition_key else None,+ partition_size=1 if partition_key else None,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )+++def validate_credentials(api_key: str, network_id: str) -> tuple[bool, int | None]:+ """Probe Mighty Networks' `/me` endpoint to confirm the token (and network id) are genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error.+ """+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ _network_url(network_id, "/me"),+ headers={"Authorization": f"Bearer {api_key}", "User-Agent": USER_AGENT, "Accept": "application/json"},+ )+++def check_endpoint_access(api_key: str, network_id: str, endpoint: str) -> Optional[str]:+ """Probe a single list endpoint and report why it's inaccessible, or ``None`` if it's fine.++ Only a genuine 403 (valid token, missing permission) counts as a permission problem — a+ throttle, 5xx, or network blip should not deselect a table the user can actually sync.+ """+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ _network_url(network_id, PATHS[endpoint]),+ headers={"Authorization": f"Bearer {api_key}", "User-Agent": USER_AGENT, "Accept": "application/json"},+ params={"per_page": 1},+ timeout=10,+ )+ except Exception:+ return None++ if response.status_code != 403:+ return None++ try:+ message = response.json().get("message")+ except Exception:+ message = None++ return message or "Your Mighty Networks API token doesn't have permission to read this data."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/settings.pynew file mode 100644index 000000000000..f704c5631198--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/settings.py@@ -0,0 +1,44 @@+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.mn.co/admin/v1"++# Mighty Networks caps `per_page` at 100 (default 25). Always request the max to minimise round trips.+PER_PAGE = 100++ENDPOINTS = (+ "Members",+ "Spaces",+ "Posts",+ "Events",+ "Plans",+ "Subscriptions",+ "Purchases",+ "Tags",+ "Badges",+)++# Path under /admin/v1/networks/{network_id}.+PATHS: dict[str, str] = {+ "Members": "/members",+ "Spaces": "/spaces",+ "Posts": "/posts",+ "Events": "/events",+ "Plans": "/plans",+ "Subscriptions": "/subscriptions",+ "Purchases": "/purchases",+ "Tags": "/tags",+ "Badges": "/badges",+}++# Subscriptions and Purchases nest the record's real id under a `subscription`/`purchase` object+# rather than exposing it at the row root (see mighty_networks.py's flatten helpers), everything+# else has a flat `id`.+PRIMARY_KEYS: dict[str, list[str]] = {name: ["id"] for name in ENDPOINTS}++# All endpoints expose created_at, and it never changes after creation, unlike updated_at.+PARTITION_FIELDS: dict[str, str] = dict.fromkeys(ENDPOINTS, "created_at")++# No list endpoint documents or accepts an updated_since/created_since filter (checked against the+# published OpenAPI spec at api.mn.co/admin/v1/spec.json and docs.mightynetworks.com/admin-api) —+# every endpoint is full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/source.pyindex 94bf2cce53d4..b1c3272e3e2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/source.py@@ -1,21 +1,58 @@-from typing import cast+import re+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mightynetworks import (MightyNetworksSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.mighty_networks import (+ MightyNetworksResumeConfig,+ check_endpoint_access,+ mighty_networks_source,+ validate_credentials as validate_mighty_networks_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# A Mighty Networks network id is a positive integer path segment (e.g. .../networks/1234/members).+_NETWORK_ID_RE = re.compile(r"^[0-9]+$")+@SourceRegistry.register-class MightyNetworksSource(SimpleSource[MightyNetworksSourceConfig]):+class MightyNetworksSource(ResumableSource[MightyNetworksSourceConfig, MightyNetworksResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ @property+ def connection_host_fields(self) -> list[str]:+ # `network_id` is where the stored API key is sent; retargeting it must re-require the key.+ return ["network_id"]++ # The API has no dedicated version token (path is a bare, never-changed /v1/); see+ # api_docs_url for where a future version would be announced.+ api_docs_url = "https://docs.mightynetworks.com/admin-api-changelog"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MIGHTYNETWORKS@@ -25,8 +62,108 @@ class MightyNetworksSource(SimpleSource[MightyNetworksSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.MIGHTY_NETWORKS,category=DataWarehouseSourceCategory.COMMUNICATION,+ keywords=["community", "courses", "membership"],label="Mighty Networks",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Mighty Networks network ID and API key to pull your members, spaces, posts, events, plans, subscriptions, purchases, tags, and badges into the PostHog Data warehouse.++Generate an API key under **Settings > API Keys** in your Mighty Networks admin dashboard. The Admin API is only available on the Growth and Mighty Pro plans.""",iconPath="/static/services/mighty_networks.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/mighty-networks",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="network_id",+ label="Network ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1234",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Mighty Networks API key is invalid or has been revoked. Generate a new key under Settings > API Keys, then reconnect.",+ "403 Client Error: Forbidden": "Your Mighty Networks API key doesn't have permission for this data. Check the key's permissions under Settings > API Keys, then reconnect.",+ "404 Client Error: Not Found": "Mighty Networks couldn't find that network ID. Check the network ID and try again.",+ }++ def get_schemas(+ self,+ config: MightyNetworksSourceConfig,+ 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: MightyNetworksSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if not _NETWORK_ID_RE.match(config.network_id):+ return False, "That doesn't look like a Mighty Networks network ID. Enter just the numeric ID."++ ok, status_code = validate_mighty_networks_credentials(config.api_key, config.network_id)+ if ok:+ return True, None+ # A valid token missing a scope for /me is still a usable connection — users may only+ # grant scopes for the tables they want to sync. Reject it once they've picked a table.+ if schema_name is None and status_code == 403:+ return True, None+ if status_code == 404:+ return False, "Mighty Networks couldn't find that network ID. Check the network ID and try again."+ if status_code == 403:+ return False, "Your Mighty Networks API key doesn't have permission to read this table."+ return False, "Invalid credentials"++ def get_endpoint_permissions(+ self,+ config: MightyNetworksSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return {endpoint: check_endpoint_access(config.api_key, config.network_id, endpoint) for endpoint in endpoints}++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MightyNetworksResumeConfig]:+ return ResumableSourceManager[MightyNetworksResumeConfig](inputs, MightyNetworksResumeConfig)++ def source_for_pipeline(+ self,+ config: MightyNetworksSourceConfig,+ resumable_source_manager: ResumableSourceManager[MightyNetworksResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return mighty_networks_source(+ api_key=config.api_key,+ network_id=config.network_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks.pynew file mode 100644index 000000000000..b2ebf62625d7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks.py@@ -0,0 +1,350 @@+import json+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.mighty_networks import (+ USER_AGENT,+ MightyNetworksResumeConfig,+ check_endpoint_access,+ mighty_networks_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.settings import PER_PAGE++# RESTClient builds its 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"+# validate_credentials / check_endpoint_access build their own tracked sessions in this module.+MIGHTY_NETWORKS_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.mighty_networks.make_tracked_session"+++def _response(+ items: list[dict[str, Any]] | None,+ *,+ current_page: int | None = None,+ total_pages: int | None = None,+ drop_data_key: bool = False,+ status_code: int = 200,+) -> Response:+ body: dict[str, Any] = {}+ if not drop_data_key:+ body["data"] = items or []+ if total_pages is not None:+ body["meta"] = {"current_page": current_page or 1, "total_pages": total_pages}+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: MightyNetworksResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request 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 = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append(+ {+ "url": request.url,+ "params": dict(request.params or {}),+ "auth": request.auth,+ "headers": dict(request.headers or {}),+ }+ )+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock):+ return mighty_networks_source(+ api_key="key",+ network_id="1234",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestMightyNetworksSourceNonFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_total_pages(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"id": 1}, {"id": 2}], current_page=1, total_pages=2),+ _response([{"id": 3}], current_page=2, total_pages=2),+ ],+ )++ rows = _rows(_source("Members", _make_manager()))++ assert [r["id"] for r in rows] == [1, 2, 3]+ # total_pages=2 terminates after the last page — no extra empty-page request.+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://api.mn.co/admin/v1/networks/1234/members"+ assert snapshots[0]["params"] == {"per_page": PER_PAGE, "page": 1}+ assert snapshots[1]["params"] == {"per_page": PER_PAGE, "page": 2}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_is_framework_bearer(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": 1}], total_pages=1)])++ _rows(_source("Members", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, BearerTokenAuth)+ assert auth.token == "key"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sends_descriptive_user_agent(self, MockSession) -> None:+ # Mighty Networks blocks requests with no/generic User-Agent as bot traffic (HTTP 403 ++ # HTML challenge page). The client applies this as a session-level header.+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}], total_pages=1)])++ _rows(_source("Members", _make_manager()))++ assert session.headers["User-Agent"] == USER_AGENT++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"id": 1}], current_page=1, total_pages=2),+ _response([{"id": 2}], current_page=2, total_pages=2),+ ],+ )++ manager = _make_manager()+ _rows(_source("Members", manager))++ # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == MightyNetworksResumeConfig(next_page=2)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": 2}], current_page=2, total_pages=2)])++ rows = _rows(_source("Members", _make_manager(MightyNetworksResumeConfig(next_page=2))))++ assert [r["id"] for r in rows] == [2]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["page"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_empty_page_without_total_pages(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ manager = _make_manager()+ rows = _rows(_source("Spaces", manager))++ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_data_key_raises(self, MockSession) -> None:+ # data_selector_required=True: a response shape change fails loud instead of silently+ # syncing zero rows.+ session = MockSession.return_value+ _wire(session, [_response(None, drop_data_key=True)])++ with pytest.raises(ValueError, match="data_selector"):+ _rows(_source("Members", _make_manager()))++ @parameterized.expand(+ [+ ("Members", "/members"),+ ("Spaces", "/spaces"),+ ("Posts", "/posts"),+ ("Events", "/events"),+ ("Plans", "/plans"),+ ("Subscriptions", "/subscriptions"),+ ("Purchases", "/purchases"),+ ("Tags", "/tags"),+ ("Badges", "/badges"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_endpoint_paths(self, endpoint: str, path: str, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response([], total_pages=1)])++ _rows(_source(endpoint, _make_manager()))++ assert snapshots[0]["url"] == f"https://api.mn.co/admin/v1/networks/1234{path}"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_subscriptions_row_hoists_nested_id(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ [+ {+ "member_id": 9,+ "subscription": {"id": 55, "purchased_at": "2026-01-01T00:00:00Z"},+ }+ ],+ total_pages=1,+ )+ ],+ )++ rows = _rows(_source("Subscriptions", _make_manager()))++ assert rows == [+ {+ "member_id": 9,+ "subscription": {"id": 55, "purchased_at": "2026-01-01T00:00:00Z"},+ "id": 55,+ }+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_purchases_row_hoists_nested_fields(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ [+ {+ "member_id": 9,+ "purchase": {+ "id": 77,+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-02T00:00:00Z",+ },+ }+ ],+ total_pages=1,+ )+ ],+ )++ rows = _rows(_source("Purchases", _make_manager()))++ assert rows[0]["id"] == 77+ assert rows[0]["created_at"] == "2026-01-01T00:00:00Z"+ assert rows[0]["updated_at"] == "2026-01-02T00:00:00Z"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_members_row_is_not_flattened(self, MockSession) -> None:+ # Only Subscriptions and Purchases need the nested-id fixup.+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1, "email": "[email protected]"}], total_pages=1)])++ rows = _rows(_source("Members", _make_manager()))++ assert rows == [{"id": 1, "email": "[email protected]"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_partitioning_uses_created_at(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([], total_pages=1)])++ response = _source("Members", _make_manager())++ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.primary_keys == ["id"]+++class TestValidateCredentials:+ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("key", "1234") == (True, 200)++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_unauthorized(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ assert validate_credentials("key", "1234") == (False, 401)++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", "1234") == (False, None)++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_probes_me_endpoint_with_bearer_header_and_user_agent(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("key", "1234")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.mn.co/admin/v1/networks/1234/me"+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"+ assert call.kwargs["headers"]["User-Agent"] == USER_AGENT+++class TestCheckEndpointAccess:+ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_reachable_endpoint_returns_none(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert check_endpoint_access("key", "1234", "Members") is None++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_forbidden_returns_vendor_message(self, mock_session) -> None:+ response = mock.MagicMock(status_code=403)+ response.json.return_value = {+ "error": "forbidden",+ "message": "Token is missing the members scope",+ "status": 403,+ }+ mock_session.return_value.get.return_value = response++ assert check_endpoint_access("key", "1234", "Members") == "Token is missing the members scope"++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_forbidden_without_parseable_body_falls_back_to_generic_message(self, mock_session) -> None:+ response = mock.MagicMock(status_code=403)+ response.json.side_effect = ValueError("not json")+ mock_session.return_value.get.return_value = response++ assert check_endpoint_access("key", "1234", "Members") == (+ "Your Mighty Networks API token doesn't have permission to read this data."+ )++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("not_found", 404)])+ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_non_403_statuses_are_not_treated_as_permission_errors(self, _name, status_code, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert check_endpoint_access("key", "1234", "Members") is None++ @mock.patch(MIGHTY_NETWORKS_SESSION_PATCH)+ def test_transport_error_is_not_treated_as_permission_error(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert check_endpoint_access("key", "1234", "Members") is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks_source.pynew file mode 100644index 000000000000..981790c18fb9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mighty_networks/tests/test_mighty_networks_source.py@@ -0,0 +1,205 @@+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.generated_configs.mightynetworks import (+ MightyNetworksSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.mighty_networks import (+ MightyNetworksResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.source import MightyNetworksSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestMightyNetworksSource:+ def setup_method(self):+ self.source = MightyNetworksSource()+ self.team_id = 123+ self.config = MightyNetworksSourceConfig(network_id="1234", api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.MIGHTYNETWORKS++ def test_connection_host_fields_cover_network_id(self):+ # network_id is where the stored api_key is sent; retargeting it must re-require the key.+ assert self.source.connection_host_fields == ["network_id"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "MightyNetworks"+ assert config.label == "Mighty Networks"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/mighty_networks.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mighty-networks"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["network_id", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_network_id_field_is_plain_text(self):+ config = self.source.get_source_config+ network_id_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "network_id"+ )+ assert network_id_field.type == SourceFieldInputConfigType.TEXT+ assert network_id_field.secret is False+ assert network_id_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.mn.co/admin/v1/networks/1234/members?page=1",+ "403 Client Error: Forbidden for url: https://api.mn.co/admin/v1/networks/1234/members?page=1",+ "404 Client Error: Not Found for url: https://api.mn.co/admin/v1/networks/1234/members?page=1",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.mn.co/admin/v1/networks/1234/members",+ "500 Server Error: Internal Server Error for url: https://api.mn.co/admin/v1/networks/1234/members",+ "HTTPSConnectionPool(host='api.mn.co', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_are_all_full_refresh(self):+ # No list endpoint exposes a server-side updated_since/created_since filter.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Members"])+ assert len(schemas) == 1+ assert schemas[0].name == "Members"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("valid", (True, 200), None, True, None),+ ("bad_token", (False, 401), None, False, "Invalid credentials"),+ (+ "missing_scope_at_create",+ (False, 403),+ None,+ True,+ None,+ ),+ (+ "missing_scope_for_schema",+ (False, 403),+ "Members",+ False,+ "Your Mighty Networks API key doesn't have permission to read this table.",+ ),+ (+ "wrong_network_id",+ (False, 404),+ None,+ False,+ "Mighty Networks couldn't find that network ID. Check the network ID and try again.",+ ),+ ("transport_error", (False, None), None, False, "Invalid credentials"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.source.validate_mighty_networks_credentials"+ )+ def test_validate_credentials(+ self, _name, mock_return, schema_name, expected_valid, expected_message, mock_validate+ ):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key", "1234")++ @parameterized.expand([("letters", "abc"), ("empty", ""), ("path_injection", "1234/../evil"), ("float", "12.34")])+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.source.validate_mighty_networks_credentials"+ )+ def test_validate_credentials_rejects_malformed_network_id(self, _name, network_id, mock_validate):+ config = MightyNetworksSourceConfig(network_id=network_id, api_key="key")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert "network ID" in (error_message or "")+ mock_validate.assert_not_called()++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.source.check_endpoint_access"+ )+ def test_get_endpoint_permissions_probes_every_requested_endpoint(self, mock_check_access):+ mock_check_access.side_effect = lambda api_key, network_id, endpoint: (+ "missing scope" if endpoint == "Purchases" else None+ )++ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["Members", "Purchases"])++ assert permissions == {"Members": None, "Purchases": "missing scope"}+ assert mock_check_access.call_count == 2++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is MightyNetworksResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mighty_networks.source.mighty_networks_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_mighty_networks_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Members"+ inputs.team_id = 1+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_mighty_networks_source.assert_called_once_with(+ api_key="key",+ network_id="1234",+ endpoint="Members",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )