: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 Pluralsight Flow import source (#84434)
Tom Owers16fb49591c70
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/pluralsightflow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/pluralsightflow.pyindex 8e9e6cfd44af..6ed56eccae4f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/pluralsightflow.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/pluralsightflow.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PluralsightFlowSourceConfig(config.Config):- pass+ workspace: str+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/canonical_descriptions.pynew file mode 100644index 000000000000..93d7302122c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/canonical_descriptions.py@@ -0,0 +1,129 @@+"""Canonical, documentation-sourced descriptions for Pluralsight Flow endpoints and columns.++Sourced from the official Flow Customer API and Metrics API reference+(https://appfire.atlassian.net/wiki/spaces/FD/pages/1802076213/Flow+REST+API+introduction).+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Flow table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Users": {+ "description": "A person tracked by Flow, aggregated from one or more git/ticket-host identities.",+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802404091",+ "columns": {+ "id": "User's unique identifier.",+ "name": "User's display name.",+ "email": "User's email address.",+ "hidden_from_reports": "Whether the user is excluded from Flow reports.",+ "org_id": "Identifier of the organization the user belongs to.",+ "has_login": "Whether the user has a Flow login (as opposed to a data-only identity).",+ "created_at": "Time the user record was created in Flow.",+ "last_activity_at": "Time of the user's most recent tracked activity.",+ "first_activity_at": "Time of the user's earliest tracked activity.",+ },+ },+ "Teams": {+ "description": "A group of Flow users, optionally nested under a parent team.",+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802011038",+ "columns": {+ "id": "Team's unique identifier.",+ "name": "Team name.",+ "description": "Team description.",+ "vendor": "Name of the vendor/integration the team originates from, if any.",+ "parent": "Identifier of the parent team, if this team is nested.",+ "is_visible": "Whether the team is shown in report menus.",+ "created_at": "Time the team was created.",+ },+ },+ "Commits": {+ "description": (+ "A raw git commit synced from an integrated repository. Does not exactly match the "+ "aggregated and filtered commit data shown in Flow reports."+ ),+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802568104",+ "columns": {+ "id": "Commit's unique identifier.",+ "hexsha": "Unique commit hash (SHA).",+ "user_alias_id": "Identifier of the git identity that authored the commit.",+ "apex_user_id": "Identifier of the Flow user the commit is attributed to.",+ "repo_id": "Identifier of the repository the commit belongs to.",+ "is_merge": "Whether the commit is a merge commit.",+ "is_pr_orphan": "Whether the commit isn't associated with any pull request.",+ "is_outlier": "Whether Flow flags the commit as a statistical outlier.",+ "author_date": "Date and time the commit was authored (recommended for time filtering).",+ "committer_date": "Date and time the commit was committed.",+ },+ },+ "PullRequests": {+ "description": "An author's request to merge a set of commits into a repository branch.",+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802011014",+ "columns": {+ "id": "Pull request's unique identifier.",+ "title": "Pull request title.",+ "number": "Pull request number in its repository.",+ "state": "Current state of the pull request.",+ "vendor": "Name of the git host the pull request originates from.",+ "url": "URL of the pull request.",+ "project_id": "Identifier of the associated repository/project.",+ "created_at": "Time the pull request was created.",+ "closed_at": "Time the pull request was closed.",+ "pr_start": "Time the pull request was opened.",+ "pr_end": "Time the pull request was merged or closed.",+ "first_comment_at": "Time of the first comment on the pull request.",+ "comment_count": "Number of comments on the pull request.",+ "reviewer_count": "Number of reviewers on the pull request.",+ "additions": "Number of lines added.",+ "deletions": "Number of lines deleted.",+ },+ },+ "Repos": {+ "description": "A git repository imported into Flow from an integrated vendor.",+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802600473",+ "columns": {+ "id": "Repository's unique identifier.",+ "name": "Repository name.",+ "vendor": "Name of the git host the repository is imported from (e.g. github).",+ },+ },+ "Tickets": {+ "description": "An issue filed in an integrated issue-tracking application.",+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1801912714",+ "columns": {+ "id": "Ticket's unique identifier.",+ "title": "Ticket title.",+ "number": "Ticket number in its issue tracker.",+ "state": "Current state of the ticket (e.g. Defined, InProgress, Completed).",+ "vendor": "Name of the issue-tracking application the ticket originates from.",+ "url": "URL of the ticket.",+ "closed_at": "Time the ticket was closed.",+ "created_at": "Time the ticket was created.",+ "updated_at": "Time the ticket was last modified.",+ "type": "Ticket type.",+ "comment_count": "Number of comments on the ticket.",+ },+ },+ "CodingMetrics": {+ "description": (+ "Aggregate coding activity metrics (coding days, commits per day, impact, efficiency) "+ "for the requested date range. One row per sync, covering the trailing window."+ ),+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/2208239236",+ "columns": {+ "date_range": "The `[start:end]` date window the metrics were computed over.",+ },+ },+ "CollaborationMetrics": {+ "description": (+ "Aggregate pull request collaboration metrics (time to merge, time to first comment, "+ "review thoroughness, PR count) for the requested date range. One row per sync."+ ),+ "docs_url": "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802076189",+ "columns": {+ "date_range": "The `[start:end]` date window the metrics were computed over.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/pluralsight_flow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/pluralsight_flow.pynew file mode 100644index 000000000000..b6969e2ce345--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/pluralsight_flow.py@@ -0,0 +1,216 @@+import re+from collections.abc import Callable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.settings import (+ CORE_ENDPOINT_PATHS,+ DEFAULT_METRICS_LOOKBACK_DAYS,+ INCREMENTAL_FIELDS,+ MAX_PAGE_SIZE,+ METRIC_ENDPOINT_PATHS,+ METRIC_ENDPOINTS,+ PARTITION_KEYS,+ PRIMARY_KEYS,+ TABLE_NAMES,+)++# Shared host for the Metrics API (Coding metrics, Collaboration/PR metrics) — unlike the Customer+# API, it is not workspace-specific. Flow moved this off `flow-api.pluralsight.com` to+# `api.appfireflow.com` on 2025-07-23; the old host is no longer guaranteed to work.+METRICS_BASE_URL = "https://api.appfireflow.com"++# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host+# (slashes, `@`, dots), so the stored API key is only ever sent to `<workspace>.appfireflow.com`.+_WORKSPACE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]*$")+++@frozen+class PluralsightFlowResumeConfig:+ offset: int+++def normalize_workspace(workspace: str) -> str:+ """Reduce user input to a bare, validated Flow workspace label.++ Accepts either the full host (``acme.appfireflow.com``) or the bare workspace (``acme``).+ Raises ``ValueError`` on anything that isn't a single DNS label, so the API key can never be+ sent to a host the user doesn't control.+ """+ cleaned = workspace.strip().removeprefix("https://").removeprefix("http://")+ cleaned = cleaned.strip("/")+ cleaned = cleaned.removesuffix(".appfireflow.com")+ if not _WORKSPACE_RE.match(cleaned):+ raise ValueError(+ f"Invalid Flow workspace: {workspace!r}. Enter just the workspace, e.g. 'acme' for acme.appfireflow.com."+ )+ return cleaned+++def _core_base_url(workspace: str) -> str:+ return f"https://{normalize_workspace(workspace)}.appfireflow.com/v3/customer/core"+++def _format_incremental_value(value: Any) -> str:+ """Format a date/datetime-like value as the naive ISO datetime Flow's `__gte`/`__lt`+ filters document (e.g. `2018-06-25T00:00:00`). Falls back to `str(value)` for values that+ are already a formatted string (e.g. our own `initial_value` seed)."""+ normalized = coerce_datetime_to_utc(value)+ if normalized is None:+ return str(value)+ return normalized.strftime("%Y-%m-%dT%H:%M:%S")+++def _core_client_config(workspace: str, api_key: str) -> ClientConfig:+ return {+ "base_url": _core_base_url(workspace),+ "auth": {"type": "bearer", "token": api_key},+ # Flow returns a page shorter than `limit` once exhausted; `total_path` gives an extra,+ # cheaper stop signal from the response envelope's documented `count` field.+ "paginator": OffsetPaginator(limit=MAX_PAGE_SIZE, total_path="count", stop_after_empty_page=True),+ }+++def _core_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ incremental_fields = INCREMENTAL_FIELDS.get(name)+ params: dict[str, Any] = {}+ is_incremental = bool(incremental_fields) and should_use_incremental_field+ if incremental_fields and is_incremental:+ field = incremental_fields[0]["field"]+ params[f"{field}__gte"] = {+ "type": "incremental",+ "cursor_path": field,+ "initial_value": "1970-01-01T00:00:00",+ "convert": _format_incremental_value,+ }++ return {+ "name": name,+ "table_name": TABLE_NAMES[name],+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",+ "endpoint": {+ "path": CORE_ENDPOINT_PATHS[name],+ "params": params,+ # Flow's Customer API wraps list responses as `{count, next, previous, results}`.+ "data_selector": "results",+ },+ "table_format": "delta",+ }+++def _default_metrics_date_range(today: Optional[date] = None) -> str:+ end = today or datetime.now(UTC).date()+ start = end - timedelta(days=DEFAULT_METRICS_LOOKBACK_DAYS)+ return f"[{start.isoformat()}:{end.isoformat()}]"+++def _stamp_date_range(date_range: str) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def _map(row: dict[str, Any]) -> dict[str, Any]:+ return {**row, "date_range": date_range}++ return _map+++def _metrics_resource(name: str, date_range: str) -> EndpointResource:+ return {+ "name": name,+ "table_name": TABLE_NAMES[name],+ "write_disposition": "replace",+ "endpoint": {+ "path": METRIC_ENDPOINT_PATHS[name],+ "params": {"date_range": date_range},+ # The metrics endpoints return one aggregate JSON object, not a list.+ "data_selector": "$",+ "paginator": SinglePagePaginator(),+ },+ "data_map": _stamp_date_range(date_range),+ }+++def pluralsight_flow_source(+ api_key: str,+ workspace: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[PluralsightFlowResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ if endpoint in METRIC_ENDPOINTS:+ metrics_config: RESTAPIConfig = {+ "client": {"base_url": METRICS_BASE_URL, "auth": {"type": "bearer", "token": api_key}},+ "resource_defaults": {},+ "resources": [_metrics_resource(endpoint, _default_metrics_date_range())],+ }+ resource = rest_api_resource(metrics_config, team_id, job_id, None)+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[endpoint],+ column_hints=resource.column_hints,+ )++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"offset": resume_config.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and "offset" in state:+ resumable_source_manager.save_state(PluralsightFlowResumeConfig(offset=int(state["offset"])))++ core_config: RESTAPIConfig = {+ "client": _core_client_config(workspace, api_key),+ "resource_defaults": {},+ "resources": [_core_resource(endpoint, should_use_incremental_field)],+ }++ resource = rest_api_resource(+ core_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ partition_field = PARTITION_KEYS.get(endpoint)+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[endpoint],+ column_hints=resource.column_hints,+ partition_mode="datetime" if partition_field else None,+ partition_keys=[partition_field] if partition_field else None,+ )+++def validate_credentials(api_key: str, workspace: str) -> tuple[bool, int | None]:+ url = f"{_core_base_url(workspace)}/users/?limit=1"+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ url,+ headers={"Authorization": f"Bearer {api_key}"},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/settings.pynew file mode 100644index 000000000000..068940a544b5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/settings.py@@ -0,0 +1,91 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Raw-data resources under the per-workspace Customer API (`https://<workspace>.appfireflow.com/v3/customer/core/`).+CORE_ENDPOINTS = (+ "Users",+ "Teams",+ "Commits",+ "PullRequests",+ "Repos",+ "Tickets",+)++# Aggregate report resources under the shared Metrics API (`https://api.appfireflow.com/collaboration/`).+# Unlike the core endpoints, these return one summary object for a requested date range rather than+# a paginated list of records.+METRIC_ENDPOINTS = (+ "CodingMetrics",+ "CollaborationMetrics",+)++ENDPOINTS = CORE_ENDPOINTS + METRIC_ENDPOINTS++# Path of each core endpoint under `/v3/customer/core/`.+CORE_ENDPOINT_PATHS: dict[str, str] = {+ "Users": "users/",+ "Teams": "teams/",+ "Commits": "commits/",+ "PullRequests": "pull_requests/",+ "Repos": "repos/",+ "Tickets": "tickets/",+}++# Path of each metrics endpoint under the shared collaboration host.+METRIC_ENDPOINT_PATHS: dict[str, str] = {+ "CodingMetrics": "/collaboration/code/metrics/",+ "CollaborationMetrics": "/collaboration/pullrequest/metrics/",+}++# Every Customer API object exposes `id` as its primary key (confirmed for Users, Commits,+# Pull requests, Teams, and Tickets in the API reference; Repos follows the same convention).+CORE_PRIMARY_KEYS: dict[str, list[str]] = {name: ["id"] for name in CORE_ENDPOINTS}++# The metrics endpoints return one row per requested window, so the window we asked for is the+# natural (and only) unique key for a synced row.+METRIC_PRIMARY_KEYS: dict[str, list[str]] = {name: ["date_range"] for name in METRIC_ENDPOINTS}++PRIMARY_KEYS: dict[str, list[str]] = {**CORE_PRIMARY_KEYS, **METRIC_PRIMARY_KEYS}++TABLE_NAMES: dict[str, str] = {+ "Users": "users",+ "Teams": "teams",+ "Commits": "commits",+ "PullRequests": "pull_requests",+ "Repos": "repos",+ "Tickets": "tickets",+ "CodingMetrics": "coding_metrics",+ "CollaborationMetrics": "collaboration_metrics",+}++# Stable datetime field to partition on, for endpoints where one is confirmed by the API docs.+# Repos has no documented date field, and the metrics endpoints return one aggregate row per+# sync, so neither partitions.+PARTITION_KEYS: dict[str, str] = {+ "Users": "created_at",+ "Teams": "created_at",+ "Commits": "author_date",+ "PullRequests": "created_at",+ "Tickets": "created_at",+}++# Only endpoints with a documented `<field>__gte`/`<field>__lt`-filterable timestamp get an entry.+# Repos and the metrics endpoints are full refresh: Repos has no documented date field to filter on,+# and the metrics endpoints already require an explicit date-range window on every call.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "Users": [incremental_field("last_activity_at", IncrementalFieldType.DateTime)],+ "Teams": [incremental_field("created_at", IncrementalFieldType.DateTime)],+ # Flow's docs recommend filtering commits by author_date rather than committer_date.+ "Commits": [incremental_field("author_date", IncrementalFieldType.DateTime)],+ # Pull requests have no generic `updated_at`; a PR whose state changes after it first+ # matches the incremental window (e.g. merged much later) won't be re-fetched.+ "PullRequests": [incremental_field("created_at", IncrementalFieldType.DateTime)],+ "Tickets": [incremental_field("updated_at", IncrementalFieldType.DateTime)],+}++# Maximum page size documented for the Customer API's `limit` parameter.+MAX_PAGE_SIZE = 1000++# Coding metrics trend fields only populate once the requested window spans 4+ full+# Mon-Sun weeks, so each full-refresh sync requests a trailing 90-day window by default.+DEFAULT_METRICS_LOOKBACK_DAYS = 90diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/source.pyindex 9a638b66f24c..e0829589d561 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/source.py@@ -1,32 +1,158 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pluralsightflow import (PluralsightFlowSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.pluralsight_flow import (+ PluralsightFlowResumeConfig,+ pluralsight_flow_source,+ validate_credentials as validate_pluralsight_flow_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PluralsightFlowSource(SimpleSource[PluralsightFlowSourceConfig]):+class PluralsightFlowSource(ResumableSource[PluralsightFlowSourceConfig, PluralsightFlowResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://appfire.atlassian.net/wiki/spaces/FD/pages/1802076213/Flow+REST+API+introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PLURALSIGHTFLOW+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent to `<workspace>.appfireflow.com`, so retargeting the+ # workspace must force the editor to re-enter it.+ return ["workspace"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Flow API key is invalid or expired. Generate a new key and reconnect.",+ "403 Client Error": (+ "Flow rejected this request. Coding metrics and Collaboration metrics need the "+ "Metrics API permission on your API key."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: PluralsightFlowSourceConfig,+ 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: PluralsightFlowSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ is_valid, status = validate_pluralsight_flow_credentials(config.api_key, config.workspace)+ except ValueError as e:+ return False, str(e)++ if is_valid:+ return True, None+ if status == 401:+ return False, "Your Flow API key is invalid or expired."+ return False, "Invalid credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PluralsightFlowResumeConfig]:+ return ResumableSourceManager[PluralsightFlowResumeConfig](inputs, PluralsightFlowResumeConfig)++ def source_for_pipeline(+ self,+ config: PluralsightFlowSourceConfig,+ resumable_source_manager: ResumableSourceManager[PluralsightFlowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pluralsight_flow_source(+ api_key=config.api_key,+ workspace=config.workspace,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PLURALSIGHT_FLOW,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Pluralsight Flow",+ caption=(+ "Import commits, pull requests, tickets, and coding/collaboration metrics from "+ "Pluralsight Flow (formerly GitPrime). Generate an API key in Flow under "+ "Settings > API keys. Coding metrics and Collaboration metrics need the "+ "**Metrics API** permission on that key; the other tables only need the key itself."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/pluralsight-flow",iconPath="/static/services/pluralsight_flow.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["pluralsight", "flow", "gitprime", "engineering"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="workspace",+ label="Workspace",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ caption="The subdomain in your Flow URL, e.g. 'acme' for acme.appfireflow.com.",+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow.pynew file mode 100644index 000000000000..db1d0a5b6c76--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow.py@@ -0,0 +1,265 @@+import json+from collections.abc import Iterable+from datetime import date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.pluralsight_flow import (+ PluralsightFlowResumeConfig,+ _core_resource,+ _default_metrics_date_range,+ _format_incremental_value,+ _metrics_resource,+ normalize_workspace,+ pluralsight_flow_source,+ validate_credentials,+)+++class TestNormalizeWorkspace:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("acme", "acme"),+ ("acme-test", "acme-test"),+ ("acme2024", "acme2024"),+ ("acme.appfireflow.com", "acme"),+ ("https://acme.appfireflow.com", "acme"),+ ("https://acme.appfireflow.com/", "acme"),+ ],+ )+ def test_accepts_and_normalizes_valid_workspaces(self, raw, expected):+ assert normalize_workspace(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ "acme/evil.com",+ "[email protected]",+ "evil.com/acme",+ "",+ "-acme",+ ],+ )+ def test_rejects_invalid_workspaces(self, raw):+ with pytest.raises(ValueError, match="Invalid Flow workspace"):+ normalize_workspace(raw)+++class TestFormatIncrementalValue:+ def test_formats_datetime(self):+ assert _format_incremental_value(datetime(2024, 3, 5, 12, 30, 45)) == "2024-03-05T12:30:45"++ def test_formats_date(self):+ assert _format_incremental_value(date(2024, 3, 5)) == "2024-03-05T00:00:00"++ def test_passes_through_already_formatted_string(self):+ # The `initial_value` seed for a never-synced schema is already a formatted string.+ assert _format_incremental_value("1970-01-01T00:00:00") == "1970-01-01T00:00:00"+++class TestDefaultMetricsDateRange:+ def test_builds_trailing_window(self):+ assert _default_metrics_date_range(today=date(2026, 4, 30)) == "[2026-01-30:2026-04-30]"+++def _endpoint_params(resource: EndpointResource) -> dict[str, Any]:+ # `endpoint` is typed as `str | Endpoint | None` (a dlt-style shorthand union), so mypy can't+ # index into it directly even though these tests only ever build the dict form.+ endpoint = cast(dict[str, Any], resource["endpoint"])+ return cast(dict[str, Any], endpoint["params"])+++class TestCoreResource:+ def test_incremental_endpoint_sets_merge_disposition_and_filter_param(self):+ resource = _core_resource("Commits", should_use_incremental_field=True)++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ assert resource["table_name"] == "commits"+ params = _endpoint_params(resource)+ assert "author_date__gte" in params+ assert params["author_date__gte"]["type"] == "incremental"++ def test_incremental_endpoint_without_incremental_flag_is_full_refresh(self):+ resource = _core_resource("Commits", should_use_incremental_field=False)++ assert resource["write_disposition"] == "replace"+ params = _endpoint_params(resource)+ assert params == {}++ def test_endpoint_with_no_incremental_fields_ignores_the_flag(self):+ # Repos has no INCREMENTAL_FIELDS entry, so even should_use_incremental_field=True+ # must not add a filter param.+ resource = _core_resource("Repos", should_use_incremental_field=True)++ assert resource["write_disposition"] == "replace"+ params = _endpoint_params(resource)+ assert params == {}+++class TestMetricsResource:+ def test_stamps_date_range_onto_each_row(self):+ resource = _metrics_resource("CodingMetrics", "[2026-01-01:2026-04-01]")+ data_map = resource["data_map"]+ assert data_map is not None++ row = data_map({"time_to_merge": {"average": 3.2}})+ assert row == {"time_to_merge": {"average": 3.2}, "date_range": "[2026-01-01:2026-04-01]"}+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestPluralsightFlowSourceCoreEndpoints:+ """End-to-end pagination/resume behaviour of core endpoints via `rest_api_resource`."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = pluralsight_flow_source(+ api_key="test-key",+ workspace="acme",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=None,+ )+ # Iterating a Resource yields one page (list[dict]) per response, not flat rows.+ pages = list(cast(Iterable[list[dict[str, Any]]], source_response.items()))+ rows = [row for page in pages for row in page]+ return rows, sent_params++ def test_paginates_until_short_page_and_saves_resume_offset(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ # A page exactly `limit` (1000) long doesn't tell the paginator it's the last page — only+ # a page shorter than `limit` does, so the first fake page must be full-sized.+ full_page = [{"id": i} for i in range(1000)]+ responses = [+ _make_http_response({"count": 1001, "next": "...", "previous": None, "results": full_page}),+ _make_http_response({"count": 1001, "next": None, "previous": "...", "results": [{"id": 1000}]}),+ ]+ rows, sent_params = self._drive("Repos", manager, responses)++ assert rows == [*full_page, {"id": 1000}]+ # OffsetPaginator always injects `offset` (starting at 0), unlike a bespoke paginator+ # that only adds it once seeded.+ assert [p.get("offset") for p in sent_params] == [0, 1000]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [PluralsightFlowResumeConfig(offset=1000)]++ def test_resume_seeds_paginator_with_saved_offset(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = PluralsightFlowResumeConfig(offset=2000)++ responses = [_make_http_response({"count": 1, "next": None, "previous": None, "results": [{"id": 5}]})]+ rows, sent_params = self._drive("Repos", manager, responses)++ assert rows == [{"id": 5}]+ assert sent_params[0].get("offset") == 2000+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"count": 1, "next": None, "previous": None, "results": [{"id": 1}]})]+ self._drive("Repos", manager, responses)++ manager.save_state.assert_not_called()++ def test_incremental_endpoint_sends_gte_filter(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"count": 1, "next": None, "previous": None, "results": [{"id": 1}]})]+ _, sent_params = self._drive("Commits", manager, responses, should_use_incremental_field=True)++ assert sent_params[0].get("author_date__gte") == "1970-01-01T00:00:00"+++class TestPluralsightFlowSourceMetricsEndpoints:+ def test_single_object_response_yields_one_row_with_date_range(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)++ response = _make_http_response({"time_to_merge": {"average": 3.5, "trend": 0.1}})++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = lambda request, *a, **kw: response++ source_response = pluralsight_flow_source(+ api_key="test-key",+ workspace="acme",+ endpoint="CollaborationMetrics",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ pages = list(cast(Iterable[list[dict[str, Any]]], source_response.items()))+ rows = [row for page in pages for row in page]++ assert len(rows) == 1+ assert rows[0]["time_to_merge"] == {"average": 3.5, "trend": 0.1}+ assert "date_range" in rows[0]+ manager.save_state.assert_not_called()+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [(200, True), (401, False), (403, False)],+ )+ def test_maps_status_to_validity(self, status_code, expected_valid) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.pluralsight_flow"+ ".make_tracked_session"+ ) as mock_make_session:+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = _make_http_response({}, status_code=status_code)++ is_valid, status = validate_credentials("test-key", "acme")++ assert is_valid is expected_valid+ assert status == status_code++ def test_invalid_workspace_raises(self) -> None:+ with pytest.raises(ValueError, match="Invalid Flow workspace"):+ validate_credentials("test-key", "a/b")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow_source.pynew file mode 100644index 000000000000..736d6c2a9c34--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pluralsight_flow/tests/test_pluralsight_flow_source.py@@ -0,0 +1,201 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pluralsightflow import (+ PluralsightFlowSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.pluralsight_flow import (+ PluralsightFlowResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.settings import (+ CORE_ENDPOINTS,+ ENDPOINTS,+ METRIC_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.source import (+ PluralsightFlowSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPluralsightFlowSource:+ def setup_method(self):+ self.source = PluralsightFlowSource()+ self.team_id = 123+ self.config = PluralsightFlowSourceConfig(workspace="acme", api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PLURALSIGHTFLOW++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "PluralsightFlow"+ assert config.label == "Pluralsight Flow"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/pluralsight_flow.png"+ assert config.category is not None++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["workspace", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_workspace_field_is_not_secret(self):+ config = self.source.get_source_config+ workspace_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "workspace"+ )+ assert workspace_field.secret is False+ assert workspace_field.required is True++ def test_workspace_listed_as_connection_host_field(self):+ # The API key is sent to <workspace>.appfireflow.com, so retargeting the workspace must+ # re-require it.+ assert self.source.connection_host_fields == ["workspace"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://acme.appfireflow.com/v3/customer/core/users/",+ "403 Client Error: Forbidden for url: https://api.appfireflow.com/collaboration/code/metrics/",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://acme.appfireflow.com/v3/customer/core/users/",+ "500 Server Error: Internal Server Error for url: https://acme.appfireflow.com/v3/customer/core/users/",+ "HTTPSConnectionPool(host='acme.appfireflow.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_all_endpoints(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ ("name", "field"),+ [+ ("Users", "last_activity_at"),+ ("Teams", "created_at"),+ ("Commits", "author_date"),+ ("PullRequests", "created_at"),+ ("Tickets", "updated_at"),+ ],+ )+ def test_get_schemas_incremental_endpoints(self, name, field):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].supports_incremental is True+ assert [f["field"] for f in schemas[name].incremental_fields] == [field]++ @pytest.mark.parametrize("name", ["Repos", "CodingMetrics", "CollaborationMetrics"])+ def test_get_schemas_full_refresh_endpoints(self, name):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Commits"])+ assert len(schemas) == 1+ assert schemas[0].name == "Commits"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Your Flow API key is invalid or expired."),+ ((False, 403), False, "Invalid credentials"),+ ((False, None), False, "Invalid credentials"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.source"+ ".validate_pluralsight_flow_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key", "acme")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.source"+ ".validate_pluralsight_flow_credentials"+ )+ def test_validate_credentials_surfaces_bad_workspace(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid Flow workspace: 'a/b'.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid Flow workspace" in (error_message or "")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is PluralsightFlowResumeConfig++ @pytest.mark.parametrize("endpoint", list(CORE_ENDPOINTS) + list(METRIC_ENDPOINTS))+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.source.pluralsight_flow_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_pluralsight_flow_source, endpoint):+ inputs = mock.MagicMock()+ inputs.schema_name = endpoint+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_pluralsight_flow_source.assert_called_once()+ kwargs = mock_pluralsight_flow_source.call_args.kwargs+ assert kwargs["workspace"] == "acme"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == endpoint+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pluralsight_flow.source.pluralsight_flow_source"+ )+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_pluralsight_flow_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Repos"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_pluralsight_flow_source.call_args.kwargs["db_incremental_field_last_value"] is None