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): implement launchdarkly import source (#61595)

Tom Owersb4da69c293b9
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index ad1596586dbe..c98aac96aef1 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -78,6 +78,7 @@ the row lists both.
| hubspot | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| klaviyo | HTTP | requests | ✅ |
+| launchdarkly | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| lever | HTTP | requests | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
@@ -191,7 +192,6 @@ doesn't conflict with concurrent PRs.
- iterable
- jira
- kafka
-- launchdarkly
- lever
- marketo
- microsoft_teams
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index e78c32b980d8..11bf6dcf775a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -479,7 +479,7 @@ class KlaviyoSourceConfig(config.Config):
@config.config
class LaunchDarklySourceConfig(config.Config):
- pass
+ access_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/launchdarkly/launchdarkly.py b/posthog/temporal/data_imports/sources/launchdarkly/launchdarkly.py
new file mode 100644
index 000000000000..b5c2d4ae8317
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/launchdarkly/launchdarkly.py
@@ -0,0 +1,232 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.launchdarkly.settings import (
+ LAUNCHDARKLY_ENDPOINTS,
+ LaunchDarklyEndpointConfig,
+)
+
+API_HOST = "https://app.launchdarkly.com"
+BASE_URL = f"{API_HOST}/api/v2"
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+MAX_RETRY_WAIT_SECONDS = 60
+
+
+class LaunchDarklyRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None):
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class LaunchDarklyResumeConfig:
+ # Full URL of the next page to fetch ("" once a resource is exhausted).
+ next_url: str = ""
+ # For fan-out endpoints, the project currently being paginated ("" for top-level
+ # endpoints or before the first project starts).
+ project_key: str = ""
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ # LaunchDarkly expects the raw access token in the Authorization header, with no
+ # "Bearer" prefix (see https://apidocs.launchdarkly.com/#section/Overview/Authentication).
+ return {
+ "Authorization": access_token,
+ "Accept": "application/json",
+ }
+
+
+def _initial_url(path: str, page_size: int) -> str:
+ return f"{BASE_URL}{path}?{urlencode({'limit': page_size})}"
+
+
+def _resolve_url(href: str) -> str:
+ # LaunchDarkly returns relative hrefs (e.g. "/api/v2/projects?limit=20&offset=20").
+ if href.startswith("http"):
+ return href
+ return f"{API_HOST}{href}"
+
+
+def _next_url_from(data: dict[str, Any]) -> str | None:
+ links = data.get("_links") or {}
+ next_link = links.get("next") or {}
+ href = next_link.get("href")
+ return _resolve_url(href) if href else None
+
+
+def _wait_strategy(retry_state: Any) -> float:
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, LaunchDarklyRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT_SECONDS)
+ return min(2.0**retry_state.attempt_number, MAX_RETRY_WAIT_SECONDS)
+
+
+@retry(
+ retry=retry_if_exception_type((LaunchDarklyRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=_wait_strategy,
+ reraise=True,
+)
+def _fetch_page(url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict[str, Any]:
+ response = make_tracked_session().get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429:
+ retry_after_header = response.headers.get("Retry-After")
+ try:
+ # Retry-After is normally integer seconds, but tolerate fractional values too.
+ retry_after = float(retry_after_header) if retry_after_header else None
+ except ValueError:
+ # A non-numeric value (e.g. an HTTP-date) falls back to exponential backoff.
+ retry_after = None
+ logger.warning(f"LaunchDarkly rate limited (429), retrying. retry_after={retry_after_header}, url={url}")
+ raise LaunchDarklyRetryableError(f"LaunchDarkly rate limited: url={url}", retry_after=retry_after)
+
+ if response.status_code >= 500:
+ raise LaunchDarklyRetryableError(f"LaunchDarkly server error: status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"LaunchDarkly API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(access_token: str, path: str = "/caller-identity") -> int | None:
+ """Probe an endpoint and return the HTTP status code (or None on transport failure)."""
+ try:
+ response = make_tracked_session().get(f"{BASE_URL}{path}", headers=_get_headers(access_token), timeout=10)
+ return response.status_code
+ except Exception:
+ return None
+
+
+def _fetch_project_keys(headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ keys: list[str] = []
+ url: str | None = _initial_url("/projects", LAUNCHDARKLY_ENDPOINTS["projects"].page_size)
+ while url:
+ data = _fetch_page(url, headers, logger)
+ # `key` is the identifier every fan-out URL is built from; fail fast rather than
+ # silently dropping a project (and all its environments/flags/metrics) if it's absent.
+ for item in data.get("items", []):
+ keys.append(item["key"])
+ url = _next_url_from(data)
+ return keys
+
+
+def _paginate_resource(
+ start_url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
+ project_key: str,
+) -> Iterator[list[dict[str, Any]]]:
+ url: str | None = start_url
+ while url:
+ data = _fetch_page(url, headers, logger)
+ items = data.get("items", [])
+
+ if project_key:
+ for item in items:
+ item["_project_key"] = project_key
+
+ if items:
+ yield items
+
+ next_url = _next_url_from(data)
+ # Save state AFTER yielding so a heartbeat-timeout crash re-fetches from the next
+ # page rather than re-emitting the page we just yielded (merge dedupes regardless).
+ resumable_source_manager.save_state(LaunchDarklyResumeConfig(next_url=next_url or "", project_key=project_key))
+ url = next_url
+
+
+def _get_fanout_rows(
+ config: LaunchDarklyEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
+ resume: LaunchDarklyResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ project_keys = _fetch_project_keys(headers, logger)
+ if not project_keys:
+ logger.warning(f"LaunchDarkly: no projects found, nothing to sync for endpoint={config.name}")
+ return
+
+ start_idx = 0
+ resume_url: str | None = None
+ if resume is not None and resume.project_key and resume.project_key in project_keys:
+ idx = project_keys.index(resume.project_key)
+ if resume.next_url:
+ # Mid-project: pick up at the saved page within that project.
+ start_idx = idx
+ resume_url = resume.next_url
+ else:
+ # The saved project finished (empty next_url marker); start at the next one.
+ start_idx = idx + 1
+
+ for i in range(start_idx, len(project_keys)):
+ project_key = project_keys[i]
+ if i == start_idx and resume_url:
+ start_url = resume_url
+ else:
+ start_url = _initial_url(config.path.format(project_key=project_key), config.page_size)
+ yield from _paginate_resource(start_url, headers, logger, resumable_source_manager, project_key)
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = LAUNCHDARKLY_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.requires_project:
+ yield from _get_fanout_rows(config, headers, logger, resumable_source_manager, resume)
+ return
+
+ if resume is not None and resume.next_url:
+ logger.debug(f"LaunchDarkly: resuming endpoint={endpoint} from url={resume.next_url}")
+ start_url = resume.next_url
+ else:
+ start_url = _initial_url(config.path, config.page_size)
+
+ yield from _paginate_resource(start_url, headers, logger, resumable_source_manager, project_key="")
+
+
+def launchdarkly_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
+) -> SourceResponse:
+ config = LAUNCHDARKLY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_key,
+ # LaunchDarkly timestamps are epoch-millisecond integers and the datetime
+ # partitioner expects epoch-seconds, so partitioning is intentionally left off to
+ # avoid mis-bucketing rows far into the future.
+ partition_mode=None,
+ partition_keys=None,
+ )
diff --git a/posthog/temporal/data_imports/sources/launchdarkly/settings.py b/posthog/temporal/data_imports/sources/launchdarkly/settings.py
new file mode 100644
index 000000000000..51dc24464d6c
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/launchdarkly/settings.py
@@ -0,0 +1,67 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+@dataclass
+class LaunchDarklyEndpointConfig:
+ name: str
+ # Path under the API root. A ``{project_key}`` placeholder marks a fan-out endpoint
+ # that must be queried once per project.
+ path: str
+ primary_key: list[str]
+ # Fan-out endpoints depend on the list of projects; we inject ``_project_key`` into
+ # every row so a single table stays meaningful (and uniquely keyed) across projects.
+ requires_project: bool = False
+ # LaunchDarkly's list endpoints default to a small page size; 20 is the documented
+ # safe default across every endpoint we sync. Raise per-endpoint only once verified.
+ page_size: int = 20
+ # LaunchDarkly exposes no server-side timestamp filter on these resources (its
+ # timestamps are epoch-millisecond integers and the public API offers no
+ # ``updated_after``/``since`` parameter), so every endpoint is full-refresh only.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+LAUNCHDARKLY_ENDPOINTS: dict[str, LaunchDarklyEndpointConfig] = {
+ "projects": LaunchDarklyEndpointConfig(
+ name="projects",
+ path="/projects",
+ primary_key=["_id"],
+ ),
+ "members": LaunchDarklyEndpointConfig(
+ name="members",
+ path="/members",
+ primary_key=["_id"],
+ ),
+ "auditlog": LaunchDarklyEndpointConfig(
+ name="auditlog",
+ path="/auditlog",
+ primary_key=["_id"],
+ ),
+ "environments": LaunchDarklyEndpointConfig(
+ name="environments",
+ path="/projects/{project_key}/environments",
+ primary_key=["_id"],
+ requires_project=True,
+ ),
+ "metrics": LaunchDarklyEndpointConfig(
+ name="metrics",
+ path="/metrics/{project_key}",
+ primary_key=["_id"],
+ requires_project=True,
+ ),
+ "flags": LaunchDarklyEndpointConfig(
+ name="flags",
+ path="/flags/{project_key}",
+ # Flag keys are unique only within a project, so the composite key includes the
+ # injected ``_project_key``.
+ primary_key=["key", "_project_key"],
+ requires_project=True,
+ ),
+}
+
+ENDPOINTS = tuple(LAUNCHDARKLY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in LAUNCHDARKLY_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/launchdarkly/source.py b/posthog/temporal/data_imports/sources/launchdarkly/source.py
index 236490c7d1b6..787dd257d272 100644
--- a/posthog/temporal/data_imports/sources/launchdarkly/source.py
+++ b/posthog/temporal/data_imports/sources/launchdarkly/source.py
@@ -1,19 +1,35 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import LaunchDarklySourceConfig
+from posthog.temporal.data_imports.sources.launchdarkly.launchdarkly import (
+ LaunchDarklyResumeConfig,
+ launchdarkly_source,
+ validate_credentials as validate_launchdarkly_credentials,
+)
+from posthog.temporal.data_imports.sources.launchdarkly.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LAUNCHDARKLY_ENDPOINTS,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LaunchDarklySource(SimpleSource[LaunchDarklySourceConfig]):
+class LaunchDarklySource(ResumableSource[LaunchDarklySourceConfig, LaunchDarklyResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LAUNCHDARKLY
@@ -23,7 +39,97 @@ class LaunchDarklySource(SimpleSource[LaunchDarklySourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.LAUNCH_DARKLY,
label="LaunchDarkly",
- iconPath="/static/services/launchdarkly.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your LaunchDarkly access token to pull your projects, environments, feature flags, metrics, members, and audit log into the PostHog Data warehouse.
+
+You can create a personal or service access token in your [LaunchDarkly account settings](https://app.launchdarkly.com/settings/authorization). A token with the **Reader** role grants read access to every resource this source syncs.""",
+ iconPath="/static/services/launchdarkly.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/launchdarkly",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="api-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your LaunchDarkly access token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error": "Your LaunchDarkly access token does not have permission for this resource. Please check the token's role and try again.",
+ }
+
+ def get_schemas(
+ self,
+ config: LaunchDarklySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # LaunchDarkly's API exposes no server-side timestamp filter on these resources,
+ # so every endpoint is full-refresh only (no incremental/append support).
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: LaunchDarklySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Fan-out endpoints can't be probed without a project key, so confirm scope against
+ # /projects (their prerequisite); top-level endpoints probe their own path.
+ probe_path = "/caller-identity"
+ if schema_name is not None:
+ endpoint = LAUNCHDARKLY_ENDPOINTS.get(schema_name)
+ if endpoint is not None:
+ probe_path = "/projects" if endpoint.requires_project else endpoint.path
+
+ status = validate_launchdarkly_credentials(config.access_token, probe_path)
+
+ if status is None:
+ return False, "Could not reach LaunchDarkly. Please try again."
+ if status == 401:
+ return False, "Invalid LaunchDarkly access token"
+ # A valid token may legitimately lack scope for a specific endpoint. Accept 403 at
+ # source-create (schema_name is None); only reject it for a specific schema check.
+ if status == 403:
+ if schema_name is None:
+ return True, None
+ return False, f"Your access token does not have permission to read '{schema_name}'"
+ if status >= 400:
+ return False, f"LaunchDarkly returned an unexpected status ({status})"
+ return True, None
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LaunchDarklyResumeConfig]:
+ return ResumableSourceManager[LaunchDarklyResumeConfig](inputs, LaunchDarklyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LaunchDarklySourceConfig,
+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return launchdarkly_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py b/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py
new file mode 100644
index 000000000000..0af1daef8f90
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py
@@ -0,0 +1,237 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.launchdarkly.launchdarkly import (
+ API_HOST,
+ BASE_URL,
+ LaunchDarklyResumeConfig,
+ _initial_url,
+ _next_url_from,
+ _resolve_url,
+ get_rows,
+ launchdarkly_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.launchdarkly.settings import ENDPOINTS, LAUNCHDARKLY_ENDPOINTS
+
+
+def _make_manager(resume_state: LaunchDarklyResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _page(items: list[dict[str, Any]], next_href: str | None = None) -> dict[str, Any]:
+ links: dict[str, Any] = {}
+ if next_href:
+ links["next"] = {"href": next_href}
+ return {"items": items, "_links": links}
+
+
+def _resp(page: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = page
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 300
+ return resp
+
+
+class TestUrlHelpers:
+ def test_initial_url_includes_limit(self):
+ assert _initial_url("/projects", 20) == f"{BASE_URL}/projects?limit=20"
+
+ @pytest.mark.parametrize(
+ "href, expected",
+ [
+ ("/api/v2/projects?limit=20&offset=20", f"{API_HOST}/api/v2/projects?limit=20&offset=20"),
+ ("https://app.launchdarkly.com/api/v2/members?offset=40", f"{API_HOST}/api/v2/members?offset=40"),
+ ],
+ )
+ def test_resolve_url(self, href, expected):
+ assert _resolve_url(href) == expected
+
+ @pytest.mark.parametrize(
+ "data, expected",
+ [
+ ({"_links": {"next": {"href": "/api/v2/members?offset=20"}}}, f"{API_HOST}/api/v2/members?offset=20"),
+ ({"_links": {}}, None),
+ ({}, None),
+ ({"_links": {"next": {}}}, None),
+ ],
+ )
+ def test_next_url_from(self, data, expected):
+ assert _next_url_from(data) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_returns_status_code(self, mock_session, status_code):
+ response = mock.MagicMock(status_code=status_code)
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials("api-token") == status_code
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_uses_no_bearer_prefix(self, mock_session):
+ response = mock.MagicMock(status_code=200)
+ mock_session.return_value.get.return_value = response
+ validate_credentials("api-secret-token")
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "api-secret-token"
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_returns_none_on_exception(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("api-token") is None
+
+
+class TestGetRowsTopLevel:
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_paginates_via_links_next(self, mock_session):
+ pages = [
+ _page([{"_id": "1"}, {"_id": "2"}], "/api/v2/members?limit=20&offset=20"),
+ _page([{"_id": "3"}], None),
+ ]
+ mock_session.return_value.get.side_effect = [_resp(p) for p in pages]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "members", mock.MagicMock(), manager))
+
+ assert [item["_id"] for batch in batches for item in batch] == ["1", "2", "3"]
+ # No project key injected for top-level endpoints.
+ assert all("_project_key" not in item for batch in batches for item in batch)
+ # State saved after every page (final save records the empty next_url marker).
+ saved_urls = [call.args[0].next_url for call in manager.save_state.call_args_list]
+ assert saved_urls == [f"{API_HOST}/api/v2/members?limit=20&offset=20", ""]
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session):
+ mock_session.return_value.get.return_value = _resp(_page([{"_id": "9"}], None))
+
+ resume_url = f"{API_HOST}/api/v2/members?limit=20&offset=80"
+ manager = _make_manager(LaunchDarklyResumeConfig(next_url=resume_url))
+
+ list(get_rows("token", "members", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_empty_response_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _resp(_page([], None))
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "members", mock.MagicMock(), manager))
+
+ assert batches == []
+
+
+class TestGetRowsFanout:
+ def _fanout_side_effect(self) -> list[mock.MagicMock]:
+ # 1) project list, 2) environments for proj1, 3) environments for proj2
+ return [
+ _resp(_page([{"key": "proj1"}, {"key": "proj2"}], None)),
+ _resp(_page([{"_id": "e1"}], None)),
+ _resp(_page([{"_id": "e2"}], None)),
+ ]
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_iterates_projects_and_injects_project_key(self, mock_session):
+ mock_session.return_value.get.side_effect = self._fanout_side_effect()
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "environments", mock.MagicMock(), manager))
+
+ rows = [item for batch in batches for item in batch]
+ assert rows == [
+ {"_id": "e1", "_project_key": "proj1"},
+ {"_id": "e2", "_project_key": "proj2"},
+ ]
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls[0] == f"{BASE_URL}/projects?limit=20"
+ assert urls[1] == f"{BASE_URL}/projects/proj1/environments?limit=20"
+ assert urls[2] == f"{BASE_URL}/projects/proj2/environments?limit=20"
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_flags_compose_metrics_path(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _resp(_page([{"key": "proj1"}], None)),
+ _resp(_page([{"_id": "m1"}], None)),
+ ]
+ list(get_rows("token", "metrics", mock.MagicMock(), _make_manager()))
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls[1] == f"{BASE_URL}/metrics/proj1?limit=20"
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_resume_skips_completed_project(self, mock_session):
+ # proj1 was finished last run (empty next_url marker); resume must start at proj2.
+ mock_session.return_value.get.side_effect = [
+ _resp(_page([{"key": "proj1"}, {"key": "proj2"}], None)),
+ _resp(_page([{"_id": "e2"}], None)),
+ ]
+ manager = _make_manager(LaunchDarklyResumeConfig(next_url="", project_key="proj1"))
+
+ batches = list(get_rows("token", "environments", mock.MagicMock(), manager))
+
+ rows = [item for batch in batches for item in batch]
+ assert rows == [{"_id": "e2", "_project_key": "proj2"}]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ # projects list + proj2 environments only (proj1 skipped)
+ assert urls == [f"{BASE_URL}/projects?limit=20", f"{BASE_URL}/projects/proj2/environments?limit=20"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_resume_midproject_uses_saved_url(self, mock_session):
+ resume_url = f"{BASE_URL}/projects/proj1/environments?limit=20&offset=20"
+ mock_session.return_value.get.side_effect = [
+ _resp(_page([{"key": "proj1"}, {"key": "proj2"}], None)),
+ _resp(_page([{"_id": "e1b"}], None)),
+ _resp(_page([{"_id": "e2"}], None)),
+ ]
+ manager = _make_manager(LaunchDarklyResumeConfig(next_url=resume_url, project_key="proj1"))
+
+ list(get_rows("token", "environments", mock.MagicMock(), manager))
+
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls == [
+ f"{BASE_URL}/projects?limit=20",
+ resume_url,
+ f"{BASE_URL}/projects/proj2/environments?limit=20",
+ ]
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_no_projects_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _resp(_page([], None))
+
+ batches = list(get_rows("token", "flags", mock.MagicMock(), _make_manager()))
+ assert batches == []
+
+
+class TestRetryAndErrors:
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.launchdarkly.make_tracked_session")
+ def test_4xx_raises(self, mock_session):
+ resp = _resp(_page([], None), status_code=403)
+ resp.raise_for_status.side_effect = Exception("403 Client Error")
+ mock_session.return_value.get.return_value = resp
+
+ with pytest.raises(Exception, match="403 Client Error"):
+ list(get_rows("token", "members", mock.MagicMock(), _make_manager()))
+
+
+class TestLaunchDarklySourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = LAUNCHDARKLY_ENDPOINTS[endpoint]
+ response = launchdarkly_source("token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_key
+ # Partitioning is intentionally off (epoch-ms timestamps).
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_flags_use_composite_primary_key(self):
+ assert LAUNCHDARKLY_ENDPOINTS["flags"].primary_key == ["key", "_project_key"]
diff --git a/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly_source.py b/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly_source.py
new file mode 100644
index 000000000000..a0a71e931233
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly_source.py
@@ -0,0 +1,132 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import LaunchDarklySourceConfig
+from posthog.temporal.data_imports.sources.launchdarkly.launchdarkly import LaunchDarklyResumeConfig
+from posthog.temporal.data_imports.sources.launchdarkly.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.launchdarkly.source import LaunchDarklySource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestLaunchDarklySource:
+ def setup_method(self):
+ self.source = LaunchDarklySource()
+ self.team_id = 123
+ self.config = LaunchDarklySourceConfig(access_token="api-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LAUNCHDARKLY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "LaunchDarkly"
+ assert config.label == "LaunchDarkly"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/launchdarkly.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_token"]
+
+ def test_access_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://app.launchdarkly.com/api/v2/projects",
+ "403 Client Error: Forbidden for url: https://app.launchdarkly.com/api/v2/flags/proj",
+ ],
+ )
+ 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",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://app.launchdarkly.com/api/v2/members",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ # 401 substring would match the Stripe url too, so only assert the 5xx case is excluded.
+ if "500" in other_error:
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_lists_all_endpoints_full_refresh(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # LaunchDarkly has no server-side timestamp filter, so nothing is incremental.
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["flags"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "flags"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (401, None, False),
+ # A valid token may lack scope for an unselected endpoint — accept 403 at source-create.
+ (403, None, True),
+ # But reject 403 when validating a specific schema.
+ (403, "flags", False),
+ (500, None, False),
+ (None, None, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.source.validate_launchdarkly_credentials")
+ def test_validate_credentials_status_mapping(self, mock_validate, status, schema_name, expected_valid):
+ mock_validate.return_value = status
+
+ is_valid, _error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.source.validate_launchdarkly_credentials")
+ def test_validate_credentials_probes_projects_for_fanout_schema(self, mock_validate):
+ mock_validate.return_value = 200
+ self.source.validate_credentials(self.config, self.team_id, schema_name="flags")
+ assert mock_validate.call_args.args[1] == "/projects"
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.source.validate_launchdarkly_credentials")
+ def test_validate_credentials_probes_endpoint_path_for_toplevel_schema(self, mock_validate):
+ mock_validate.return_value = 200
+ self.source.validate_credentials(self.config, self.team_id, schema_name="members")
+ assert mock_validate.call_args.args[1] == "/members"
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is LaunchDarklyResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.launchdarkly.source.launchdarkly_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_launchdarkly_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "projects"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_launchdarkly_source.call_args.kwargs
+ assert kwargs["access_token"] == "api-token"
+ assert kwargs["endpoint"] == "projects"
+ assert kwargs["resumable_source_manager"] is manager