: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 genesys cloud source (#110180)
Tom Owersf0615a7196b7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d4153e129b68..e7941beb94ce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -326,6 +326,7 @@ the row lists both.| g2 | HTTP | requests | ✅ || gainsight_cs | HTTP | requests | ✅ || gainsight_px | HTTP | requests | ✅ |+| genesys_cloud | HTTP | requests | ✅ || gerrit | HTTP | requests | ✅ || gitbook | HTTP | requests | ✅ || gitea | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |@@ -1110,7 +1111,6 @@ doesn't conflict with concurrent PRs.- gcp_security_command_center- gdelt- gem-- genesys_cloud- gerrit- getdx- getstreamdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/genesyscloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/genesyscloud.pyindex 9891e483f7d3..c9c2385dea95 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/genesyscloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/genesyscloud.py@@ -1,9 +1,29 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass GenesysCloudSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ region: Literal[+ "mypurecloud.com",+ "use2.us-gov-pure.cloud",+ "usw2.pure.cloud",+ "cac1.pure.cloud",+ "sae1.pure.cloud",+ "mypurecloud.ie",+ "euw2.pure.cloud",+ "mypurecloud.de",+ "euc2.pure.cloud",+ "mec1.pure.cloud",+ "aps1.pure.cloud",+ "apne2.pure.cloud",+ "apne3.pure.cloud",+ "mypurecloud.jp",+ "mypurecloud.com.au",+ ] = config.value(default="mypurecloud.com")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..84f765ce94f4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py@@ -0,0 +1,86 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DETAILS_QUERY_DOCS_URL = "https://developer.genesys.cloud/analyticsdatamanagement/analytics/detail/conversation-query"++_CONVERSATION_COLUMNS = {+ "conversationId": "Unique identifier for the conversation.",+ "conversationStart": "The start time of the conversation.",+ "conversationEnd": "The end time of the conversation. Empty while the conversation is in progress.",+ "originatingDirection": "The original direction of the conversation (inbound or outbound).",+ "conversationInitiator": "Indicates the participant purpose of the participant initiating a message conversation.",+ "customerParticipation": "Indicates a messaging conversation in which the customer participated by sending at least one message.",+ "divisionIds": "Identifier(s) of division(s) associated with the conversation.",+ "externalTag": "External tag for the conversation.",+ "selfServed": "Indicates whether all flow sessions were self serviced.",+ "mediaStatsMinConversationMos": "The lowest estimated average MOS among all the audio streams belonging to this conversation.",+ "mediaStatsMinConversationRFactor": "The lowest R-factor value among all of the audio streams belonging to this conversation.",+ "evaluations": "Quality evaluations associated with this conversation.",+ "surveys": "Surveys associated with this conversation.",+ "resolutions": "Resolutions associated with this conversation.",+ "participants": "Participants in the conversation, each with their sessions, segments, and metrics.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "conversations": {+ "description": "Genesys Cloud conversations across all media types (voice, chat, email, messaging, callbacks), from the analytics conversation details query.",+ "docs_url": _DETAILS_QUERY_DOCS_URL,+ "columns": _CONVERSATION_COLUMNS,+ },+ "calls": {+ "description": "Genesys Cloud voice conversations (phone calls), from the analytics conversation details query.",+ "docs_url": _DETAILS_QUERY_DOCS_URL,+ "columns": _CONVERSATION_COLUMNS,+ },+ "participants": {+ "description": "One row per participant in a Genesys Cloud conversation (customer, agent, IVR, ACD queue, and so on).",+ "docs_url": _DETAILS_QUERY_DOCS_URL,+ "columns": {+ "conversationId": "Identifier of the conversation this participant belongs to.",+ "conversationStart": "The start time of the conversation this participant belongs to.",+ "conversationEnd": "The end time of the conversation this participant belongs to.",+ "participantId": "Unique identifier for the participant.",+ "participantName": "A human readable name identifying the participant.",+ "purpose": "The participant's purpose, for example customer, agent, ivr, or acd.",+ "userId": "Unique identifier for the Genesys Cloud user, for agent participants.",+ "teamId": "The team ID the user is a member of.",+ "externalContactId": "External contact identifier.",+ "externalOrganizationId": "External organization identifier.",+ "flaggedReason": "Reason for which the participant flagged the conversation.",+ "screenRecording": "Flag determining if a screen recording was started or not.",+ "sessions": "List of sessions associated with this participant, with segments and metrics.",+ },+ },+ "users": {+ "description": "Users (agents and other staff) in the Genesys Cloud organization, including inactive and deleted users.",+ "docs_url": "https://developer.genesys.cloud/useragentman/users/",+ "columns": {+ "id": "The globally unique identifier for the user.",+ "name": "The user's name.",+ "email": "The user's email address.",+ "username": "The user's login name.",+ "state": "The current state for this user (active, inactive, or deleted).",+ "division": "The division to which this user belongs.",+ "team": "The team the user is a member of.",+ "dateLastLogin": "The last time the user logged in using username and password.",+ },+ },+ "queues": {+ "description": "ACD routing queues in the Genesys Cloud organization.",+ "docs_url": "https://developer.genesys.cloud/routing/routing/",+ "columns": {+ "id": "The globally unique identifier for the queue.",+ "name": "The queue name.",+ "description": "The queue description.",+ "division": "The division to which this queue belongs.",+ "dateCreated": "The date the queue was created.",+ "dateModified": "The date of the last modification to the queue.",+ "memberCount": "The total number of members in the queue.",+ "userMemberCount": "The number of user members (non-group members) in the queue.",+ "joinedMemberCount": "The number of joined members in the queue.",+ "mediaSettings": "The media settings for the queue.",+ "scoringMethod": "The scoring method for the queue.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.pynew file mode 100644index 000000000000..aa23a06d2a6c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py@@ -0,0 +1,316 @@+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+import structlog++from posthog.dataclasses import frozen++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.auth import (+ OAuth2Auth,+ OAuth2AuthRequestError,+)+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.genesys_cloud.settings import (+ ANALYTICS_PAGE_SIZE,+ CONVERSATION_DETAILS_PATH,+ GENESYS_CLOUD_ENDPOINTS,+ LISTING_PAGE_SIZE,+ REGIONS,+ GenesysCloudEndpointConfig,+)++logger = structlog.get_logger(__name__)++REQUEST_TIMEOUT_SECONDS = 60+VALIDATION_TIMEOUT_SECONDS = 10++# History read on the first sync and on every full refresh.+INITIAL_HISTORY = timedelta(days=365)+ANALYTICS_WINDOW = timedelta(days=1)+# A conversation keeps changing after it starts (it ends, participants join), so an incremental+# sync reads again from a bit before the watermark. Merge on the primary key removes the overlap.+INCREMENTAL_LOOKBACK = timedelta(days=2)+# The details query pages by page number, which does not scale to very large result sets. A window+# with more hits than this is split in half until it fits, down to MIN_ANALYTICS_WINDOW.+MAX_RESULTS_PER_WINDOW = 10_000+MIN_ANALYTICS_WINDOW = timedelta(seconds=1)+++class InvalidGenesysCloudRegionError(ValueError):+ pass+++@frozen+class GenesysCloudResumeConfig:+ # Analytics endpoints: start of the next window to read (ISO 8601).+ window_start: Optional[str] = None+ # Listing endpoints: next page number to read.+ page_number: Optional[int] = None+++def _validated_region(region: str) -> str:+ if region not in REGIONS:+ raise InvalidGenesysCloudRegionError(f"Unknown Genesys Cloud region: {region!r}")+ return region+++def _make_auth(region: str, client_id: str, client_secret: str) -> OAuth2Auth:+ return OAuth2Auth(+ token_url=f"https://login.{_validated_region(region)}/oauth/token",+ client_id=client_id,+ client_secret=client_secret,+ grant_type="client_credentials",+ client_auth_method="basic",+ )+++def _make_session(region: str, client_id: str, client_secret: str) -> requests.Session:+ session = make_tracked_session(redact_values=(client_secret,))+ session.auth = _make_auth(region, client_id, client_secret)+ return session+++def _api_base_url(region: str) -> str:+ return f"https://api.{_validated_region(region)}"+++def _to_utc(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime(value.year, value.month, value.day, tzinfo=UTC)+ parsed = datetime.fromisoformat(str(value))+ return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _format_instant(value: datetime) -> str:+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"+++def _interval(start: datetime, end: datetime) -> str:+ return f"{_format_instant(start)}/{_format_instant(end)}"+++def _starts_in_window(conversation: dict[str, Any], start: datetime, end: datetime) -> bool:+ # The API can return conversations outside the exact interval (it matches by day), so keep+ # windows disjoint here. That prevents duplicate rows across windows.+ raw = conversation.get("conversationStart")+ if not raw:+ return True+ return start <= _to_utc(raw) < end+++def _to_rows(conversations: list[dict[str, Any]], flatten_participants: bool) -> list[dict[str, Any]]:+ if not flatten_participants:+ return conversations+ rows: list[dict[str, Any]] = []+ for conversation in conversations:+ for participant in conversation.get("participants") or []:+ rows.append(+ {+ **participant,+ "conversationId": conversation.get("conversationId"),+ "conversationStart": conversation.get("conversationStart"),+ "conversationEnd": conversation.get("conversationEnd"),+ }+ )+ return rows+++def _query_window(+ session: requests.Session,+ url: str,+ config: GenesysCloudEndpointConfig,+ start: datetime,+ end: datetime,+) -> Iterator[tuple[list[dict[str, Any]], Optional[datetime]]]:+ """Yield `(conversations, window_end)` per page. `window_end` is set on the last page of a window."""+ page_number = 1+ while True:+ body = {+ **config.query_body,+ "interval": _interval(start, end),+ "order": "asc",+ "orderBy": "conversationStart",+ "paging": {"pageSize": ANALYTICS_PAGE_SIZE, "pageNumber": page_number},+ }+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ data = response.json() or {}+ total_hits = int(data.get("totalHits") or 0)++ if page_number == 1 and total_hits > MAX_RESULTS_PER_WINDOW:+ if end - start > MIN_ANALYTICS_WINDOW:+ middle = start + (end - start) / 2+ yield from _query_window(session, url, config, start, middle)+ yield from _query_window(session, url, config, middle, end)+ return+ logger.warning(+ "genesys_cloud_window_over_result_limit",+ endpoint=config.name,+ interval=_interval(start, end),+ total_hits=total_hits,+ )++ conversations = [c for c in data.get("conversations") or [] if _starts_in_window(c, start, end)]+ returned = len(data.get("conversations") or [])+ is_last_page = returned < ANALYTICS_PAGE_SIZE or page_number * ANALYTICS_PAGE_SIZE >= total_hits+ yield conversations, (end if is_last_page else None)+ if is_last_page:+ return+ page_number += 1+++def _iter_analytics_rows(+ session: requests.Session,+ base_url: str,+ config: GenesysCloudEndpointConfig,+ resumable_source_manager: ResumableSourceManager[GenesysCloudResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> Iterator[list[dict[str, Any]]]:+ now = datetime.now(UTC)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start:+ start = _to_utc(resume.window_start)+ elif db_incremental_field_last_value is not None:+ start = _to_utc(db_incremental_field_last_value) - INCREMENTAL_LOOKBACK+ else:+ start = now - INITIAL_HISTORY++ url = f"{base_url}{CONVERSATION_DETAILS_PATH}"+ while start < now:+ window_end = min(start + ANALYTICS_WINDOW, now)+ for conversations, finished_window_end in _query_window(session, url, config, start, window_end):+ rows = _to_rows(conversations, config.flatten_participants)+ if finished_window_end is not None:+ # Stage the cursor before the yield that covers it, so a resume starts after this window.+ resumable_source_manager.save_state(+ GenesysCloudResumeConfig(window_start=_format_instant(finished_window_end))+ )+ if not rows:+ resumable_source_manager.safe_point()+ if rows:+ yield rows+ start = window_end++ # A later sync must derive a fresh start from its watermark instead of reusing this run's cursor.+ resumable_source_manager.clear_state()+++def _iter_listing_rows(+ session: requests.Session,+ base_url: str,+ config: GenesysCloudEndpointConfig,+ resumable_source_manager: ResumableSourceManager[GenesysCloudResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page_number = resume.page_number if resume is not None and resume.page_number else 1++ url = f"{base_url}{config.path}"+ while True:+ response = session.get(+ url,+ params={**config.params, "pageSize": LISTING_PAGE_SIZE, "pageNumber": page_number},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ data = response.json() or {}+ entities = data.get("entities") or []+ page_count = int(data.get("pageCount") or 0)+ has_next_page = bool(entities) and page_number < page_count+ if has_next_page:+ resumable_source_manager.save_state(GenesysCloudResumeConfig(page_number=page_number + 1))+ if entities:+ yield entities+ if not has_next_page:+ # A later full refresh must restart at page one, not the last checkpoint from this run.+ resumable_source_manager.clear_state()+ return+ page_number += 1+++def genesys_cloud_source(+ region: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[GenesysCloudResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = GENESYS_CLOUD_ENDPOINTS[endpoint]+ base_url = _api_base_url(region)++ def items() -> Iterator[list[dict[str, Any]]]:+ session = _make_session(region, client_id, client_secret)+ if config.kind == "analytics":+ yield from _iter_analytics_rows(+ session, base_url, config, resumable_source_manager, db_incremental_field_last_value+ )+ else:+ yield from _iter_listing_rows(session, base_url, config, resumable_source_manager)++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=list(config.primary_keys),+ partition_mode="datetime" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ sort_mode="asc",+ )+++def validate_credentials(+ region: str, client_id: str, client_secret: str, endpoint: Optional[str] = None+) -> tuple[bool, str | None]:+ if region not in REGIONS:+ return False, "Select the Genesys Cloud region your organization is hosted in."++ config = GENESYS_CLOUD_ENDPOINTS[endpoint] if endpoint else None+ base_url = _api_base_url(region)+ session = _make_session(region, client_id, client_secret)+ try:+ if config is None:+ response = session.get(f"{base_url}/api/v2/organizations/me", timeout=VALIDATION_TIMEOUT_SECONDS)+ elif config.kind == "analytics":+ now = datetime.now(UTC)+ response = session.post(+ f"{base_url}{CONVERSATION_DETAILS_PATH}",+ json={"interval": _interval(now - timedelta(hours=1), now), "paging": {"pageSize": 1, "pageNumber": 1}},+ timeout=VALIDATION_TIMEOUT_SECONDS,+ )+ else:+ response = session.get(+ f"{base_url}{config.path}",+ params={"pageSize": 1, "pageNumber": 1},+ timeout=VALIDATION_TIMEOUT_SECONDS,+ )+ except OAuth2AuthRequestError as e:+ if e.is_permanent:+ return (+ False,+ "Genesys Cloud rejected the client ID and secret. Check that the OAuth client uses the client credentials grant and belongs to the selected region.",+ )+ return False, "Could not get an access token from Genesys Cloud. Try again in a few minutes."+ except requests.RequestException:+ return False, "Could not connect to Genesys Cloud. Check the selected region and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Genesys Cloud rejected the access token. Check the client ID, client secret, and region."+ if response.status_code == 403:+ # The token is valid. A missing permission only matters for the table the user asked about.+ if config is None:+ return True, None+ if config.permission:+ return (+ False,+ f"The OAuth client's role is missing the `{config.permission}` permission, which the {config.name} table needs.",+ )+ return False, f"The OAuth client does not have access to the {config.name} table."+ return False, f"Genesys Cloud returned HTTP {response.status_code}. Try again in a few minutes."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.pynew file mode 100644index 000000000000..db4f654c1e7b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py@@ -0,0 +1,127 @@+from dataclasses import dataclass, field+from typing import Any, Literal++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Genesys Cloud hosts each org in one region. The region domain builds both the API host+# (api.{domain}) and the login host (login.{domain}), so only these exact values are accepted.+# https://developer.genesys.cloud/platform/api/+REGIONS: dict[str, str] = {+ "mypurecloud.com": "Americas (US East)",+ "use2.us-gov-pure.cloud": "Americas (US East 2, FedRAMP)",+ "usw2.pure.cloud": "Americas (US West)",+ "cac1.pure.cloud": "Americas (Canada)",+ "sae1.pure.cloud": "Americas (São Paulo)",+ "mypurecloud.ie": "EMEA (Dublin)",+ "euw2.pure.cloud": "EMEA (London)",+ "mypurecloud.de": "EMEA (Frankfurt)",+ "euc2.pure.cloud": "EMEA (Zurich)",+ "mec1.pure.cloud": "EMEA (UAE)",+ "aps1.pure.cloud": "Asia Pacific (Mumbai)",+ "apne2.pure.cloud": "Asia Pacific (Seoul)",+ "apne3.pure.cloud": "Asia Pacific (Osaka)",+ "mypurecloud.jp": "Asia Pacific (Tokyo)",+ "mypurecloud.com.au": "Asia Pacific (Sydney)",+}+DEFAULT_REGION = "mypurecloud.com"++CONVERSATION_DETAILS_PATH = "/api/v2/analytics/conversations/details/query"++# The details query caps pageSize at 100.+ANALYTICS_PAGE_SIZE = 100+LISTING_PAGE_SIZE = 100++_CONVERSATION_START_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "conversationStart",+ "type": IncrementalFieldType.DateTime,+ "field": "conversationStart",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass(frozen=True)+class GenesysCloudEndpointConfig:+ name: str+ primary_keys: list[str]+ # "analytics" endpoints read the conversation details query in time windows;+ # "listing" endpoints page through a plain GET entity listing.+ kind: Literal["analytics", "listing"]+ path: str+ # Permission a Genesys Cloud role must grant for the OAuth client to read this endpoint.+ permission: str | None = None+ params: dict[str, Any] = field(default_factory=dict)+ # Extra body keys for the conversation details query (filters).+ query_body: dict[str, Any] = field(default_factory=dict)+ # Emit one row per participant instead of one row per conversation.+ flatten_participants: bool = False+ partition_key: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++_VOICE_SEGMENT_FILTER: dict[str, Any] = {+ "segmentFilters": [+ {+ "type": "or",+ "predicates": [+ {"type": "dimension", "dimension": "mediaType", "operator": "matches", "value": "voice"},+ ],+ }+ ]+}++GENESYS_CLOUD_ENDPOINTS: dict[str, GenesysCloudEndpointConfig] = {+ "conversations": GenesysCloudEndpointConfig(+ name="conversations",+ primary_keys=["conversationId"],+ kind="analytics",+ path=CONVERSATION_DETAILS_PATH,+ permission="analytics:conversationDetail:view",+ partition_key="conversationStart",+ incremental_fields=list(_CONVERSATION_START_INCREMENTAL_FIELDS),+ ),+ # Voice conversations only. Same shape as `conversations`.+ "calls": GenesysCloudEndpointConfig(+ name="calls",+ primary_keys=["conversationId"],+ kind="analytics",+ path=CONVERSATION_DETAILS_PATH,+ permission="analytics:conversationDetail:view",+ query_body=_VOICE_SEGMENT_FILTER,+ partition_key="conversationStart",+ incremental_fields=list(_CONVERSATION_START_INCREMENTAL_FIELDS),+ ),+ "participants": GenesysCloudEndpointConfig(+ name="participants",+ primary_keys=["conversationId", "participantId"],+ kind="analytics",+ path=CONVERSATION_DETAILS_PATH,+ permission="analytics:conversationDetail:view",+ flatten_participants=True,+ partition_key="conversationStart",+ incremental_fields=list(_CONVERSATION_START_INCREMENTAL_FIELDS),+ ),+ # `state=any` keeps inactive and deleted users, so historical conversations still join to a user.+ "users": GenesysCloudEndpointConfig(+ name="users",+ primary_keys=["id"],+ kind="listing",+ path="/api/v2/users",+ params={"state": "any", "sortOrder": "ascending"},+ ),+ "queues": GenesysCloudEndpointConfig(+ name="queues",+ primary_keys=["id"],+ kind="listing",+ path="/api/v2/routing/queues",+ permission="routing:queue:view",+ params={"sortOrder": "asc"},+ ),+}++ENDPOINTS = tuple(GENESYS_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GENESYS_CLOUD_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.pyindex c39f93117a2a..c6956e63b705 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py@@ -1,27 +1,166 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,+)+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.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+)+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.genesyscloud import (GenesysCloudSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.genesys_cloud import (+ GenesysCloudResumeConfig,+ genesys_cloud_source,+ validate_credentials as validate_genesys_cloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.settings import (+ DEFAULT_REGION,+ ENDPOINTS,+ GENESYS_CLOUD_ENDPOINTS,+ INCREMENTAL_FIELDS,+ REGIONS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GenesysCloudSource(SimpleSource[GenesysCloudSourceConfig]):+class GenesysCloudSource(ResumableSource[GenesysCloudSourceConfig, GenesysCloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://developer.genesys.cloud/platform/api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GENESYSCLOUD+ @property+ def connection_host_fields(self) -> list[str]:+ # The client secret is sent to login.{region} and the token to api.{region}.+ return ["region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ OAUTH2_PERMANENT_ERROR_MARKER: "Genesys Cloud rejected the client ID and secret. Check that the OAuth client uses the client credentials grant and belongs to the selected region, then reconnect.",+ "401 Client Error: Unauthorized for url": "Genesys Cloud rejected the access token. Check the client ID, client secret, and region, then reconnect.",+ "403 Client Error: Forbidden for url": "The Genesys Cloud OAuth client's role is missing a permission this table needs. Add the permission to the role, or deselect the table.",+ "Unknown Genesys Cloud region": "Select the Genesys Cloud region your organization is hosted in, then reconnect.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.GENESYSCLOUD,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,- label="Genesys Cloud (Genesys Telecommunications Laboratories)",+ keywords=["genesys", "purecloud", "contact center"],+ label="Genesys Cloud",+ caption="""Connect your Genesys Cloud organization to import calls, conversations, participants, users, and queues.++In Genesys Cloud, go to **Admin > Integrations > OAuth** and add a client with the **Client Credentials** grant type. Assign it a role with these permissions:++- `analytics:conversationDetail:view` for calls, conversations, and participants+- `routing:queue:view` for queues++Then select the region your organization is hosted in.""",iconPath="/static/services/genesys_cloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/genesys-cloud",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue=DEFAULT_REGION,+ options=[+ SourceFieldSelectConfigOption(label=f"{label} ({domain})", value=domain)+ for domain, label in REGIONS.items()+ ],+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: GenesysCloudSourceConfig,+ 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: GenesysCloudSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in GENESYS_CLOUD_ENDPOINTS:+ return False, f"Genesys Cloud has no table named {schema_name}."+ return validate_genesys_cloud_credentials(config.region, config.client_id, config.client_secret, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GenesysCloudResumeConfig]:+ return ResumableSourceManager[GenesysCloudResumeConfig](inputs, GenesysCloudResumeConfig)++ def source_for_pipeline(+ self,+ config: GenesysCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[GenesysCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return genesys_cloud_source(+ region=config.region,+ client_id=config.client_id,+ client_secret=config.client_secret,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ 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/genesys_cloud/tests/test_genesys_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.pynew file mode 100644index 000000000000..94a2ef7c64e2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.py@@ -0,0 +1,274 @@+from collections.abc import Iterable+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+import time_machine+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAuth2AuthRequestError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud import genesys_cloud+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.genesys_cloud import (+ GenesysCloudResumeConfig,+ genesys_cloud_source,+ validate_credentials,+)++SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.genesys_cloud.make_tracked_session"+)+NOW = datetime(2026, 3, 10, 12, 0, tzinfo=UTC)+++def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.json.return_value = payload+ return response+++def _conversation(conversation_id: str, start: datetime, participants: list[dict[str, Any]] | None = None) -> dict:+ return {+ "conversationId": conversation_id,+ "conversationStart": start.strftime("%Y-%m-%dT%H:%M:%S.000Z"),+ "participants": participants or [],+ }+++def _manager(resume: GenesysCloudResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _request_interval(call: Any) -> tuple[datetime, datetime]:+ start, end = call.kwargs["json"]["interval"].split("/")+ return datetime.fromisoformat(start), datetime.fromisoformat(end)+++def _run(endpoint: str, session: mock.MagicMock, manager: mock.MagicMock, watermark: Any = None) -> list[dict]:+ with mock.patch(SESSION_PATCH, return_value=session):+ response = genesys_cloud_source(+ region="mypurecloud.com",+ client_id="cid",+ client_secret="secret",+ endpoint=endpoint,+ resumable_source_manager=manager,+ db_incremental_field_last_value=watermark,+ )+ items = response.items()+ assert isinstance(items, Iterable)+ return [row for batch in items for row in batch]+++class TestAnalyticsEndpoints:+ @pytest.fixture(autouse=True)+ def frozen_clock(self):+ with time_machine.travel(NOW, tick=False):+ yield++ def test_pages_within_window_and_drops_conversations_outside_it(self):+ start = NOW - timedelta(hours=6)+ full_page = [_conversation(f"c{i}", start + timedelta(seconds=i)) for i in range(100)]+ last_page = [+ _conversation("c100", start + timedelta(minutes=5)),+ _conversation("from-previous-window", start - timedelta(hours=1)),+ ]+ session = mock.MagicMock()+ session.post.side_effect = [+ _response({"totalHits": 102, "conversations": full_page}),+ _response({"totalHits": 102, "conversations": last_page}),+ ]+ manager = _manager(GenesysCloudResumeConfig(window_start=start.isoformat()))++ rows = _run("conversations", session, manager)++ assert [row["conversationId"] for row in rows] == [f"c{i}" for i in range(101)]+ assert [c.kwargs["json"]["paging"]["pageNumber"] for c in session.post.call_args_list] == [1, 2]+ assert _request_interval(session.post.call_args_list[0]) == (start, NOW)+ manager.save_state.assert_called_once_with(GenesysCloudResumeConfig(window_start="2026-03-10T12:00:00.000Z"))++ def test_splits_window_with_too_many_hits(self):+ start = NOW - timedelta(hours=4)+ middle = NOW - timedelta(hours=2)+ session = mock.MagicMock()+ session.post.side_effect = [+ _response({"totalHits": genesys_cloud.MAX_RESULTS_PER_WINDOW + 1, "conversations": []}),+ _response({"totalHits": 1, "conversations": [_conversation("early", start)]}),+ _response({"totalHits": 1, "conversations": [_conversation("late", middle)]}),+ ]+ manager = _manager(GenesysCloudResumeConfig(window_start=start.isoformat()))++ rows = _run("conversations", session, manager)++ assert [row["conversationId"] for row in rows] == ["early", "late"]+ assert [_request_interval(c) for c in session.post.call_args_list[1:]] == [(start, middle), (middle, NOW)]+ assert [c.args[0].window_start for c in manager.save_state.call_args_list] == [+ "2026-03-10T10:00:00.000Z",+ "2026-03-10T12:00:00.000Z",+ ]+ manager.clear_state.assert_called_once_with()++ def test_splits_a_dense_ten_minute_window(self):+ start = NOW - timedelta(minutes=10)+ middle = NOW - timedelta(minutes=5)+ session = mock.MagicMock()+ session.post.side_effect = [+ _response({"totalHits": genesys_cloud.MAX_RESULTS_PER_WINDOW + 1, "conversations": []}),+ _response({"totalHits": 1, "conversations": [_conversation("early", start)]}),+ _response({"totalHits": 1, "conversations": [_conversation("late", middle)]}),+ ]+ manager = _manager(GenesysCloudResumeConfig(window_start=start.isoformat()))++ rows = _run("conversations", session, manager)++ assert [row["conversationId"] for row in rows] == ["early", "late"]+ assert [_request_interval(c) for c in session.post.call_args_list[1:]] == [(start, middle), (middle, NOW)]++ @pytest.mark.parametrize(+ "resume,watermark,expected_start",+ [+ (None, None, NOW - genesys_cloud.INITIAL_HISTORY),+ (None, datetime(2026, 3, 9, 6, 0), datetime(2026, 3, 7, 6, 0, tzinfo=UTC)),+ (+ GenesysCloudResumeConfig(window_start="2026-03-10T08:00:00.000Z"),+ datetime(2026, 3, 9, 6, 0),+ datetime(2026, 3, 10, 8, 0, tzinfo=UTC),+ ),+ ],+ )+ def test_first_window_start(self, resume, watermark, expected_start):+ session = mock.MagicMock()+ session.post.return_value = _response({"totalHits": 0})+ manager = _manager(resume)++ _run("calls", session, manager, watermark=watermark)++ assert _request_interval(session.post.call_args_list[0])[0] == expected_start+ assert _request_interval(session.post.call_args_list[-1])[1] == NOW+ manager.safe_point.assert_called()++ def test_participants_are_flattened_with_conversation_keys(self):+ start = NOW - timedelta(hours=1)+ session = mock.MagicMock()+ session.post.return_value = _response(+ {+ "totalHits": 1,+ "conversations": [+ _conversation(+ "conv-1",+ start,+ participants=[+ {"participantId": "p1", "purpose": "customer"},+ {"participantId": "p2", "purpose": "agent"},+ ],+ )+ ],+ }+ )++ rows = _run("participants", session, _manager(GenesysCloudResumeConfig(window_start=start.isoformat())))++ assert [(row["conversationId"], row["participantId"], row["purpose"]) for row in rows] == [+ ("conv-1", "p1", "customer"),+ ("conv-1", "p2", "agent"),+ ]+ assert all(row["conversationStart"] == "2026-03-10T11:00:00.000Z" for row in rows)+++class TestListingEndpoints:+ @pytest.mark.parametrize(+ "resume,expected_pages",+ [+ (None, [1, 2]),+ (GenesysCloudResumeConfig(page_number=2), [2]),+ ],+ )+ def test_pages_until_page_count(self, resume, expected_pages):+ pages = {+ 1: _response({"entities": [{"id": "q1"}], "pageNumber": 1, "pageCount": 2}),+ 2: _response({"entities": [{"id": "q2"}], "pageNumber": 2, "pageCount": 2}),+ }+ session = mock.MagicMock()+ session.get.side_effect = lambda url, params, timeout: pages[params["pageNumber"]]+ manager = _manager(resume)++ rows = _run("queues", session, manager)++ requested = [c.kwargs["params"]["pageNumber"] for c in session.get.call_args_list]+ assert requested == expected_pages+ assert [row["id"] for row in rows] == [f"q{page}" for page in expected_pages]+ saved = [c.args[0].page_number for c in manager.save_state.call_args_list]+ assert saved == ([2] if resume is None else [])+ manager.clear_state.assert_called_once_with()+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "endpoint,status_code,expected_valid,expected_message",+ [+ (None, 200, True, None),+ (None, 403, True, None),+ (+ None,+ 401,+ False,+ "Genesys Cloud rejected the access token. Check the client ID, client secret, and region.",+ ),+ (+ "conversations",+ 403,+ False,+ "The OAuth client's role is missing the `analytics:conversationDetail:view` permission, which the conversations table needs.",+ ),+ ("users", 403, False, "The OAuth client does not have access to the users table."),+ ("queues", 500, False, "Genesys Cloud returned HTTP 500. Try again in a few minutes."),+ ],+ )+ def test_maps_probe_status(self, endpoint, status_code, expected_valid, expected_message):+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code)+ session.post.return_value = _response({}, status_code)++ with mock.patch(SESSION_PATCH, return_value=session):+ result = validate_credentials("mypurecloud.com", "cid", "secret", endpoint)++ assert result == (expected_valid, expected_message)++ @pytest.mark.parametrize(+ "error,expected_message",+ [+ (+ OAuth2AuthRequestError("HTTP 400 from the OAuth2 token endpoint: invalid_client", is_permanent=True),+ "Genesys Cloud rejected the client ID and secret. Check that the OAuth client uses the client credentials grant and belongs to the selected region.",+ ),+ (+ OAuth2AuthRequestError("HTTP 503 from the OAuth2 token endpoint", is_permanent=False),+ "Could not get an access token from Genesys Cloud. Try again in a few minutes.",+ ),+ (+ requests.ConnectionError("Name or service not known"),+ "Could not connect to Genesys Cloud. Check the selected region and try again.",+ ),+ ],+ )+ def test_maps_request_errors(self, error, expected_message):+ session = mock.MagicMock()+ session.get.side_effect = error++ with mock.patch(SESSION_PATCH, return_value=session):+ result = validate_credentials("mypurecloud.com", "cid", "secret")++ assert result == (False, expected_message)++ def test_rejects_unknown_region_without_a_request(self):+ with mock.patch(SESSION_PATCH) as make_session:+ result = validate_credentials("evil.example.com", "cid", "secret")++ assert result == (False, "Select the Genesys Cloud region your organization is hosted in.")+ make_session.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud_source.pynew file mode 100644index 000000000000..50d5f4c07f07--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud_source.py@@ -0,0 +1,61 @@+import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAuth2AuthRequestError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.genesyscloud import (+ GenesysCloudSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.genesys_cloud import (+ InvalidGenesysCloudRegionError,+ genesys_cloud_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.source import GenesysCloudSource+++class TestGenesysCloudSource:+ def setup_method(self):+ self.source = GenesysCloudSource()++ @pytest.mark.parametrize(+ "observed_error",+ [+ str(OAuth2AuthRequestError("HTTP 401 from the OAuth2 token endpoint: invalid_client", is_permanent=True)),+ "403 Client Error: Forbidden for url: https://api.mypurecloud.com/api/v2/analytics/conversations/details/query",+ str(InvalidGenesysCloudRegionError("Unknown Genesys Cloud region: 'evil.example.com'")),+ ],+ )+ def test_permanent_failures_are_non_retryable(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ str(OAuth2AuthRequestError("HTTP 503 from the OAuth2 token endpoint", is_permanent=False)),+ "429 Client Error: Too Many Requests for url: https://api.mypurecloud.com/api/v2/routing/queues",+ ],+ )+ def test_transient_failures_are_retryable(self, observed_error):+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_validate_credentials_rejects_unknown_table(self):+ config = GenesysCloudSourceConfig(region="mypurecloud.com", client_id="cid", client_secret="secret")++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.source.validate_genesys_cloud_credentials"+ ) as validate:+ result = self.source.validate_credentials(config, team_id=1, schema_name="recordings")++ assert result == (False, "Genesys Cloud has no table named recordings.")+ validate.assert_not_called()++ def test_unknown_region_fails_before_any_request(self):+ with pytest.raises(InvalidGenesysCloudRegionError):+ genesys_cloud_source(+ region="evil.example.com",+ client_id="cid",+ client_secret="secret",+ endpoint="conversations",+ resumable_source_manager=mock.MagicMock(),+ )