: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): implement appdynamics import source (#71214)
Tom Owerse3003e325f73
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d673fa9a42f7..069b93f19b0e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -60,6 +60,7 @@ the row lists both.| anthropic | HTTP | requests | ✅ || apify_dataset | HTTP | requests | ✅ || apollo | HTTP | requests | ✅ |+| appdynamics | HTTP | requests | ✅ || appfigures | HTTP | requests | ✅ || appfollow | HTTP | requests | ✅ || appsflyer | HTTP (CSV reports) | requests | ✅ |@@ -566,7 +567,6 @@ doesn't conflict with concurrent PRs.- amazon_sns- amazon_sqs- appcues-- appdynamics- apple_search_ads- appsignal- appstackdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/appdynamics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/appdynamics.pynew file mode 100644index 000000000000..623b46f9872f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/appdynamics.py@@ -0,0 +1,727 @@+import json+import socket+import threading+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, datetime, timedelta+from typing import Any, Optional, cast+from urllib.parse import urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPool+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.settings import (+ APPDYNAMICS_ENDPOINTS,+ APPLICATIONS_PATH,+ MAX_APPLICATIONS,+ MAX_FANOUT_REQUESTS,+ AppdynamicsEndpointConfig,+)+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.http.transport import TrackedHTTPAdapter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT = 60+MAX_RETRY_ATTEMPTS = 5+# The controller host is user-supplied, so a hostile or misbehaving controller could stream+# an unbounded or slowly-trickled body. `requests`' read timeout only limits idle gaps between+# reads, not total size or duration, so cap both: no single response may buffer more than this+# many bytes or take longer than the wall-clock budget to download.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+MAX_DOWNLOAD_SECONDS = 120+RESPONSE_CHUNK_SIZE = 1024 * 1024+# Controller OAuth tokens default to a ~5 minute TTL (configurable per controller);+# refresh well before expiry so a request never rides a token that dies mid-flight.+TOKEN_REFRESH_MARGIN_SECONDS = 60+MILLIS_PER_DAY = 24 * 60 * 60 * 1000++OAUTH_FAILED_MESSAGE = (+ "AppDynamics OAuth token request failed. Check your API client name, client secret, and account name."+)+++class AppdynamicsRetryableError(Exception):+ pass+++class AppdynamicsError(Exception):+ """Non-retryable AppDynamics transport error (bad credentials, unexpected redirect)."""+++class AppdynamicsResumeConfig:+ # Fan-out bookmark: the application currently being processed. A stable application-ID+ # bookmark (not a positional index) so applications added/removed between a crash and+ # the retry can't resume us into the wrong application. None for `applications` itself.+ application_id: int | None = None+ # For time-windowed endpoints: epoch-ms start of the next unprocessed window within+ # the bookmarked application.+ window_start: int | None = None+++class AppdynamicsAuth:+ """Resolved credentials for a single sync. Exactly one auth style is populated."""++ account_name: str+ api_client_name: Optional[str] = None+ api_client_secret: Optional[str] = None+ username: Optional[str] = None+ password: Optional[str] = None++ @property+ def uses_oauth(self) -> bool:+ return bool(self.api_client_name)+++def normalize_host(host: str) -> str:+ """Accept a bare account name, host, or full URL and return `https://<host>[:port]`.++ Forces HTTPS and strips any path, query, fragment, or userinfo so only the host (and+ optional port) survive. This keeps the value safe to feed into the SSRF host check and+ to build Controller API paths against.++ Examples: ``mycompany`` -> ``https://mycompany.saas.appdynamics.com``;+ ``https://acme.saas.appdynamics.com/controller`` -> ``https://acme.saas.appdynamics.com``.+ """+ value = (host or "").strip().rstrip("/")+ if not value:+ raise ValueError("AppDynamics controller URL is required")++ # A bare account name (no scheme, no dot) expands to the standard SaaS controller domain.+ if "://" not in value and "." not in value:+ return f"https://{value}.saas.appdynamics.com"++ if "://" not in value:+ value = f"https://{value}"++ parsed = urlparse(value)+ hostname = parsed.hostname+ if not hostname:+ raise ValueError("Invalid AppDynamics controller URL")++ netloc = f"{hostname}:{parsed.port}" if parsed.port else hostname+ return f"https://{netloc}"+++def _resolve_base_url(host: str, team_id: int) -> str:+ """Normalize the controller URL and reject internal/private hosts (SSRF guard).++ ``_is_host_safe`` is a no-op outside of PostHog Cloud, so self-hosted instances can+ still reach any host (e.g. an on-premises controller).+ """+ base_url = normalize_host(host)+ hostname = urlparse(base_url).hostname or ""+ is_safe, error = _is_host_safe(hostname, team_id)+ if not is_safe:+ raise ValueError(error or "AppDynamics controller host is not allowed.")+ return base_url+++class _InflightTrackingPoolMixin:+ """Connection pool that remembers the connection it most recently handed out.++ ``requests.Session.close()`` only clears *idle* pooled connections; it cannot reach a+ connection currently checked out and blocked inside ``getresponse()`` while ``requests``+ parses response headers. Recording that in-flight connection lets a watchdog force-close its+ socket, which unblocks the read so the request thread unwinds instead of leaking.+ """++ def _get_conn(self, timeout: Optional[float] = None) -> Any:+ conn = super()._get_conn(timeout=timeout) # type: ignore[misc]+ self._inflight_conn = conn+ return conn+++class _InflightHTTPConnectionPool(_InflightTrackingPoolMixin, HTTPConnectionPool):+ pass+++class _InflightHTTPSConnectionPool(_InflightTrackingPoolMixin, HTTPSConnectionPool):+ pass+++_INFLIGHT_POOL_CLASSES = {"http": _InflightHTTPConnectionPool, "https": _InflightHTTPSConnectionPool}+++class _AbortableTrackedAdapter(TrackedHTTPAdapter):+ """Tracked adapter whose pools expose the in-flight connection so it can be force-closed.++ Keeps the egress metering/capture of ``TrackedHTTPAdapter`` while swapping in pools that track+ the connection ``requests`` is currently blocked on, so ``abort_inflight`` can close its socket+ at the deadline — the connect/header phase that ``Session.close()`` can't interrupt.+ """++ def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:+ super().init_poolmanager(*args, **kwargs)+ self.poolmanager.pool_classes_by_scheme = _INFLIGHT_POOL_CLASSES++ def proxy_manager_for(self, *args: Any, **kwargs: Any) -> Any:+ manager = super().proxy_manager_for(*args, **kwargs)+ try:+ manager.pool_classes_by_scheme = _INFLIGHT_POOL_CLASSES+ except Exception:+ pass+ return manager++ def abort_inflight(self) -> None:+ managers = [self.poolmanager, *self.proxy_manager.values()]+ for manager in managers:+ try:+ pools = list(manager.pools._container.values())+ except Exception:+ continue+ for pool in pools:+ conn = getattr(pool, "_inflight_conn", None)+ if conn is None:+ continue+ # Shut the socket down (not just close it): closing an fd another thread is+ # blocked reading on doesn't wake that read, but a SHUT_RDWR sends FIN and makes+ # the blocked recv return, so the worker unwinds instead of leaking.+ sock = getattr(conn, "sock", None)+ if sock is not None:+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ conn.close()+ except Exception:+ pass+++def _make_abortable_session(**kwargs: Any) -> requests.Session:+ """A tracked session whose adapters can force-close the connection blocked parsing headers.++ Mirrors ``make_tracked_session`` (SSRF-safe no-redirect session, egress metering) but mounts+ ``_AbortableTrackedAdapter`` so ``_request_within_deadline`` can interrupt a trickled-header+ request. ``kwargs`` are forwarded to ``make_tracked_session``.+ """+ session = make_tracked_session(**kwargs)+ template = cast(TrackedHTTPAdapter, session.get_adapter("https://"))+ adapter = _AbortableTrackedAdapter(+ max_retries=template.max_retries,+ redact_values=getattr(template, "_redact_values", ()),+ capture=getattr(template, "_capture", True),+ )+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+++def _abort_inflight(session: requests.Session) -> None:+ for adapter in getattr(session, "adapters", {}).values():+ abort = getattr(adapter, "abort_inflight", None)+ if callable(abort):+ abort()+ # Fall back to tearing down idle pools too; harmless once we're aborting the request.+ try:+ session.close()+ except Exception:+ pass+++def _request_within_deadline(session: requests.Session, send: Callable[[], requests.Response]) -> requests.Response:+ """Issue a request under a hard wall-clock deadline covering connect and response-header parsing.++ `requests`' read timeout only limits idle gaps between socket reads, so a controller that+ trickles the status line or headers just often enough to beat that timeout keeps+ ``session.get``/``session.post`` blocked before it ever returns a ``Response`` — so+ ``_read_body_capped``'s body-level watchdog never engages. `requests` offers no total timeout,+ so run the blocking call in a daemon thread; if it overruns the budget, force-close the+ in-flight connection's socket (which ``_AbortableTrackedAdapter`` exposes). That unblocks the+ read so the worker thread and its socket are reclaimed rather than leaked, frees the import+ worker, and fails the sync non-retryably (a host behaving this way won't recover on a retry).+ The body download stays bounded separately by ``_read_body_capped``.+ """+ result: dict[str, Any] = {}++ def _run() -> None:+ try:+ result["response"] = send()+ except Exception as exc:+ result["error"] = exc++ worker = threading.Thread(target=_run, daemon=True)+ worker.start()+ worker.join(timeout=MAX_DOWNLOAD_SECONDS)+ if worker.is_alive():+ # Deadline hit before headers arrived: close the socket the worker is blocked on so it+ # unwinds, then give it a moment to observe the closed connection and exit.+ _abort_inflight(session)+ worker.join(timeout=5)+ raise AppdynamicsError(f"AppDynamics did not send response headers within the {MAX_DOWNLOAD_SECONDS}s deadline")+ if "error" in result:+ raise result["error"]+ return result["response"]+++def _fetch_oauth_token(session: requests.Session, base_url: str, auth: AppdynamicsAuth) -> tuple[str, int]:+ """Exchange the API client credentials for a short-lived bearer token.++ Returns ``(access_token, expires_in_seconds)``.+ """+ response = _request_within_deadline(+ session,+ lambda: session.post(+ f"{base_url}/controller/api/oauth/access_token",+ data={+ "grant_type": "client_credentials",+ "client_id": f"{auth.api_client_name}@{auth.account_name}",+ "client_secret": auth.api_client_secret,+ },+ timeout=REQUEST_TIMEOUT,+ allow_redirects=False,+ stream=True,+ ),+ )++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise AppdynamicsRetryableError(+ f"AppDynamics OAuth token request failed (retryable): status={response.status_code}"+ )+ if not response.ok:+ response.close()+ raise AppdynamicsError(OAUTH_FAILED_MESSAGE)++ payload = _read_json_within_limits(response)+ token = payload.get("access_token")+ if not token:+ raise AppdynamicsError(OAUTH_FAILED_MESSAGE)+ # The default token TTL is 5 minutes; fall back to that when the response omits it.+ return token, int(payload.get("expires_in") or 300)+++def _read_body_capped(response: requests.Response, byte_limit: int, error_on_limit: bool) -> bytes:+ """Read a streamed body under a hard wall-clock deadline and a byte cap.++ `iter_content` blocks until a full chunk is read, so a controller that trickles bytes+ slowly enough to fill each chunk while still beating the read-idle timeout could occupy+ an import worker far past ``MAX_DOWNLOAD_SECONDS``. A background timer closes the+ connection when the deadline passes so the in-progress read is interrupted, not merely+ checked between chunks. When ``error_on_limit`` the byte cap is a hard failure (data+ reads); otherwise the body is truncated at the cap (best-effort error logging).+ """+ aborted = threading.Event()++ def _abort() -> None:+ aborted.set()+ response.close()++ timer = threading.Timer(MAX_DOWNLOAD_SECONDS, _abort)+ timer.start()+ data = bytearray()+ try:+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_SIZE):+ if aborted.is_set():+ break+ if not chunk:+ continue+ data.extend(chunk)+ if len(data) > byte_limit:+ if error_on_limit:+ raise AppdynamicsError(+ f"AppDynamics response exceeded the {byte_limit // (1024 * 1024)} MiB size limit"+ )+ del data[byte_limit:]+ break+ except AppdynamicsError:+ raise+ except Exception:+ # Closing the connection from the watchdog surfaces here as a read error; report the+ # real cause (the deadline) rather than the incidental socket exception.+ if aborted.is_set():+ raise AppdynamicsError(+ f"AppDynamics response exceeded the {MAX_DOWNLOAD_SECONDS}s download time limit"+ ) from None+ raise+ finally:+ timer.cancel()+ response.close()++ if aborted.is_set():+ raise AppdynamicsError(f"AppDynamics response exceeded the {MAX_DOWNLOAD_SECONDS}s download time limit")+ return bytes(data)+++def _read_json_within_limits(response: requests.Response) -> Any:+ """Stream a response body under fixed byte and wall-clock caps, then parse it as JSON.++ Rejecting an oversized or trickled body before buffering it whole keeps a hostile+ controller from exhausting memory or holding an import worker open. Exceeding a limit is+ non-retryable — a host that behaves this way won't stop on a retry.+ """+ return json.loads(_read_body_capped(response, MAX_RESPONSE_BYTES, error_on_limit=True))+++def _read_capped_text(response: requests.Response, limit: int = 64 * 1024) -> str:+ """Read at most `limit` bytes of a streamed body for error logging, under the deadline."""+ return _read_body_capped(response, limit, error_on_limit=False).decode("utf-8", errors="replace")+++class AppdynamicsClient:+ """Thin Controller REST client handling auth (OAuth token refresh or basic) and retries."""++ def __init__(self, base_url: str, auth: AppdynamicsAuth, logger: FilteringBoundLogger):+ self._base_url = base_url+ self._auth = auth+ self._logger = logger+ # One session for the whole sync so the TCP/TLS connection is reused. Disable+ # urllib3-level retries — `tenacity` below is the single retry mechanism. The abortable+ # session lets the deadline force-close a connection stuck parsing response headers.+ self._session = _make_abortable_session(retry=Retry(total=0))+ self._token: str | None = None+ self._token_expires_at: datetime | None = None++ def _get_token(self) -> str:+ now = datetime.now(UTC)+ if self._token and self._token_expires_at and now < self._token_expires_at:+ return self._token++ token, expires_in = _fetch_oauth_token(self._session, self._base_url, self._auth)+ self._token = token+ # Refresh ahead of expiry, but never treat the token as valid past its actual TTL: for a+ # short-lived token the margin is capped at half the TTL so the cached window can't outlast it.+ refresh_buffer = min(TOKEN_REFRESH_MARGIN_SECONDS, expires_in // 2)+ self._token_expires_at = now + timedelta(seconds=expires_in - refresh_buffer)+ return token++ def _headers(self) -> dict[str, str]:+ headers = {"Accept": "application/json"}+ if self._auth.uses_oauth:+ headers["Authorization"] = f"Bearer {self._get_token()}"+ return headers++ def _basic_auth(self) -> Optional[tuple[str, str]]:+ if self._auth.uses_oauth:+ return None+ return (f"{self._auth.username}@{self._auth.account_name}", self._auth.password or "")++ @retry(+ retry=retry_if_exception_type(+ (+ AppdynamicsRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def get_json(self, path: str, params: dict[str, Any]) -> Any:+ # `output=JSON` is required on Controller REST endpoints — the default is XML.+ # The base URL is user-supplied; refuse redirects so a safe-looking host can't+ # bounce us to an internal one (SSRF guard).+ # `stream=True` keeps the body off the wire until we read it in bounded chunks below,+ # so a hostile controller can't make `requests` buffer an arbitrarily large response.+ # The request runs under a wall-clock deadline that also bounds the connect/header phase.+ response = _request_within_deadline(+ self._session,+ lambda: self._session.get(+ f"{self._base_url}{path}",+ params={**params, "output": "JSON"},+ headers=self._headers(),+ auth=self._basic_auth(),+ timeout=REQUEST_TIMEOUT,+ allow_redirects=False,+ stream=True,+ ),+ )++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise AppdynamicsRetryableError(+ f"AppDynamics API error (retryable): status={response.status_code}, path={path}"+ )++ if 300 <= response.status_code < 400:+ response.close()+ raise AppdynamicsError(+ f"AppDynamics returned an unexpected redirect (status={response.status_code}, path={path}); refusing to follow"+ )++ if not response.ok:+ self._logger.error(+ f"AppDynamics API error: status={response.status_code}, body={_read_capped_text(response)}, path={path}"+ )+ response.raise_for_status()++ return _read_json_within_limits(response)+++def validate_credentials(+ host: str,+ auth: AppdynamicsAuth,+ team_id: int,+ schema_name: Optional[str] = None,+) -> tuple[bool, str | None]:+ try:+ base_url = _resolve_base_url(host, team_id)+ except ValueError as exc:+ return False, str(exc)++ session = _make_abortable_session()+ headers = {"Accept": "application/json"}+ basic_auth: Optional[tuple[str, str]] = None++ if auth.uses_oauth:+ # The token exchange itself proves the API client credentials are genuine.+ try:+ token, _ = _fetch_oauth_token(session, base_url, auth)+ except (AppdynamicsError, AppdynamicsRetryableError) as exc:+ return False, str(exc)+ except requests.RequestException as exc:+ return False, str(exc)+ headers["Authorization"] = f"Bearer {token}"+ else:+ basic_auth = (f"{auth.username}@{auth.account_name}", auth.password or "")++ try:+ # Cheap probe; every Controller stream shares the same account-level read roles,+ # so one probe covers all endpoints. Refuse redirects (SSRF guard). Only the status+ # code matters, so stream and close without downloading a body a hostile host could+ # bloat. The deadline also bounds the connect/header phase so a trickled-header host+ # can't hang credential validation.+ response = _request_within_deadline(+ session,+ lambda: session.get(+ f"{base_url}{APPLICATIONS_PATH}",+ params={"output": "JSON"},+ headers=headers,+ auth=basic_auth,+ timeout=10,+ allow_redirects=False,+ stream=True,+ ),+ )+ response.close()+ except (requests.RequestException, AppdynamicsError) as exc:+ return False, str(exc)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return (+ False,+ "Invalid AppDynamics credentials. Please check your controller URL, account name, and credentials.",+ )+ if response.status_code == 403:+ # Valid identity, missing read role. Accept at source-create (the user may grant+ # roles afterwards) and only surface the error when validating a specific schema.+ if schema_name is None:+ return True, None+ return False, "Your AppDynamics user or API client is missing read access to application data."++ return False, f"AppDynamics returned an unexpected status ({response.status_code})."+++def _watermark_to_epoch_ms(value: Any) -> int:+ """Coerce the persisted incremental watermark to epoch milliseconds."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return int(dt.timestamp() * 1000)+ return int(value)+++def _iter_windows(start_ms: int, end_ms: int, chunk_days: int) -> Iterator[tuple[int, int]]:+ """Yield `[start, end)` epoch-ms chunks so each request stays bounded and resumable."""+ chunk_ms = chunk_days * MILLIS_PER_DAY+ window_start = start_ms+ while window_start < end_ms:+ yield window_start, min(window_start + chunk_ms, end_ms)+ window_start += chunk_ms+++def _metric_rows(application_id: int, metric: dict[str, Any]) -> list[dict[str, Any]]:+ """Flatten a metric-data entry's nested `metricValues` into one row per interval."""+ return [+ {+ "application_id": application_id,+ "metricId": metric.get("metricId"),+ "metricName": metric.get("metricName"),+ "metricPath": metric.get("metricPath"),+ "frequency": metric.get("frequency"),+ **value,+ }+ for value in metric.get("metricValues") or []+ ]+++def _window_start_ms(+ config: AppdynamicsEndpointConfig,+ end_ms: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> int:+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # BETWEEN_TIMES bounds are inclusive and these endpoints don't paginate, so every+ # row at the watermark timestamp was already captured by the previous run — +1ms+ # skips nothing and avoids re-fetching the boundary rows.+ return _watermark_to_epoch_ms(db_incremental_field_last_value) + 1+ return end_ms - config.default_lookback_days * MILLIS_PER_DAY+++def _get_windowed_application_rows(+ client: AppdynamicsClient,+ config: AppdynamicsEndpointConfig,+ application_id: int,+ start_ms: int,+ end_ms: int,+ metric_paths: list[str],+ resumable_source_manager: ResumableSourceManager[AppdynamicsResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ path = config.path.format(application_id=application_id)++ for window_start, window_end in _iter_windows(start_ms, end_ms, config.window_chunk_days):+ window_params = {+ "time-range-type": "BETWEEN_TIMES",+ "start-time": window_start,+ "end-time": window_end,+ }+ if config.is_metric_data:+ for metric_path in metric_paths:+ metrics = client.get_json(path, {**window_params, "metric-path": metric_path, "rollup": "false"})+ for metric in metrics or []:+ rows = _metric_rows(application_id, metric)+ if rows:+ yield rows+ else:+ rows = client.get_json(path, window_params)+ if rows:+ yield [{**row, "application_id": application_id} for row in rows]++ # Save AFTER yielding the window so a crash re-yields it (merge dedupes on the+ # primary key) rather than skipping it.+ resumable_source_manager.save_state(+ AppdynamicsResumeConfig(application_id=application_id, window_start=window_end)+ )+++def get_rows(+ base_url: str,+ endpoint: str,+ auth: AppdynamicsAuth,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppdynamicsResumeConfig],+ metric_paths: list[str],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = APPDYNAMICS_ENDPOINTS[endpoint]+ client = AppdynamicsClient(base_url, auth, logger)++ if not config.fan_out_over_applications:+ rows = client.get_json(config.path, {})+ if rows:+ yield rows+ return++ applications = client.get_json(APPLICATIONS_PATH, {}) or []+ # The controller controls this list, so dedupe IDs and cap the catalog before fanning+ # out — otherwise a hostile or misconfigured host could return a huge (or duplicate-laden)+ # list and monopolize a shared import worker. `dict.fromkeys` preserves order.+ application_ids = list(dict.fromkeys(application["id"] for application in applications))+ if len(application_ids) > MAX_APPLICATIONS:+ raise AppdynamicsError(+ f"Too many AppDynamics applications ({len(application_ids)}); the maximum per sync is {MAX_APPLICATIONS}."+ )++ # Resolve the saved application-ID bookmark to the slice of applications still to+ # process. If the bookmarked application no longer exists (deleted between runs),+ # start over from the first one — merge dedupes re-pulled rows on the primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = application_ids+ resume_window_start: int | None = None+ if resume is not None and resume.application_id is not None and resume.application_id in application_ids:+ remaining = application_ids[application_ids.index(resume.application_id) :]+ resume_window_start = resume.window_start+ logger.debug(+ f"AppDynamics: resuming '{endpoint}' from application_id={resume.application_id}, "+ f"window_start={resume_window_start}"+ )++ end_ms = int(datetime.now(UTC).timestamp() * 1000)+ start_ms = _window_start_ms(config, end_ms, should_use_incremental_field, db_incremental_field_last_value)++ # The per-dimension caps still multiply: applications × metric paths × time windows. Bound+ # the Cartesian product up front so a large-but-legal catalog can't hold a worker for the+ # activity's whole (week-long) timeout doing hundreds of thousands of sequential requests.+ num_windows = (+ sum(1 for _ in _iter_windows(start_ms, end_ms, config.window_chunk_days)) if config.time_windowed else 1+ )+ paths_factor = len(metric_paths) if config.is_metric_data else 1+ estimated_requests = len(application_ids) * paths_factor * num_windows+ if estimated_requests > MAX_FANOUT_REQUESTS:+ raise AppdynamicsError(+ f"This AppDynamics sync would issue about {estimated_requests} requests "+ f"({len(application_ids)} applications × {paths_factor} metric paths × {num_windows} time windows), "+ f"above the {MAX_FANOUT_REQUESTS} limit for one sync. Reduce the metric paths or narrow the applications."+ )++ for index, application_id in enumerate(remaining):+ if config.time_windowed:+ # Only the resumed-into application uses the saved window; the rest start fresh.+ application_start = resume_window_start if resume_window_start is not None else start_ms+ resume_window_start = None+ yield from _get_windowed_application_rows(+ client,+ config,+ application_id,+ application_start,+ end_ms,+ metric_paths,+ resumable_source_manager,+ )+ else:+ rows = client.get_json(config.path.format(application_id=application_id), {})+ if rows:+ yield [{**row, "application_id": application_id} for row in rows]++ # Advance the bookmark to the next application so a crash between applications+ # resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ AppdynamicsResumeConfig(application_id=remaining[index + 1], window_start=None)+ )+++def appdynamics_source(+ host: str,+ auth: AppdynamicsAuth,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppdynamicsResumeConfig],+ team_id: int,+ metric_paths: list[str],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = APPDYNAMICS_ENDPOINTS[endpoint]+ base_url = _resolve_base_url(host, team_id)++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ base_url=base_url,+ endpoint=endpoint,+ auth=auth,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ metric_paths=metric_paths,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Time-windowed streams fan out over applications, so rows are not globally ordered+ # by the cursor field; desc mode persists the incremental watermark only at+ # successful job end instead of checkpointing a misleading per-batch max.+ sort_mode="desc" if endpoint_config.time_windowed else "asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/canonical_descriptions.pynew file mode 100644index 000000000000..acbb3d9ae988--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/canonical_descriptions.py@@ -0,0 +1,103 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://docs.appdynamics.com/appd/24.x/latest/en/extend-appdynamics/appdynamics-apis/apm-apis"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "applications": {+ "description": "Business applications monitored by the AppDynamics controller.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier of the application within the controller.",+ "name": "Name of the business application.",+ "description": "Optional description of the application.",+ "accountGuid": "GUID of the controller account the application belongs to.",+ },+ },+ "business_transactions": {+ "description": "Business transactions registered for each monitored application.",+ "docs_url": _DOCS_URL,+ "columns": {+ "application_id": "Identifier of the application the business transaction belongs to.",+ "id": "Unique identifier of the business transaction within the controller.",+ "name": "Name of the business transaction.",+ "entryPointType": "Type of the transaction entry point (e.g. SERVLET, WEB_SERVICE).",+ "internalName": "Internal name the agent registered the transaction under.",+ "tierId": "Identifier of the tier the transaction's entry point belongs to.",+ "tierName": "Name of the tier the transaction's entry point belongs to.",+ "background": "Whether the transaction is a background task rather than a user-facing request.",+ },+ },+ "tiers": {+ "description": "Tiers (logical service groupings of nodes) for each monitored application.",+ "docs_url": _DOCS_URL,+ "columns": {+ "application_id": "Identifier of the application the tier belongs to.",+ "id": "Unique identifier of the tier within the controller.",+ "name": "Name of the tier.",+ "type": "Tier type (e.g. Application Server).",+ "agentType": "Type of app agent reporting for the tier (e.g. APP_AGENT, DOT_NET_APP_AGENT).",+ "numberOfNodes": "Number of nodes currently registered in the tier.",+ "description": "Optional description of the tier.",+ },+ },+ "nodes": {+ "description": "Nodes (individual monitored processes or JVMs/CLRs) for each monitored application.",+ "docs_url": _DOCS_URL,+ "columns": {+ "application_id": "Identifier of the application the node belongs to.",+ "id": "Unique identifier of the node within the controller.",+ "name": "Name of the node.",+ "type": "Node type (e.g. Application Server).",+ "tierId": "Identifier of the tier the node belongs to.",+ "tierName": "Name of the tier the node belongs to.",+ "machineId": "Identifier of the machine the node runs on.",+ "machineName": "Hostname of the machine the node runs on.",+ "machineOSType": "Operating system of the machine the node runs on.",+ "appAgentVersion": "Version of the app agent running on the node.",+ "agentType": "Type of agent reporting for the node.",+ "ipAddresses": "IP addresses registered for the node.",+ },+ },+ "health_rule_violations": {+ "description": "Health rule violations (policy breaches such as slow response times or high error rates) per application, synced by their start time.",+ "docs_url": _DOCS_URL,+ "columns": {+ "application_id": "Identifier of the application the violation occurred in.",+ "id": "Unique identifier of the health rule violation within the controller.",+ "name": "Name of the health rule that was violated.",+ "description": "Summary of the violation.",+ "severity": "Severity of the violation (WARNING or CRITICAL).",+ "status": "Current status of the violation (e.g. OPEN, RESOLVED, CANCELED).",+ "incidentStatus": "Status of the incident associated with the violation.",+ "startTimeInMillis": "Epoch-ms timestamp when the violation started.",+ "endTimeInMillis": "Epoch-ms timestamp when the violation ended (0 while still open).",+ "detectedTimeInMillis": "Epoch-ms timestamp when the controller detected the violation.",+ "affectedEntityDefinition": "Entity (tier, node, business transaction) the violation affects.",+ "triggeredEntityDefinition": "Entity whose metrics triggered the violation.",+ "deepLinkUrl": "Link to the violation in the AppDynamics controller UI.",+ },+ },+ "metric_data": {+ "description": "Metric time series for the configured metric paths, flattened to one row per metric per interval.",+ "docs_url": _DOCS_URL,+ "columns": {+ "application_id": "Identifier of the application the metric belongs to.",+ "metricId": "Unique identifier of the metric within the controller.",+ "metricName": "Short name of the metric (e.g. BTM|Application Summary|Average Response Time (ms)).",+ "metricPath": "Full metric browser path of the metric.",+ "frequency": "Granularity of the data point (ONE_MIN, TEN_MIN, or SIXTY_MIN).",+ "startTimeInMillis": "Epoch-ms timestamp of the start of the interval the value covers.",+ "value": "Average value of the metric over the interval.",+ "min": "Minimum observed value over the interval.",+ "max": "Maximum observed value over the interval.",+ "current": "Most recent observed value in the interval.",+ "sum": "Sum of observed values over the interval.",+ "count": "Number of observations aggregated into the interval.",+ "occurrences": "Number of times the metric was reported in the interval.",+ "standardDeviation": "Standard deviation of observed values over the interval.",+ "useRange": "Whether min/max carry meaningful range information for this metric.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/settings.pynew file mode 100644index 000000000000..06116185fadb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/settings.py@@ -0,0 +1,126 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++APPLICATIONS_PATH = "/controller/rest/applications"++# Metric paths synced when the user leaves the "Metric paths" field empty. App-level KPIs+# (calls per minute, average response time, error rate, ...) broken out per tier.+DEFAULT_METRIC_PATHS = ["Overall Application Performance|*"]++# The metric_data stream sends one request per (application, metric path, time window), so an+# unbounded path list would let a single source config fan out into tens of thousands of+# requests per sync and monopolize shared import workers. Wildcards make broad coverage+# possible well within this cap.+MAX_METRIC_PATHS = 50++# Application-fan-out streams issue at least one request per application, multiplied by time+# windows and metric paths. The application list comes from the user-supplied controller, so+# an unbounded catalog would let a hostile or misconfigured host monopolize a shared import+# worker. Cap the catalog size per sync (generous enough for real accounts).+MAX_APPLICATIONS = 1000++# The per-dimension caps still multiply — applications × metric paths × time windows — so bound+# the Cartesian product too. A sync above this many estimated requests is rejected before the+# fan-out starts, keeping a large-but-legal catalog from holding a worker for the activity's+# week-long timeout. Generous enough for realistic accounts; the worst pathological combination+# (max applications × max metric paths × the 7-day metric window) lands well above it.+MAX_FANOUT_REQUESTS = 100_000++# The Controller's time-windowed endpoints filter server-side on epoch-ms `start-time` /+# `end-time` (`time-range-type=BETWEEN_TIMES`), so the row's `startTimeInMillis` is the+# only reliable incremental cursor. There is no `updated-since` filter on any endpoint.+TIME_WINDOW_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "startTimeInMillis",+ "type": IncrementalFieldType.Integer,+ "field": "startTimeInMillis",+ "field_type": IncrementalFieldType.Integer,+ },+]+++@dataclass+class AppdynamicsEndpointConfig:+ name: str+ """Stream name shown to the user."""+ path: str+ """Controller REST path. Fan-out paths carry an `{application_id}` placeholder."""+ primary_keys: list[str]+ """Unique across the whole table — fan-out children include `application_id`."""+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ fan_out_over_applications: bool = False+ """Iterate every application and query this endpoint once per application."""+ time_windowed: bool = False+ """Endpoint requires `time-range-type=BETWEEN_TIMES` with epoch-ms start/end params."""+ is_metric_data: bool = False+ """Metric-data responses nest `metricValues` per metric; rows are flattened out of them."""+ default_lookback_days: int = 30+ """First-sync / full-refresh window for time-windowed endpoints."""+ window_chunk_days: int = 7+ """Time-windowed fetches are chunked so responses stay bounded and resumable."""+ description: str | None = None+++APPDYNAMICS_ENDPOINTS: dict[str, AppdynamicsEndpointConfig] = {+ "applications": AppdynamicsEndpointConfig(+ name="applications",+ path=APPLICATIONS_PATH,+ primary_keys=["id"],+ ),+ "business_transactions": AppdynamicsEndpointConfig(+ name="business_transactions",+ path="/controller/rest/applications/{application_id}/business-transactions",+ primary_keys=["application_id", "id"],+ fan_out_over_applications=True,+ ),+ "tiers": AppdynamicsEndpointConfig(+ name="tiers",+ path="/controller/rest/applications/{application_id}/tiers",+ primary_keys=["application_id", "id"],+ fan_out_over_applications=True,+ ),+ "nodes": AppdynamicsEndpointConfig(+ name="nodes",+ path="/controller/rest/applications/{application_id}/nodes",+ primary_keys=["application_id", "id"],+ fan_out_over_applications=True,+ ),+ "health_rule_violations": AppdynamicsEndpointConfig(+ name="health_rule_violations",+ path="/controller/rest/applications/{application_id}/problems/healthrule-violations",+ primary_keys=["application_id", "id"],+ fan_out_over_applications=True,+ time_windowed=True,+ incremental_fields=TIME_WINDOW_INCREMENTAL_FIELDS,+ default_lookback_days=30,+ window_chunk_days=7,+ description=(+ "Health rule violations are synced by their start time. Status changes to previously "+ "synced violations (e.g. a violation resolving) are only picked up on a full refresh. "+ "Only syncs the last 30 days on initial sync."+ ),+ ),+ "metric_data": AppdynamicsEndpointConfig(+ name="metric_data",+ path="/controller/rest/applications/{application_id}/metric-data",+ primary_keys=["application_id", "metricId", "startTimeInMillis"],+ fan_out_over_applications=True,+ time_windowed=True,+ is_metric_data=True,+ incremental_fields=TIME_WINDOW_INCREMENTAL_FIELDS,+ default_lookback_days=7,+ window_chunk_days=1,+ description=(+ "Metric time series for the metric paths configured on the source (defaults to "+ "'Overall Application Performance|*'). One row per metric per interval. "+ "Only syncs the last 7 days on initial sync."+ ),+ ),+}++ENDPOINTS = tuple(APPDYNAMICS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in APPDYNAMICS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/source.pyindex 81afa093ace5..eee2747adfa9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/source.py@@ -1,30 +1,259 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.appdynamics import (+ AppdynamicsAuth,+ AppdynamicsResumeConfig,+ appdynamics_source,+ validate_credentials as validate_appdynamics_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.settings import (+ APPDYNAMICS_ENDPOINTS,+ DEFAULT_METRIC_PATHS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MAX_METRIC_PATHS,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AppdynamicsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AppdynamicsSource(SimpleSource[AppdynamicsSourceConfig]):+class AppdynamicsSource(ResumableSource[AppdynamicsSourceConfig, AppdynamicsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPDYNAMICS+ @property+ def connection_host_fields(self) -> list[str]:+ # Every credential is qualified as `<user-or-client>@{account_name}`, so retargeting+ # `account_name` sends the preserved secret to a different account — require re-entry.+ return ["account_name"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.APPDYNAMICS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Splunk AppDynamics (Cisco)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["appdynamics", "cisco", "splunk", "apm"],+ caption="""Sync your Splunk AppDynamics (Cisco) APM data (applications, business transactions, tiers, nodes, health rule violations, and metric time series) into the PostHog Data warehouse.++Enter your controller URL (e.g. `https://mycompany.saas.appdynamics.com`) and your account name, then authenticate with an OAuth API client (recommended) or a username and password.++You can create an API client in your controller under **Administration → API Clients**. The API client (or user) needs read access to the applications you want to sync. If your account signs in via Cisco Identity Provider, basic authentication is disabled and an API client is required.""",iconPath="/static/services/appdynamics.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/appdynamics",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Controller URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://mycompany.saas.appdynamics.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="account_name",+ label="Account name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="mycompany",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="api_client",+ options=[+ SourceFieldSelectConfigOption(+ label="OAuth API client",+ value="api_client",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_client_name",+ label="API client name",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="posthog-import",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Username and password",+ value="basic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ SourceFieldInputConfig(+ name="metric_paths",+ label="Metric paths (one per line)",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="Overall Application Performance|*",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your AppDynamics credentials are invalid or expired. Please update your credentials and reconnect.",+ "403 Client Error": "Your AppDynamics user or API client is missing read access to application data. Grant the required roles and try again.",+ "AppDynamics OAuth token request failed": "Your AppDynamics API client credentials were rejected. Check your API client name, client secret, and account name, then reconnect.",+ "Too many metric paths configured": None,+ "Too many AppDynamics applications": None,+ "AppDynamics sync would issue": None,+ }++ def _auth_for_config(self, config: AppdynamicsSourceConfig) -> AppdynamicsAuth:+ if config.auth_method.selection == "basic":+ if not config.auth_method.username or not config.auth_method.password:+ raise ValueError("Missing AppDynamics username or password")+ return AppdynamicsAuth(+ account_name=config.account_name,+ username=config.auth_method.username,+ password=config.auth_method.password,+ )++ if not config.auth_method.api_client_name or not config.auth_method.api_client_secret:+ raise ValueError("Missing AppDynamics API client name or client secret")+ return AppdynamicsAuth(+ account_name=config.account_name,+ api_client_name=config.auth_method.api_client_name,+ api_client_secret=config.auth_method.api_client_secret,+ )++ def _metric_paths_for_config(self, config: AppdynamicsSourceConfig) -> list[str]:+ paths: list[str] = [line.strip() for line in (config.metric_paths or "").splitlines() if line.strip()]+ if len(paths) > MAX_METRIC_PATHS:+ raise ValueError(+ f"Too many metric paths configured ({len(paths)}); the maximum is {MAX_METRIC_PATHS}. "+ "Use wildcard paths to cover more metrics with fewer entries."+ )+ return paths or list(DEFAULT_METRIC_PATHS)++ def get_schemas(+ self,+ config: AppdynamicsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=APPDYNAMICS_ENDPOINTS[endpoint].description,+ )+ 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: AppdynamicsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ auth = self._auth_for_config(config)+ self._metric_paths_for_config(config)+ except ValueError as exc:+ return False, str(exc)++ return validate_appdynamics_credentials(config.host, auth, team_id, schema_name=schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppdynamicsResumeConfig]:+ return ResumableSourceManager[AppdynamicsResumeConfig](inputs, AppdynamicsResumeConfig)++ def source_for_pipeline(+ self,+ config: AppdynamicsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AppdynamicsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return appdynamics_source(+ host=config.host,+ auth=self._auth_for_config(config),+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ metric_paths=self._metric_paths_for_config(config),+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.pynew file mode 100644index 000000000000..c8fa8763edde--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py@@ -0,0 +1,602 @@+import json+import time+import socket+import threading+from typing import Any+from urllib.parse import urlparse++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics import (+ appdynamics as appdynamics_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.appdynamics import (+ AppdynamicsAuth,+ AppdynamicsClient,+ AppdynamicsError,+ AppdynamicsResumeConfig,+ appdynamics_source,+ get_rows,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.settings import (+ APPDYNAMICS_ENDPOINTS,+ MAX_METRIC_PATHS,+)++BASE_URL = "https://acme.saas.appdynamics.com"+MILLIS_PER_DAY = 24 * 60 * 60 * 1000+# 2024-01-31T00:00:00Z, used as the frozen "now" for window tests+FROZEN_NOW_MS = 1706659200000++BASIC_AUTH = AppdynamicsAuth(account_name="acme", username="user", password="pass")+OAUTH_AUTH = AppdynamicsAuth(account_name="acme", api_client_name="client", api_client_secret="secret")+++class FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = ""):+ self.status_code = status_code+ self._json = json_data if json_data is not None else []+ self.text = text++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._json++ def iter_content(self, chunk_size: int = 1) -> Any:+ body = self.text.encode() if self.text else json.dumps(self._json).encode()+ yield body++ def close(self) -> None:+ pass++ def raise_for_status(self) -> None:+ if not self.ok:+ response = requests.Response()+ response.status_code = self.status_code+ raise requests.HTTPError(f"{self.status_code} Client Error", response=response)+++class _TrickleResponse:+ """A 200 response whose body never stops arriving, to exercise the download deadline.++ Yields small chunks with a gap shorter than any read-idle timeout, so only the hard+ wall-clock deadline (which closes the connection) can end the read.+ """++ status_code = 200+ text = ""++ def __init__(self) -> None:+ self._closed = False++ @property+ def ok(self) -> bool:+ return True++ def iter_content(self, chunk_size: int = 1) -> Any:+ while not self._closed:+ time.sleep(0.02)+ yield b"x" * 8+ raise OSError("connection closed")++ def close(self) -> None:+ self._closed = True++ def json(self) -> Any:+ return {}+++class _PartialHeaderServer:+ """A local HTTP server that sends a status line then trickles headers forever without ever+ terminating them, holding the connection open — reproducing a controller that stalls in the+ response-header phase faster than any read-idle timeout. Records when the client closes the+ socket so a test can prove the in-flight connection was actually torn down (not leaked).+ """++ def __init__(self) -> None:+ self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ self._listener.bind(("127.0.0.1", 0))+ self._listener.listen(1)+ self.port = self._listener.getsockname()[1]+ self.client_closed = threading.Event()+ self._thread = threading.Thread(target=self._serve, daemon=True)++ def _serve(self) -> None:+ try:+ conn, _ = self._listener.accept()+ except OSError:+ return+ try:+ conn.recv(4096) # consume the request line/headers+ conn.sendall(b"HTTP/1.1 200 OK\r\n") # status line only — headers never terminated+ while True:+ conn.sendall(b"X-Trickle: 1\r\n") # keep dribbling headers, never the blank line+ time.sleep(0.02)+ except OSError:+ # sendall raises once the client force-closes its socket at the deadline.+ self.client_closed.set()+ finally:+ try:+ conn.close()+ except OSError:+ pass++ def __enter__(self) -> "_PartialHeaderServer":+ self._thread.start()+ return self++ def __exit__(self, *exc: Any) -> None:+ try:+ self._listener.close()+ except OSError:+ pass+++class FakeResumeManager:+ def __init__(self, initial: AppdynamicsResumeConfig | None = None):+ self.state = initial+ self.saved: list[AppdynamicsResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> AppdynamicsResumeConfig | None:+ return self.state++ def save_state(self, data: AppdynamicsResumeConfig) -> None:+ self.state = data+ self.saved.append(data)+++class FakeSession:+ """Routes GETs by URL path and records every request's path + params."""++ def __init__(self, responder: Any = None, post_response: FakeResponse | None = None):+ self._responder = responder or (lambda path, params: FakeResponse(json_data=[]))+ self._post_response = post_response or FakeResponse(json_data={"access_token": "tok", "expires_in": 300})+ self.get_calls: list[tuple[str, dict[str, Any], dict[str, Any]]] = []+ self.post_calls: list[dict[str, Any]] = []++ def get(self, url: str, params: dict[str, Any], **kwargs: Any) -> FakeResponse:+ path = urlparse(url).path+ self.get_calls.append((path, params, kwargs))+ return self._responder(path, params)++ def post(self, url: str, **kwargs: Any) -> FakeResponse:+ self.post_calls.append(kwargs)+ return self._post_response+++def _patch_session(session: Any) -> Any:+ return mock.patch.object(appdynamics_module, "_make_abortable_session", return_value=session)+++class TestNormalizeHost:+ @parameterized.expand(+ [+ ("full_url", "https://acme.saas.appdynamics.com", "https://acme.saas.appdynamics.com"),+ ("trailing_slash", "https://acme.saas.appdynamics.com/", "https://acme.saas.appdynamics.com"),+ ("bare_account", "acme", "https://acme.saas.appdynamics.com"),+ ("host_no_scheme", "acme.saas.appdynamics.com", "https://acme.saas.appdynamics.com"),+ ("http_upgraded", "http://acme.saas.appdynamics.com", "https://acme.saas.appdynamics.com"),+ (+ "strips_path_and_query",+ "https://acme.saas.appdynamics.com/controller?x=1",+ "https://acme.saas.appdynamics.com",+ ),+ ("strips_userinfo", "https://u:[email protected]", "https://acme.saas.appdynamics.com"),+ ("keeps_port", "https://onprem.example.com:8090", "https://onprem.example.com:8090"),+ ("whitespace", " acme ", "https://acme.saas.appdynamics.com"),+ ]+ )+ def test_normalize(self, _name: str, value: str, expected: str) -> None:+ assert normalize_host(value) == expected++ def test_empty_raises(self) -> None:+ with pytest.raises(ValueError):+ normalize_host("")+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("forbidden_at_create_accepted", 403, None, True),+ ("forbidden_for_schema_rejected", 403, "applications", False),+ ("unexpected_status", 500, None, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_valid: bool) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(status_code=status))+ with _patch_session(session):+ valid, _ = validate_credentials(BASE_URL, BASIC_AUTH, team_id=1, schema_name=schema_name)+ assert valid is expected_valid++ def test_oauth_exchanges_token_before_probe(self) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(json_data=[]))+ with _patch_session(session):+ valid, error = validate_credentials(BASE_URL, OAUTH_AUTH, team_id=1)++ assert (valid, error) == (True, None)+ assert session.post_calls[0]["data"]["client_id"] == "client@acme"+ _, _, kwargs = session.get_calls[0]+ assert kwargs["headers"]["Authorization"] == "Bearer tok"++ def test_oauth_rejected_token_fails_validation(self) -> None:+ session = FakeSession(post_response=FakeResponse(status_code=401, json_data={}))+ with _patch_session(session):+ valid, error = validate_credentials(BASE_URL, OAUTH_AUTH, team_id=1)++ assert valid is False+ assert error is not None+ assert session.get_calls == []++ def test_invalid_host(self) -> None:+ valid, error = validate_credentials("", BASIC_AUTH, team_id=1)+ assert valid is False+ assert error is not None++ def test_network_error_is_handled(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch.object(appdynamics_module, "make_tracked_session", return_value=session):+ valid, error = validate_credentials(BASE_URL, BASIC_AUTH, team_id=1)+ assert valid is False+ assert error is not None++ def test_redirects_are_never_followed(self) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(status_code=200))+ with _patch_session(session):+ validate_credentials(BASE_URL, BASIC_AUTH, team_id=1)+ _, _, kwargs = session.get_calls[0]+ assert kwargs["allow_redirects"] is False+ # The probe only needs the status code, so it must stream rather than buffer a body.+ assert kwargs["stream"] is True+++class TestAppdynamicsClient:+ def test_basic_auth_sends_account_qualified_username(self) -> None:+ session = FakeSession()+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ client.get_json("/controller/rest/applications", {})++ _, params, kwargs = session.get_calls[0]+ assert kwargs["auth"] == ("user@acme", "pass")+ assert "Authorization" not in kwargs["headers"]+ assert params["output"] == "JSON"++ def test_oauth_token_cached_until_expiry(self) -> None:+ session = FakeSession()+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, OAUTH_AUTH, mock.MagicMock())++ with freeze_time("2024-01-31T00:00:00Z") as frozen:+ client.get_json("/controller/rest/applications", {})+ client.get_json("/controller/rest/applications", {})+ assert len(session.post_calls) == 1++ frozen.move_to("2024-01-31T00:10:00Z") # past the 5 min TTL+ client.get_json("/controller/rest/applications", {})+ assert len(session.post_calls) == 2++ for _, _, kwargs in session.get_calls:+ assert kwargs["headers"]["Authorization"] == "Bearer tok"+ assert kwargs["auth"] is None++ def test_short_lived_token_is_refreshed_before_its_ttl(self) -> None:+ # A short TTL must not be cached past expiry: the refresh margin is capped at half the+ # TTL, so a 10s token is re-fetched well before 10s rather than trusted for a fixed 30s.+ session = FakeSession(post_response=FakeResponse(json_data={"access_token": "tok", "expires_in": 10}))+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, OAUTH_AUTH, mock.MagicMock())++ with freeze_time("2024-01-31T00:00:00Z") as frozen:+ client.get_json("/controller/rest/applications", {})+ assert len(session.post_calls) == 1+ frozen.move_to("2024-01-31T00:00:06Z") # past the 5s cache window (10 - min(60, 5))+ client.get_json("/controller/rest/applications", {})+ assert len(session.post_calls) == 2++ def test_oauth_failure_raises_non_retryable(self) -> None:+ session = FakeSession(post_response=FakeResponse(status_code=400, json_data={}))+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, OAUTH_AUTH, mock.MagicMock())+ with pytest.raises(AppdynamicsError):+ client.get_json("/controller/rest/applications", {})++ def test_redirect_raises_non_retryable(self) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(status_code=302))+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ with pytest.raises(AppdynamicsError):+ client.get_json("/controller/rest/applications", {})++ def test_client_error_raises_http_error(self) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(status_code=401))+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ with pytest.raises(requests.HTTPError):+ client.get_json("/controller/rest/applications", {})++ def test_response_body_is_streamed(self) -> None:+ session = FakeSession()+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ client.get_json("/controller/rest/applications", {})+ _, _, kwargs = session.get_calls[0]+ assert kwargs["stream"] is True++ def test_oversized_response_is_rejected(self) -> None:+ session = FakeSession(responder=lambda path, params: FakeResponse(json_data=[{"a": "b" * 100}]))+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ # Non-retryable: a host that overflows the cap won't stop on a retry.+ with mock.patch.object(appdynamics_module, "MAX_RESPONSE_BYTES", 10):+ with pytest.raises(AppdynamicsError):+ client.get_json("/controller/rest/applications", {})++ def test_download_deadline_interrupts_trickled_body(self) -> None:+ # A trickled body never idle-times-out, so only the wall-clock deadline can end it.+ session = FakeSession(responder=lambda path, params: _TrickleResponse())+ with _patch_session(session):+ client = AppdynamicsClient(BASE_URL, BASIC_AUTH, mock.MagicMock())+ with mock.patch.object(appdynamics_module, "MAX_DOWNLOAD_SECONDS", 0.2):+ started = time.monotonic()+ with pytest.raises(AppdynamicsError):+ client.get_json("/controller/rest/applications", {})+ assert time.monotonic() - started < 5++ def test_header_deadline_closes_connection_stuck_parsing_headers(self) -> None:+ # A real server that stalls mid-header keeps `requests` blocked before the body watchdog+ # can run. The deadline must force-close the in-flight socket so the request unwinds and+ # the connection is reclaimed — Session.close() alone can't reach an in-use connection.+ with _PartialHeaderServer() as server:+ client = AppdynamicsClient(f"http://127.0.0.1:{server.port}", BASIC_AUTH, mock.MagicMock())+ with mock.patch.object(appdynamics_module, "MAX_DOWNLOAD_SECONDS", 0.3):+ started = time.monotonic()+ with pytest.raises(AppdynamicsError, match="response headers"):+ client.get_json("/controller/rest/applications", {})+ assert time.monotonic() - started < 5+ # The client must have actually torn down the connection, not merely abandoned it.+ assert server.client_closed.wait(timeout=5)+++def _run_get_rows(+ responder: Any,+ endpoint: str,+ manager: FakeResumeManager,+ metric_paths: list[str] | None = None,+ **kwargs: Any,+) -> tuple[list[list[dict[str, Any]]], FakeSession]:+ session = FakeSession(responder=responder)+ with _patch_session(session):+ batches = list(+ get_rows(+ base_url=BASE_URL,+ endpoint=endpoint,+ auth=BASIC_AUTH,+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ metric_paths=metric_paths or ["Overall Application Performance|*"],+ **kwargs,+ )+ )+ return batches, session+++class TestGetRows:+ def test_applications_yields_rows_without_state(self) -> None:+ manager = FakeResumeManager()+ batches, _ = _run_get_rows(+ lambda path, params: FakeResponse(json_data=[{"id": 1, "name": "app"}]),+ "applications",+ manager,+ )+ assert batches == [[{"id": 1, "name": "app"}]]+ assert manager.saved == []++ def test_too_many_applications_is_rejected(self) -> None:+ many = [{"id": i} for i in range(appdynamics_module.MAX_APPLICATIONS + 1)]+ manager = FakeResumeManager()+ with pytest.raises(AppdynamicsError):+ _run_get_rows(lambda path, params: FakeResponse(json_data=many), "business_transactions", manager)++ def test_metric_data_fan_out_budget_is_enforced(self) -> None:+ # Max applications × max metric paths × the 7-day metric window blows the aggregate+ # budget even though each individual dimension is within its own cap.+ apps = [{"id": i} for i in range(appdynamics_module.MAX_APPLICATIONS)]+ paths = [f"Metric|{i}" for i in range(MAX_METRIC_PATHS)]+ manager = FakeResumeManager()+ with pytest.raises(AppdynamicsError):+ _run_get_rows(lambda path, params: FakeResponse(json_data=apps), "metric_data", manager, metric_paths=paths)++ def test_duplicate_application_ids_are_deduplicated(self) -> None:+ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}, {"id": 1}, {"id": 2}])+ return FakeResponse(json_data=[{"name": "bt"}])++ manager = FakeResumeManager()+ batches, _ = _run_get_rows(responder, "business_transactions", manager)+ assert [row["application_id"] for batch in batches for row in batch] == [1, 2]++ def test_fan_out_injects_application_id_and_bookmarks_next_app(self) -> None:+ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}, {"id": 2}])+ return FakeResponse(json_data=[{"id": 10, "name": f"bt-{path.split('/')[4]}"}])++ manager = FakeResumeManager()+ batches, _ = _run_get_rows(responder, "business_transactions", manager)++ assert [row["application_id"] for batch in batches for row in batch] == [1, 2]+ # bookmark points at the NEXT application, saved once per non-final application+ assert [s.application_id for s in manager.saved] == [2]++ def test_fan_out_resumes_from_bookmarked_application(self) -> None:+ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}, {"id": 2}, {"id": 3}])+ return FakeResponse(json_data=[{"id": 10}])++ manager = FakeResumeManager(initial=AppdynamicsResumeConfig(application_id=2))+ batches, session = _run_get_rows(responder, "tiers", manager)++ fetched_apps = [row["application_id"] for batch in batches for row in batch]+ assert fetched_apps == [2, 3]++ def test_fan_out_deleted_bookmark_application_starts_over(self) -> None:+ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}])+ return FakeResponse(json_data=[{"id": 10}])++ manager = FakeResumeManager(initial=AppdynamicsResumeConfig(application_id=99))+ batches, _ = _run_get_rows(responder, "tiers", manager)+ assert [row["application_id"] for batch in batches for row in batch] == [1]++ @freeze_time("2024-01-31T00:00:00Z")+ def test_windowed_full_refresh_uses_lookback_and_chunks(self) -> None:+ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}])+ return FakeResponse(json_data=[{"id": 5, "startTimeInMillis": params["start-time"]}])++ manager = FakeResumeManager()+ batches, session = _run_get_rows(responder, "health_rule_violations", manager)++ window_calls = [(params["start-time"], params["end-time"]) for path, params, _ in session.get_calls[1:]]+ expected_start = FROZEN_NOW_MS - 30 * MILLIS_PER_DAY+ # 30-day lookback fetched in 7-day chunks: 4 full chunks + a 2-day remainder+ assert len(window_calls) == 5+ assert window_calls[0][0] == expected_start+ assert window_calls[-1][1] == FROZEN_NOW_MS+ for start, end in window_calls:+ assert start < end+ assert all(params["time-range-type"] == "BETWEEN_TIMES" for _, params, _ in session.get_calls[1:])+ # each window's state is saved after its rows are yielded+ assert [s.window_start for s in manager.saved] == [end for _, end in window_calls]++ @freeze_time("2024-01-31T00:00:00Z")+ def test_windowed_incremental_starts_one_ms_after_watermark(self) -> None:+ watermark = FROZEN_NOW_MS - MILLIS_PER_DAY++ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}])+ return FakeResponse(json_data=[])++ manager = FakeResumeManager()+ _, session = _run_get_rows(+ responder,+ "health_rule_violations",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ _, params, _ = session.get_calls[1]+ assert params["start-time"] == watermark + 1+ assert params["end-time"] == FROZEN_NOW_MS+ assert len(session.get_calls) == 2++ @freeze_time("2024-01-31T00:00:00Z")+ def test_windowed_resume_uses_saved_window_for_bookmarked_app_only(self) -> None:+ resume_start = FROZEN_NOW_MS - MILLIS_PER_DAY++ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 1}, {"id": 2}])+ return FakeResponse(json_data=[])++ manager = FakeResumeManager(initial=AppdynamicsResumeConfig(application_id=1, window_start=resume_start))+ _, session = _run_get_rows(+ responder,+ "health_rule_violations",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=FROZEN_NOW_MS - 2 * MILLIS_PER_DAY,+ )++ app_1_call = session.get_calls[1]+ app_2_call = session.get_calls[2]+ assert "/applications/1/" in app_1_call[0]+ assert app_1_call[1]["start-time"] == resume_start+ # the app after the bookmark starts from the regular watermark-derived window+ assert "/applications/2/" in app_2_call[0]+ assert app_2_call[1]["start-time"] == FROZEN_NOW_MS - 2 * MILLIS_PER_DAY + 1++ @freeze_time("2024-01-31T00:00:00Z")+ def test_metric_data_flattens_metric_values_per_path(self) -> None:+ metric = {+ "metricId": 42,+ "metricName": "BTM|Application Summary|Average Response Time (ms)",+ "metricPath": "Overall Application Performance|Average Response Time (ms)",+ "frequency": "ONE_MIN",+ "metricValues": [+ {"startTimeInMillis": 1706572800000, "value": 12, "min": 1, "max": 20},+ {"startTimeInMillis": 1706572860000, "value": 15, "min": 2, "max": 30},+ ],+ }++ def responder(path: str, params: dict[str, Any]) -> FakeResponse:+ if path == "/controller/rest/applications":+ return FakeResponse(json_data=[{"id": 7}])+ return FakeResponse(json_data=[metric])++ manager = FakeResumeManager()+ batches, session = _run_get_rows(+ responder,+ "metric_data",+ manager,+ metric_paths=["Overall Application Performance|*", "Business Transaction Performance|*"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=FROZEN_NOW_MS - MILLIS_PER_DAY,+ )++ # one window (1 day, 1-day chunks) x two metric paths+ metric_calls = session.get_calls[1:]+ assert [params["metric-path"] for _, params, _ in metric_calls] == [+ "Overall Application Performance|*",+ "Business Transaction Performance|*",+ ]+ assert all(params["rollup"] == "false" for _, params, _ in metric_calls)++ rows = [row for batch in batches for row in batch]+ assert len(rows) == 4+ # every primary key column is present on every row+ assert all({"application_id", "metricId", "startTimeInMillis"} <= set(row) for row in rows)+ assert rows[0]["application_id"] == 7+ assert rows[0]["metricId"] == 42+ assert rows[0]["value"] == 12+++class TestAppdynamicsSourceResponse:+ @parameterized.expand(list(APPDYNAMICS_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint: str) -> None:+ response = appdynamics_source(+ host=BASE_URL,+ auth=BASIC_AUTH,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(), # type: ignore[arg-type]+ team_id=1,+ metric_paths=["Overall Application Performance|*"],+ )+ config = APPDYNAMICS_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == ("desc" if config.time_windowed else "asc")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics_source.pynew file mode 100644index 000000000000..b3f71deb739d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics_source.py@@ -0,0 +1,208 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.appdynamics import (+ AppdynamicsAuth,+ AppdynamicsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.settings import (+ ENDPOINTS,+ MAX_METRIC_PATHS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.source import AppdynamicsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ AppdynamicsAuthMethodConfig,+ AppdynamicsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _api_client_config(metric_paths: str | None = None) -> AppdynamicsSourceConfig:+ return AppdynamicsSourceConfig(+ host="https://acme.saas.appdynamics.com",+ account_name="acme",+ auth_method=AppdynamicsAuthMethodConfig(+ selection="api_client", api_client_name="client", api_client_secret="secret"+ ),+ metric_paths=metric_paths,+ )+++def _basic_config(username: str | None = "user", password: str | None = "pass") -> AppdynamicsSourceConfig:+ return AppdynamicsSourceConfig(+ host="https://acme.saas.appdynamics.com",+ account_name="acme",+ auth_method=AppdynamicsAuthMethodConfig(selection="basic", username=username, password=password),+ )+++def _source_inputs(schema_name: str = "applications", incremental: bool = False) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=1704067200000 if incremental else None,+ db_incremental_field_earliest_value=None,+ incremental_field="startTimeInMillis" if incremental else None,+ incremental_field_type=None,+ job_id="job-1",+ logger=mock.MagicMock(),+ reset_pipeline=False,+ )+++class TestAppdynamicsSource:+ def setup_method(self) -> None:+ self.source = AppdynamicsSource()+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.APPDYNAMICS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Appdynamics"+ assert config.unreleasedSource is not True+ assert config.releaseStatus == ReleaseStatus.ALPHA++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "account_name", "auth_method", "metric_paths"]++ host_field = config.fields[0]+ assert isinstance(host_field, SourceFieldInputConfig)+ assert host_field.required is True++ auth_field = config.fields[2]+ assert isinstance(auth_field, SourceFieldSelectConfig)+ assert {option.value for option in auth_field.options} == {"api_client", "basic"}++ def test_non_retryable_errors(self) -> None:+ errors = self.source.get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors+ assert "AppDynamics OAuth token request failed" in errors++ def test_account_name_is_a_connection_host_field(self) -> None:+ # Changing account_name retargets the preserved credential, so it must force re-entry.+ assert self.source.connection_host_fields == ["account_name"]++ def test_get_schemas_incremental_flags(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_api_client_config(), self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ incremental_endpoints = {name for name, s in schemas.items() if s.supports_incremental}+ assert incremental_endpoints == {"health_rule_violations", "metric_data"}+ for name in incremental_endpoints:+ assert {f["field"] for f in schemas[name].incremental_fields} == {"startTimeInMillis"}++ def test_get_schemas_filtered_by_name(self) -> None:+ schemas = self.source.get_schemas(_api_client_config(), self.team_id, names=["applications"])+ assert [s.name for s in schemas] == ["applications"]+ assert self.source.get_schemas(_api_client_config(), self.team_id, names=["nope"]) == []++ def test_auth_for_config_api_client(self) -> None:+ auth = self.source._auth_for_config(_api_client_config())+ assert auth == AppdynamicsAuth(account_name="acme", api_client_name="client", api_client_secret="secret")+ assert auth.uses_oauth is True++ def test_auth_for_config_basic(self) -> None:+ auth = self.source._auth_for_config(_basic_config("u", "p"))+ assert auth == AppdynamicsAuth(account_name="acme", username="u", password="p")+ assert auth.uses_oauth is False++ def test_auth_for_config_missing_basic_password_raises(self) -> None:+ with pytest.raises(ValueError):+ self.source._auth_for_config(_basic_config("u", None))++ def test_auth_for_config_missing_api_client_secret_raises(self) -> None:+ config = AppdynamicsSourceConfig(+ host="https://acme.saas.appdynamics.com",+ account_name="acme",+ auth_method=AppdynamicsAuthMethodConfig(selection="api_client", api_client_name="client"),+ )+ with pytest.raises(ValueError):+ self.source._auth_for_config(config)++ def test_metric_paths_default_when_empty(self) -> None:+ assert self.source._metric_paths_for_config(_api_client_config()) == ["Overall Application Performance|*"]++ def test_metric_paths_parsed_from_textarea(self) -> None:+ config = _api_client_config(+ metric_paths="Overall Application Performance|*\n\n Business Transaction Performance|*|* \n"+ )+ assert self.source._metric_paths_for_config(config) == [+ "Overall Application Performance|*",+ "Business Transaction Performance|*|*",+ ]++ def test_metric_paths_over_limit_rejected(self) -> None:+ config = _api_client_config(metric_paths="\n".join(f"Metric|{i}" for i in range(MAX_METRIC_PATHS + 1)))++ with pytest.raises(ValueError):+ self.source._metric_paths_for_config(config)++ # the same cap rejects the config at source create/edit time+ valid, error = self.source.validate_credentials(config, self.team_id)+ assert valid is False+ assert error is not None and "Too many metric paths" in error++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.source.validate_appdynamics_credentials"+ )+ def test_validate_credentials_plumbing(self, mock_validate: mock.Mock) -> None:+ mock_validate.return_value = (True, None)+ valid, error = self.source.validate_credentials(_api_client_config(), self.team_id, schema_name="applications")++ assert (valid, error) == (True, None)+ _, kwargs = mock_validate.call_args+ assert kwargs["schema_name"] == "applications"++ def test_validate_credentials_missing_creds(self) -> None:+ valid, error = self.source.validate_credentials(_basic_config("u", None), self.team_id)+ assert valid is False+ assert error is not None++ def test_get_resumable_source_manager(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AppdynamicsResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.source.appdynamics_source"+ )+ def test_source_for_pipeline_plumbing(self, mock_source: mock.Mock) -> None:+ inputs = _source_inputs(schema_name="health_rule_violations", incremental=True)+ manager = mock.MagicMock()++ self.source.source_for_pipeline(_api_client_config(), manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["host"] == "https://acme.saas.appdynamics.com"+ assert kwargs["auth"] == AppdynamicsAuth(+ account_name="acme", api_client_name="client", api_client_secret="secret"+ )+ assert kwargs["endpoint"] == "health_rule_violations"+ assert kwargs["team_id"] == 1+ assert kwargs["metric_paths"] == ["Overall Application Performance|*"]+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1704067200000++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appdynamics.source.appdynamics_source"+ )+ def test_source_for_pipeline_full_refresh_drops_watermark(self, mock_source: mock.Mock) -> None:+ inputs = _source_inputs(schema_name="health_rule_violations", incremental=False)+ inputs.db_incremental_field_last_value = 1704067200000++ self.source.source_for_pipeline(_api_client_config(), mock.MagicMock(), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 0a179d2635f0..fc133193cf06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -8,6 +8,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common impfrom products.warehouse_sources.backend.types import ExternalDataSourceType+class AppdynamicsAuthMethodConfig(config.Config):+ selection: Literal["api_client", "basic"] = "api_client"+ api_client_name: str | None = None+ api_client_secret: str | None = None+ username: str | None = None+ password: str | None = None++@config.configclass BigQueryDatasetProjectConfig(config.Config):dataset_project_id: str@@ -321,7 +330,10 @@ class AppcuesSourceConfig(config.Config):@config.configclass AppdynamicsSourceConfig(config.Config):- pass+ host: str+ account_name: str+ auth_method: AppdynamicsAuthMethodConfig+ metric_paths: str | None = None@config.config