Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Impact.com source (#78838)

Tom Owers4d74fae306a3
diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.py
index ecc1af9c5abc..f032b980916c 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -20,7 +20,6 @@ from prometheus_client import Counter
from posthog.caching.login_device_cache import check_and_cache_login_device
from posthog.constants import AUTH_BACKEND_DISPLAY_NAMES
from posthog.exceptions_capture import capture_exception
-from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated
from posthog.models import Organization, PersonalAPIKey, Tag, TaggedItem
from posthog.models.activity_logging.activity_log import (
@@ -909,6 +908,11 @@ def post_login(sender, user, request: HttpRequest, **kwargs):
# Cache device info on signup to skip login notification for this device
if user.last_login is None:
+ # Deferred: importing posthog.geoip loads the MaxMind DB into memory at import time,
+ # which lands on the django.setup() path via this app's ready() and blows the startup
+ # import budget. Keep it at call time so only the signup path pays for it.
+ from posthog.geoip import get_geoip_properties # noqa: PLC0415
+
short_user_agent = get_short_user_agent(request)
ip_address = get_ip_address(request)
country = get_geoip_properties(ip_address).get("$geoip_country_name", "Unknown")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index e6a99d556f60..910b80002616 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -329,6 +329,7 @@ the row lists both.
| huntr | HTTP | requests | ✅ |
| hyperspell | HTTP | requests | ✅ |
| imagga | HTTP | requests | ✅ |
+| impact | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
| infisical | HTTP | requests | ✅ |
| inflowinventory | HTTP | requests | ✅ |
@@ -1060,7 +1061,6 @@ doesn't conflict with concurrent PRs.
- ikas
- illumina_basespace
- imf_data
-- impact
- imperva
- influxdb_cloud
- infor_nexus
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/impact.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/impact.py
index 50fa69c328ad..a7d17daf0040 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/impact.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/impact.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ImpactSourceConfig(config.Config):
- pass
+ account_sid: str
+ auth_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/canonical_descriptions.py
new file mode 100644
index 000000000000..177dfc106941
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/canonical_descriptions.py
@@ -0,0 +1,58 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Campaigns": {
+ "description": "The affiliate programs (campaigns) advertised on your Impact.com account.",
+ "docs_url": "https://integrations.impact.com/brand-api-reference/reference/programs/programs",
+ "columns": {
+ "Id": "Unique identifier for the campaign (program).",
+ "Name": "Name of the campaign.",
+ "State": "Current state of the campaign, e.g. ACTIVE, SETUP, CLOSED.",
+ "Type": "Type of campaign.",
+ },
+ },
+ "MediaPartners": {
+ "description": "The partners (publishers/affiliates) working with your campaigns.",
+ "docs_url": "https://integrations.impact.com/brand-api-reference/reference/partners/partners",
+ "columns": {
+ "Id": "Unique identifier for the partner.",
+ "Name": "Display name of the partner.",
+ "State": "Account state of the partner, e.g. ACTIVE, PENDING, DEACTIVATED.",
+ "PartnerType": "DIRECT or MARKETPLACE.",
+ "DateCreated": "When the partner account was created.",
+ "DateLastUpdated": "When the partner record was last updated.",
+ },
+ },
+ "Invoices": {
+ "description": "Invoices issued for partner payouts.",
+ "docs_url": "https://integrations.impact.com/brand-api-reference/reference/invoices/invoices",
+ "columns": {
+ "Id": "Unique identifier for the invoice.",
+ "CreatedDate": "When the invoice was created.",
+ "MediaId": "Partner (media) id the invoice was issued to.",
+ "MediaName": "Partner (media) name the invoice was issued to.",
+ "Currency": "ISO 4217 currency code of the invoice.",
+ "TotalAmount": "Total invoice amount.",
+ },
+ },
+ "Actions": {
+ "description": "Conversion and commission records tracked against your campaigns.",
+ "docs_url": "https://integrations.impact.com/brand-api-reference/reference/actions/actions",
+ "columns": {
+ "Id": "Unique identifier for the action.",
+ "CampaignId": "Campaign the action was tracked against.",
+ "CampaignName": "Name of the campaign the action was tracked against.",
+ "State": "Approval state of the action: PENDING, APPROVED, or REVERSED.",
+ "Payout": "Commission payout for the action.",
+ "Amount": "Order/transaction amount associated with the action.",
+ "Currency": "ISO 4217 currency code of the payout/amount.",
+ "EventDate": "When the tracked conversion event occurred.",
+ "CreationDate": "When the action record was created.",
+ "LockingDate": "When the action's payout was (or will be) locked/finalized.",
+ "MediaPartnerId": "Partner credited with the action.",
+ "MediaPartnerName": "Name of the partner credited with the action.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/impact.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/impact.py
new file mode 100644
index 000000000000..59af79c5ff9d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/impact.py
@@ -0,0 +1,309 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from requests.auth import HTTPBasicAuth
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.settings import (
+ IMPACT_ENDPOINTS,
+ MAX_LOOKBACK_DAYS,
+ MAX_WINDOW_DAYS,
+ ImpactEndpointConfig,
+)
+
+BASE_URL = "https://api.impact.com"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class ImpactResumeConfig:
+ # Simple (non-fan-out) endpoints: the last page fetched. Re-fetched on resume (merge dedupes).
+ page: Optional[int] = None
+ # Actions: the campaign currently being processed.
+ campaign_id: Optional[int] = None
+ # Actions: ISO start of the date window currently being processed.
+ window_start: Optional[str] = None
+
+
+def _get_session(account_sid: str, auth_token: str) -> requests.Session:
+ session = make_tracked_session(redact_values=(auth_token,))
+ session.auth = HTTPBasicAuth(account_sid, auth_token)
+ # Impact.com returns XML unless explicitly asked for JSON.
+ session.headers["Accept"] = "application/json"
+ return session
+
+
+def _fetch(
+ session: requests.Session, account_sid: str, path: str, params: dict[str, Any], logger: FilteringBoundLogger
+) -> Any:
+ url = f"{BASE_URL}/Advertisers/{account_sid}{path}"
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ logger.error(f"Impact API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+ return response.json()
+
+
+def validate_credentials(account_sid: str, auth_token: str) -> bool:
+ try:
+ session = _get_session(account_sid, auth_token)
+ response = session.get(
+ f"{BASE_URL}/Advertisers/{account_sid}/Campaigns",
+ params={"PageSize": 1},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _safe_int(value: Any) -> Optional[int]:
+ try:
+ return int(value) if value is not None else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _rows_from_response(config: ImpactEndpointConfig, data: Any) -> list[dict[str, Any]]:
+ rows = data.get(config.data_key, []) if isinstance(data, dict) else []
+ return [row for row in rows if isinstance(row, dict)]
+
+
+def _to_datetime(value: Any) -> Optional[datetime]:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+ except ValueError:
+ return None
+ return None
+
+
+def _format_datetime(value: datetime) -> str:
+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _iter_windows(start: datetime, end: datetime, max_days: int) -> Iterator[tuple[datetime, datetime]]:
+ """Yield ascending (start, end) windows no wider than `max_days`, covering [start, end]."""
+ cursor = start
+ step = timedelta(days=max_days)
+ while cursor < end:
+ window_end = min(cursor + step, end)
+ yield cursor, window_end
+ cursor = window_end
+
+
+def _discover_campaign_ids(session: requests.Session, account_sid: str, logger: FilteringBoundLogger) -> list[int]:
+ """Return every campaign id on the account, sorted for deterministic fan-out order."""
+ config = IMPACT_ENDPOINTS["Campaigns"]
+ campaign_ids: set[int] = set()
+ for _page, rows in _paginate_endpoint(session, account_sid, config, {}, logger):
+ for row in rows:
+ campaign_id = _safe_int(row.get("Id"))
+ if campaign_id is not None:
+ campaign_ids.add(campaign_id)
+ return sorted(campaign_ids)
+
+
+def _paginate_endpoint(
+ session: requests.Session,
+ account_sid: str,
+ config: ImpactEndpointConfig,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+ start_page: int = 1,
+) -> Iterator[tuple[int, list[dict[str, Any]]]]:
+ """Yield (page_number, rows) from `start_page` to the last page (`@numpages`)."""
+ page = start_page
+ while True:
+ page_params = {**params, "Page": page, "PageSize": config.page_size}
+ data = _fetch(session, account_sid, config.path, page_params, logger)
+ rows = _rows_from_response(config, data)
+ yield page, rows
+
+ num_pages = _safe_int(data.get("@numpages")) if isinstance(data, dict) else None
+ if not rows or (num_pages is not None and page >= num_pages):
+ break
+ page += 1
+
+
+def _windows_for_actions(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> list[tuple[datetime, datetime]]:
+ now = datetime.now(UTC)
+ max_lookback_start = now - timedelta(days=MAX_LOOKBACK_DAYS)
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ cursor_start = _to_datetime(db_incremental_field_last_value)
+ start = max(cursor_start, max_lookback_start) if cursor_start is not None else max_lookback_start
+ else:
+ start = max_lookback_start
+
+ if start >= now:
+ return []
+ return list(_iter_windows(start, now, MAX_WINDOW_DAYS))
+
+
+def _resume_index(work_items: list[tuple[Any, int]], resume: Optional[ImpactResumeConfig]) -> int:
+ """Find where to restart a (window, campaign_id) work list from a saved bookmark.
+
+ Returns the index of the last-yielded item so it's re-processed (merge dedupes) and
+ everything after it runs. Falls back to the start when there's no bookmark or it no longer
+ matches (e.g. the campaign list changed between runs).
+ """
+ if resume is None or resume.campaign_id is None:
+ return 0
+ for index, (window, campaign_id) in enumerate(work_items):
+ window_start = window[0].isoformat() if window is not None else None
+ if campaign_id == resume.campaign_id and window_start == resume.window_start:
+ return index
+ return 0
+
+
+def _get_rows_simple(
+ session: requests.Session,
+ account_sid: str,
+ config: ImpactEndpointConfig,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resumable_source_manager: ResumableSourceManager[ImpactResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ params: dict[str, Any] = {}
+ if config.incremental_start_param and should_use_incremental_field and db_incremental_field_last_value is not None:
+ cursor = _to_datetime(db_incremental_field_last_value)
+ if cursor is not None:
+ params[config.incremental_start_param] = _format_datetime(cursor)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_page = resume.page if resume and resume.page else 1
+
+ for page, rows in _paginate_endpoint(session, account_sid, config, params, logger, start_page=start_page):
+ if rows:
+ yield rows
+ # Save after yielding: a crash re-fetches this same page and merge dedupes it.
+ resumable_source_manager.save_state(ImpactResumeConfig(page=page))
+
+
+def _get_rows_actions(
+ session: requests.Session,
+ account_sid: str,
+ config: ImpactEndpointConfig,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resumable_source_manager: ResumableSourceManager[ImpactResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ # Only the Actions config reaches this path, and it always declares both date params.
+ assert config.incremental_start_param is not None
+ assert config.incremental_end_param is not None
+ start_param = config.incremental_start_param
+ end_param = config.incremental_end_param
+
+ campaign_ids = _discover_campaign_ids(session, account_sid, logger)
+ if not campaign_ids:
+ logger.warning("Impact: no campaigns found for account; nothing to sync for Actions")
+ return
+
+ windows = _windows_for_actions(should_use_incremental_field, db_incremental_field_last_value)
+ # Windows OUTER, campaigns INNER so rows arrive in globally ascending date order across every
+ # campaign — required for the `sort_mode="asc"` watermark to advance monotonically.
+ work_items = [(window, campaign_id) for window in windows for campaign_id in campaign_ids]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = _resume_index(work_items, resume)
+ if start_index > 0:
+ logger.debug(f"Impact: resuming Actions from item {start_index}/{len(work_items)}")
+
+ for window, campaign_id in work_items[start_index:]:
+ params: dict[str, Any] = {
+ "CampaignId": campaign_id,
+ start_param: _format_datetime(window[0]),
+ end_param: _format_datetime(window[1]),
+ }
+ for _page, rows in _paginate_endpoint(session, account_sid, config, params, logger):
+ if rows:
+ yield rows
+ # Save once the whole (window, campaign) item is drained. A crash re-fetches it from page
+ # 1 on resume; merge dedupes the re-yielded rows.
+ resumable_source_manager.save_state(
+ ImpactResumeConfig(campaign_id=campaign_id, window_start=window[0].isoformat())
+ )
+
+
+def get_rows(
+ account_sid: str,
+ auth_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ImpactResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = IMPACT_ENDPOINTS[endpoint]
+ session = _get_session(account_sid, auth_token)
+
+ if config.requires_campaign_fanout:
+ yield from _get_rows_actions(
+ session,
+ account_sid,
+ config,
+ logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ resumable_source_manager,
+ )
+ return
+
+ yield from _get_rows_simple(
+ session,
+ account_sid,
+ config,
+ logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ resumable_source_manager,
+ )
+
+
+def impact_source(
+ account_sid: str,
+ auth_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ImpactResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = IMPACT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ account_sid=account_sid,
+ auth_token=auth_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/settings.py
new file mode 100644
index 000000000000..f6133560501e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Impact rejects an Actions StartDate/EndDate (or ActionDateStart/ActionDateEnd) span wider than
+# 45 days; 44 keeps every window safely inside the inclusive limit.
+MAX_WINDOW_DAYS = 44
+
+# Impact rejects an Actions StartDate more than 3 years in the past. This also doubles as the
+# default backfill depth on the first sync (or a full refresh), since there's no cursor yet.
+MAX_LOOKBACK_DAYS = 365 * 3
+
+DEFAULT_PAGE_SIZE = 1000
+# Impact's documented minimum PageSize for the Actions endpoint.
+ACTIONS_PAGE_SIZE = 2000
+
+
+@dataclass
+class ImpactEndpointConfig:
+ name: str
+ # Path relative to https://api.impact.com/Advertisers/{account_sid}.
+ path: str
+ # Key the response wraps its row array under.
+ data_key: str
+ primary_keys: list[str]
+ # Actions is the only endpoint that requires a CampaignId filter, so it's fetched once per
+ # campaign discovered from the Campaigns endpoint.
+ requires_campaign_fanout: bool = False
+ # Actions is also the only endpoint whose date filter is capped at a 45-day span, so history
+ # is walked in bounded windows.
+ date_windowed: bool = False
+ incremental_start_param: Optional[str] = None
+ incremental_end_param: Optional[str] = None
+ page_size: int = DEFAULT_PAGE_SIZE
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+IMPACT_ENDPOINTS: dict[str, ImpactEndpointConfig] = {
+ "Campaigns": ImpactEndpointConfig(
+ name="Campaigns",
+ path="/Campaigns",
+ data_key="Campaigns",
+ primary_keys=["Id"],
+ description="The affiliate programs (campaigns) in your Impact.com account. Full refresh only.",
+ ),
+ "MediaPartners": ImpactEndpointConfig(
+ name="MediaPartners",
+ path="/MediaPartners",
+ data_key="Partners",
+ primary_keys=["Id"],
+ incremental_start_param="startDate",
+ incremental_fields=[
+ {
+ "label": "DateLastUpdated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "DateLastUpdated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description="The partners (publishers/affiliates) in your Impact.com account.",
+ ),
+ "Invoices": ImpactEndpointConfig(
+ name="Invoices",
+ path="/Invoices",
+ data_key="Invoices",
+ primary_keys=["Id"],
+ description="Partner invoices, returned most recent first. Full refresh only.",
+ ),
+ "Actions": ImpactEndpointConfig(
+ name="Actions",
+ path="/Actions",
+ data_key="Actions",
+ primary_keys=["Id"],
+ requires_campaign_fanout=True,
+ date_windowed=True,
+ incremental_start_param="ActionDateStart",
+ incremental_end_param="ActionDateEnd",
+ page_size=ACTIONS_PAGE_SIZE,
+ partition_key="EventDate",
+ incremental_fields=[
+ {
+ "label": "EventDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "EventDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description=(
+ "Conversion and commission records, fetched per campaign in 44-day windows "
+ "(an Impact.com API limit). Only syncs the last 3 years on initial sync."
+ ),
+ ),
+}
+
+ENDPOINTS = tuple(IMPACT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in IMPACT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/source.py
index 64e04a6e4a38..d33dd837a1e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/source.py
@@ -1,19 +1,41 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.impact import ImpactSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.impact import (
+ ImpactResumeConfig,
+ impact_source,
+ validate_credentials as validate_impact_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.settings import (
+ ENDPOINTS,
+ IMPACT_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ImpactSource(SimpleSource[ImpactSourceConfig]):
+class ImpactSource(ResumableSource[ImpactSourceConfig, ImpactResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://integrations.impact.com/brand-api-reference/readme/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.IMPACT
@@ -25,7 +47,103 @@ class ImpactSource(SimpleSource[ImpactSourceConfig]):
category=DataWarehouseSourceCategory.ADVERTISING,
keywords=["impact.com", "impact radius"],
label="impact.com",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your impact.com Account SID and Auth Token to pull your partnership data into the PostHog Data warehouse.
+
+Find these in impact.com under **Settings > Technical > API**. Create a Read-Only access token, then copy its Account SID and Auth Token below.""",
iconPath="/static/services/impact.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/impact",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="account_sid",
+ label="Account SID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="auth_token",
+ label="Auth token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.impact.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.impact.com": "Your Impact.com Account SID or Auth Token is invalid. Check your credentials, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.impact.com": "Your Impact.com token does not have access to this data. Check the token's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ImpactSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=IMPACT_ENDPOINTS[endpoint].should_sync_default,
+ description=IMPACT_ENDPOINTS[endpoint].description,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: ImpactSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_impact_credentials(config.account_sid, config.auth_token):
+ return True, None
+
+ return False, "Invalid Impact.com Account SID or Auth Token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ImpactResumeConfig]:
+ return ResumableSourceManager[ImpactResumeConfig](inputs, ImpactResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ImpactSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ImpactResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return impact_source(
+ account_sid=config.account_sid,
+ auth_token=config.auth_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py
new file mode 100644
index 000000000000..4383ca6ee20a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py
@@ -0,0 +1,398 @@
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact import impact
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.impact import (
+ ImpactResumeConfig,
+ _discover_campaign_ids,
+ _format_datetime,
+ _iter_windows,
+ _paginate_endpoint,
+ _resume_index,
+ _rows_from_response,
+ _safe_int,
+ _to_datetime,
+ _windows_for_actions,
+ get_rows,
+ impact_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.settings import IMPACT_ENDPOINTS
+
+
+class FakeResumableManager:
+ """Minimal stand-in for ResumableSourceManager that records saved state in memory."""
+
+ def __init__(self, state: Optional[ImpactResumeConfig] = None):
+ self.state = state
+ self.saved: list[ImpactResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[ImpactResumeConfig]:
+ return self.state
+
+ def save_state(self, data: ImpactResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestIterWindows:
+ def test_range_shorter_than_max_is_single_window(self) -> None:
+ start = datetime(2024, 1, 1, tzinfo=UTC)
+ end = datetime(2024, 1, 10, tzinfo=UTC)
+ assert list(_iter_windows(start, end, max_days=44)) == [(start, end)]
+
+ def test_range_is_chunked_ascending_and_contiguous(self) -> None:
+ start = datetime(2024, 1, 1, tzinfo=UTC)
+ end = datetime(2024, 6, 1, tzinfo=UTC)
+ windows = list(_iter_windows(start, end, max_days=44))
+
+ assert len(windows) > 1
+ assert windows[0][0] == start
+ assert windows[-1][1] == end
+ for i, (window_start, window_end) in enumerate(windows):
+ assert window_start < window_end
+ assert (window_end - window_start).days <= 44
+ if i > 0:
+ assert window_start == windows[i - 1][1]
+
+
+class TestToDatetime:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("naive_string", "2024-01-01T00:00:00", datetime(2024, 1, 1, tzinfo=UTC)),
+ ("z_string", "2024-01-01T00:00:00Z", datetime(2024, 1, 1, tzinfo=UTC)),
+ ("garbage", "not-a-date", None),
+ ]
+ )
+ def test_to_datetime(self, _name: str, value: Any, expected: Optional[datetime]) -> None:
+ assert _to_datetime(value) == expected
+
+ def test_naive_datetime_gets_utc(self) -> None:
+ assert _to_datetime(datetime(2024, 1, 1)) == datetime(2024, 1, 1, tzinfo=UTC)
+
+
+class TestFormatDatetime:
+ def test_formats_as_utc_iso_with_z(self) -> None:
+ assert _format_datetime(datetime(2024, 3, 5, 12, 30, 0, tzinfo=UTC)) == "2024-03-05T12:30:00Z"
+
+
+class TestSafeInt:
+ @parameterized.expand(
+ [
+ ("string", "3", 3),
+ ("int", 3, 3),
+ ("none", None, None),
+ ("garbage", "abc", None),
+ ]
+ )
+ def test_safe_int(self, _name: str, value: Any, expected: Optional[int]) -> None:
+ assert _safe_int(value) == expected
+
+
+class TestRowsFromResponse:
+ def test_reads_wrapped_key(self) -> None:
+ data = {"Campaigns": [{"Id": 1}, {"Id": 2}]}
+ assert _rows_from_response(IMPACT_ENDPOINTS["Campaigns"], data) == [{"Id": 1}, {"Id": 2}]
+
+ def test_missing_key_is_empty(self) -> None:
+ assert _rows_from_response(IMPACT_ENDPOINTS["Campaigns"], {"@page": "1"}) == []
+
+ def test_non_dict_rows_are_dropped(self) -> None:
+ data = {"Campaigns": [{"Id": 1}, "junk", None]}
+ assert _rows_from_response(IMPACT_ENDPOINTS["Campaigns"], data) == [{"Id": 1}]
+
+ def test_non_dict_response_is_empty(self) -> None:
+ assert _rows_from_response(IMPACT_ENDPOINTS["Campaigns"], ["junk"]) == []
+
+
+class TestWindowsForActions:
+ @freeze_time("2024-06-01")
+ def test_full_refresh_backfills_max_lookback(self) -> None:
+ windows = _windows_for_actions(False, None)
+ assert windows[0][0] == datetime(2021, 6, 2, tzinfo=UTC)
+ assert windows[-1][1] == datetime(2024, 6, 1, tzinfo=UTC)
+
+ @freeze_time("2024-06-01")
+ def test_incremental_windows_start_at_last_value(self) -> None:
+ last_value = datetime(2024, 5, 1, tzinfo=UTC)
+ windows = _windows_for_actions(True, last_value)
+ assert windows[0][0] == last_value
+
+ @freeze_time("2024-06-01")
+ def test_cursor_older_than_max_lookback_is_clamped(self) -> None:
+ # Impact rejects a StartDate more than 3 years back, so a stale cursor is clamped rather
+ # than sent as-is.
+ windows = _windows_for_actions(True, datetime(2015, 1, 1, tzinfo=UTC))
+ assert windows[0][0] == datetime(2021, 6, 2, tzinfo=UTC)
+
+ @freeze_time("2024-06-01")
+ def test_future_cursor_yields_no_windows(self) -> None:
+ assert _windows_for_actions(True, datetime(2025, 1, 1, tzinfo=UTC)) == []
+
+
+class TestPaginateEndpoint:
+ def test_stops_when_page_reaches_numpages(self) -> None:
+ responses = [
+ {"Campaigns": [{"Id": 1}], "@numpages": "2"},
+ {"Campaigns": [{"Id": 2}], "@numpages": "2"},
+ ]
+ with patch.object(impact, "_fetch", side_effect=responses):
+ pages = list(_paginate_endpoint(MagicMock(), "sid", IMPACT_ENDPOINTS["Campaigns"], {}, MagicMock()))
+ assert [p for p, _rows in pages] == [1, 2]
+ assert [rows for _p, rows in pages] == [[{"Id": 1}], [{"Id": 2}]]
+
+ def test_stops_on_empty_page_even_without_numpages(self) -> None:
+ responses = [{"Campaigns": [{"Id": 1}]}, {"Campaigns": []}]
+ with patch.object(impact, "_fetch", side_effect=responses) as mock_fetch:
+ pages = list(_paginate_endpoint(MagicMock(), "sid", IMPACT_ENDPOINTS["Campaigns"], {}, MagicMock()))
+ assert len(pages) == 2
+ assert mock_fetch.call_count == 2
+
+ def test_single_page_stops_immediately(self) -> None:
+ with patch.object(impact, "_fetch", return_value={"Campaigns": [{"Id": 1}], "@numpages": "1"}):
+ pages = list(_paginate_endpoint(MagicMock(), "sid", IMPACT_ENDPOINTS["Campaigns"], {}, MagicMock()))
+ assert len(pages) == 1
+
+ def test_start_page_is_honored(self) -> None:
+ with patch.object(impact, "_fetch", return_value={"Campaigns": [], "@numpages": "1"}) as mock_fetch:
+ list(_paginate_endpoint(MagicMock(), "sid", IMPACT_ENDPOINTS["Campaigns"], {}, MagicMock(), start_page=3))
+ assert mock_fetch.call_args.args[3]["Page"] == 3
+
+
+class TestDiscoverCampaignIds:
+ def test_dedupes_and_sorts(self) -> None:
+ with patch.object(
+ impact,
+ "_fetch",
+ return_value={"Campaigns": [{"Id": 3}, {"Id": 1}, {"Id": 2}, {"Id": 1}], "@numpages": "1"},
+ ):
+ assert _discover_campaign_ids(MagicMock(), "sid", MagicMock()) == [1, 2, 3]
+
+ def test_no_campaigns_is_empty(self) -> None:
+ with patch.object(impact, "_fetch", return_value={"Campaigns": [], "@numpages": "1"}):
+ assert _discover_campaign_ids(MagicMock(), "sid", MagicMock()) == []
+
+
+class TestResumeIndex:
+ def test_no_resume_starts_at_zero(self) -> None:
+ assert _resume_index([((datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 2, tzinfo=UTC)), 1)], None) == 0
+
+ def test_matching_bookmark_resumes_at_that_index(self) -> None:
+ window = (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 2, tzinfo=UTC))
+ work_items = [(window, 1), (window, 2)]
+ resume = ImpactResumeConfig(campaign_id=2, window_start=window[0].isoformat())
+ assert _resume_index(work_items, resume) == 1
+
+ def test_stale_bookmark_falls_back_to_start(self) -> None:
+ window = (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 2, tzinfo=UTC))
+ work_items = [(window, 1)]
+ resume = ImpactResumeConfig(campaign_id=999, window_start=window[0].isoformat())
+ assert _resume_index(work_items, resume) == 0
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ with patch.object(impact, "make_tracked_session") as mock_session:
+ response = MagicMock()
+ response.status_code = status
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials("sid", "token") is expected
+
+ def test_exception_is_false(self) -> None:
+ with patch.object(impact, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("sid", "token") is False
+
+
+class TestGetRowsSimple:
+ def test_single_page_endpoint(self) -> None:
+ manager = FakeResumableManager()
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", return_value={"Campaigns": [{"Id": 1}], "@numpages": "1"}),
+ ):
+ batches = list(get_rows("sid", "token", "Campaigns", MagicMock(), manager)) # type: ignore[arg-type]
+ assert batches == [[{"Id": 1}]]
+ assert [s.page for s in manager.saved] == [1]
+
+ def test_multi_page_endpoint_saves_state_per_page(self) -> None:
+ manager = FakeResumableManager()
+ responses = [
+ {"Campaigns": [{"Id": 1}], "@numpages": "2"},
+ {"Campaigns": [{"Id": 2}], "@numpages": "2"},
+ ]
+ with patch.object(impact, "make_tracked_session"), patch.object(impact, "_fetch", side_effect=responses):
+ batches = list(get_rows("sid", "token", "Campaigns", MagicMock(), manager)) # type: ignore[arg-type]
+ assert batches == [[{"Id": 1}], [{"Id": 2}]]
+ assert [s.page for s in manager.saved] == [1, 2]
+
+ def test_resume_starts_at_saved_page(self) -> None:
+ manager = FakeResumableManager(state=ImpactResumeConfig(page=2))
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", return_value={"Campaigns": [], "@numpages": "2"}) as mock_fetch,
+ ):
+ list(get_rows("sid", "token", "Campaigns", MagicMock(), manager)) # type: ignore[arg-type]
+ assert mock_fetch.call_args.args[3]["Page"] == 2
+
+ def test_incremental_param_sent_when_using_incremental_field(self) -> None:
+ manager = FakeResumableManager()
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", return_value={"Partners": [], "@numpages": "1"}) as mock_fetch,
+ ):
+ list(
+ get_rows(
+ "sid",
+ "token",
+ "MediaPartners",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00",
+ )
+ )
+ assert mock_fetch.call_args.args[3]["startDate"] == "2024-01-01T00:00:00Z"
+
+ def test_no_incremental_param_when_not_incremental(self) -> None:
+ manager = FakeResumableManager()
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", return_value={"Partners": [], "@numpages": "1"}) as mock_fetch,
+ ):
+ list(get_rows("sid", "token", "MediaPartners", MagicMock(), manager)) # type: ignore[arg-type]
+ assert "startDate" not in mock_fetch.call_args.args[3]
+
+
+class TestGetRowsActions:
+ @freeze_time("2024-06-01")
+ def test_fanout_yields_per_campaign_and_saves_state(self) -> None:
+ manager = FakeResumableManager()
+
+ def fake_fetch(session: Any, account_sid: str, path: str, params: Any, logger: Any) -> Any:
+ if path == "/Campaigns":
+ return {"Campaigns": [{"Id": 10}, {"Id": 20}], "@numpages": "1"}
+ return {"Actions": [{"Id": 1, "CampaignId": params["CampaignId"]}], "@numpages": "1"}
+
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", side_effect=fake_fetch),
+ ):
+ # A last-updated value one day back keeps this to a single window per campaign.
+ batches = list(
+ get_rows(
+ "sid",
+ "token",
+ "Actions",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 31, tzinfo=UTC),
+ )
+ )
+
+ campaign_ids = {row["CampaignId"] for batch in batches for row in batch}
+ assert campaign_ids == {10, 20}
+ # One save per (window, campaign) work item: two campaigns, one window each.
+ assert len(manager.saved) == 2 == len(batches)
+ assert {s.campaign_id for s in manager.saved} == {10, 20}
+
+ @freeze_time("2024-06-01")
+ def test_no_campaigns_yields_nothing(self) -> None:
+ manager = FakeResumableManager()
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", return_value={"Campaigns": [], "@numpages": "1"}),
+ ):
+ batches = list(get_rows("sid", "token", "Actions", MagicMock(), manager)) # type: ignore[arg-type]
+ assert batches == []
+
+ @freeze_time("2024-06-01")
+ def test_resume_skips_campaigns_before_the_bookmark(self) -> None:
+ # An incremental cursor collapses the run to a single window, starting exactly at the
+ # cursor value. Bookmarking campaign 20 (the middle of three) re-fetches it plus
+ # everything after (merge dedupes the re-fetch); campaign 10 is skipped entirely.
+ last_value = datetime(2024, 5, 30, tzinfo=UTC)
+ manager = FakeResumableManager(state=ImpactResumeConfig(campaign_id=20, window_start=last_value.isoformat()))
+ seen_campaigns: list[int] = []
+
+ def fake_fetch(session: Any, account_sid: str, path: str, params: Any, logger: Any) -> Any:
+ if path == "/Campaigns":
+ return {"Campaigns": [{"Id": 10}, {"Id": 20}, {"Id": 30}], "@numpages": "1"}
+ seen_campaigns.append(params["CampaignId"])
+ return {"Actions": [], "@numpages": "1"}
+
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", side_effect=fake_fetch),
+ ):
+ list(
+ get_rows(
+ "sid",
+ "token",
+ "Actions",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+ assert seen_campaigns == [20, 30]
+
+ @freeze_time("2024-06-01")
+ def test_paired_date_params_sent(self) -> None:
+ manager = FakeResumableManager()
+
+ def fake_fetch(session: Any, account_sid: str, path: str, params: Any, logger: Any) -> Any:
+ if path == "/Campaigns":
+ return {"Campaigns": [{"Id": 10}], "@numpages": "1"}
+ assert "ActionDateStart" in params
+ assert "ActionDateEnd" in params
+ return {"Actions": [], "@numpages": "1"}
+
+ with (
+ patch.object(impact, "make_tracked_session"),
+ patch.object(impact, "_fetch", side_effect=fake_fetch),
+ ):
+ list(
+ get_rows(
+ "sid",
+ "token",
+ "Actions",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 30, tzinfo=UTC),
+ )
+ )
+
+
+class TestImpactSourceResponse:
+ @parameterized.expand(
+ [
+ ("Campaigns", ["Id"], None),
+ ("MediaPartners", ["Id"], None),
+ ("Invoices", ["Id"], None),
+ ("Actions", ["Id"], "EventDate"),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str], partition_key: Optional[str]) -> None:
+ response = impact_source("sid", "token", endpoint, MagicMock(), FakeResumableManager()) # type: ignore[arg-type]
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pks
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.partition_format == "month"
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact_source.py
new file mode 100644
index 000000000000..75cb3b1ca661
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact_source.py
@@ -0,0 +1,128 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.impact import ImpactSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.impact import ImpactResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.impact.source import ImpactSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _inputs(schema_name: str = "Actions", **overrides: object) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", True)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", "2024-01-01T00:00:00")
+ return inputs
+
+
+class TestImpactSourceClass:
+ def test_source_type(self) -> None:
+ assert ImpactSource().source_type == ExternalDataSourceType.IMPACT
+
+ def test_get_source_config_fields(self) -> None:
+ config = ImpactSource().get_source_config
+ assert config.name.value == "Impact"
+ assert len(config.fields) == 2
+
+ account_sid, auth_token = config.fields
+ assert isinstance(account_sid, SourceFieldInputConfig)
+ assert account_sid.name == "account_sid"
+ assert account_sid.type == SourceFieldInputConfigType.TEXT
+ assert account_sid.required is True
+ assert account_sid.secret is False
+
+ assert isinstance(auth_token, SourceFieldInputConfig)
+ assert auth_token.name == "auth_token"
+ assert auth_token.type == SourceFieldInputConfigType.PASSWORD
+ assert auth_token.required is True
+ assert auth_token.secret is True
+
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/impact"
+
+ def test_no_unreleased_flag(self) -> None:
+ # A finished source ships visible; unreleasedSource must not be set.
+ assert ImpactSource().get_source_config.unreleasedSource is not True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert ImpactSource.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = ImpactSource().get_schemas(ImpactSourceConfig(account_sid="s", auth_token="t"), team_id=1)
+ names = {s.name for s in schemas}
+ assert names == {"Campaigns", "MediaPartners", "Invoices", "Actions"}
+
+ @parameterized.expand(
+ [
+ ("Actions", True),
+ ("MediaPartners", True),
+ ("Campaigns", False),
+ ("Invoices", False),
+ ]
+ )
+ def test_supports_incremental_per_endpoint(self, endpoint: str, expected: bool) -> None:
+ schemas = ImpactSource().get_schemas(
+ ImpactSourceConfig(account_sid="s", auth_token="t"), team_id=1, names=[endpoint]
+ )
+ assert len(schemas) == 1
+ assert schemas[0].supports_incremental is expected
+ assert schemas[0].supports_append is expected
+
+ def test_names_filter_narrows_schemas(self) -> None:
+ schemas = ImpactSource().get_schemas(
+ ImpactSourceConfig(account_sid="s", auth_token="t"), team_id=1, names=["Campaigns"]
+ )
+ assert [s.name for s in schemas] == ["Campaigns"]
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ tables = ImpactSource().get_documented_tables()
+ names = {t["name"] for t in tables}
+ assert names == {"Campaigns", "MediaPartners", "Invoices", "Actions"}
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid Impact.com Account SID or Auth Token"),
+ ]
+ )
+ def test_validate_credentials(self, _name: str, api_result: bool, ok: bool, err: Optional[str]) -> None:
+ with patch.object(source_module, "validate_impact_credentials", return_value=api_result):
+ result = ImpactSource().validate_credentials(ImpactSourceConfig(account_sid="s", auth_token="t"), team_id=1)
+ assert result == (ok, err)
+
+ def test_get_non_retryable_errors_cover_auth(self) -> None:
+ errors = ImpactSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_get_resumable_source_manager_bound_to_data_class(self) -> None:
+ manager = ImpactSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ImpactResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ manager = MagicMock()
+ inputs = _inputs(schema_name="Actions")
+ with patch.object(source_module, "impact_source") as mock_impact_source:
+ ImpactSource().source_for_pipeline(ImpactSourceConfig(account_sid="s", auth_token="t"), manager, inputs)
+
+ mock_impact_source.assert_called_once()
+ kwargs = mock_impact_source.call_args.kwargs
+ assert kwargs["account_sid"] == "s"
+ assert kwargs["auth_token"] == "t"
+ assert kwargs["endpoint"] == "Actions"
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00"
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ manager = MagicMock()
+ inputs = _inputs(should_use_incremental_field=False)
+ with patch.object(source_module, "impact_source") as mock_impact_source:
+ ImpactSource().source_for_pipeline(ImpactSourceConfig(account_sid="s", auth_token="t"), manager, inputs)
+
+ assert mock_impact_source.call_args.kwargs["db_incremental_field_last_value"] is None