: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
import json
import socket
import threading
import contextvars
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_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.sources.appdynamics.settings import (
APPDYNAMICS_ENDPOINTS,
APPLICATIONS_PATH,
MAX_APPLICATIONS,
MAX_FANOUT_REQUESTS,
MAX_PAGES_PER_TIME_WINDOW,
MAX_WINDOW_SPLITS,
METRIC_TREE_MAX_DEPTH,
METRIC_TREE_MAX_REQUESTS_PER_APPLICATION,
MIN_WINDOW_SPLIT_MS,
AppdynamicsEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
ResumableSourceManager,
SourceResponse,
TrackedHTTPAdapter,
_is_host_safe,
frozen,
make_tracked_session,
retry_with_deadline,
)
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)."""
@dataclasses.dataclass(frozen=False)
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
@frozen
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] = dataclasses.field(default=None, repr=False)
username: Optional[str] = None
password: Optional[str] = dataclasses.field(default=None, repr=False)
@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
# The thread runs in a copy of this context, so the request deadline of the retry loop reaches the request.
worker = threading.Thread(target=contextvars.copy_context().run, args=(_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]]: # nosemgrep: tuple-return-prefer-dataclass -- pre-existing, file moved
if self._auth.uses_oauth:
return None
return (f"{self._auth.username}@{self._auth.account_name}", self._auth.password or "")
@retry_with_deadline(
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], output_json: bool = True) -> Any:
# `output=JSON` is required on Controller REST endpoints — the default is XML. The
# alerting API serves JSON and defines no such parameter, so it opts out.
# 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"} if output_json else params,
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]]: # nosemgrep: tuple-return-prefer-dataclass -- pre-existing, file moved
"""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_params(config: AppdynamicsEndpointConfig, start_ms: int, end_ms: int) -> dict[str, Any]:
if config.uses_epoch_time_params:
return {"startTime": start_ms, "endTime": end_ms}
return {"time-range-type": "BETWEEN_TIMES", "start-time": start_ms, "end-time": end_ms}
def _rows_from_payload(config: AppdynamicsEndpointConfig, payload: Any) -> list[dict[str, Any]]:
"""Pull the row list out of a response, unwrapping the endpoint's envelope where it has one."""
if config.data_selector:
payload = (payload or {}).get(config.data_selector)
return payload or []
class SplitAllowance:
"""Extra requests window bisection and paging may spend, shared by every window in one sync.
Splitting and paging happen per window, but the fan-out limit is per sync. Without a shared
allowance a controller that returns a full response for every window would multiply an
already-accepted sync by the per-window split cap, which is how the limit gets bypassed.
"""
def __init__(self, allowance: int) -> None:
self.remaining = max(allowance, 0)
def take(self) -> bool:
if self.remaining <= 0:
return False
self.remaining -= 1
return True
def _get_paged_window_rows(
client: AppdynamicsClient,
config: AppdynamicsEndpointConfig,
path: str,
params: dict[str, Any],
application_id: int,
split_allowance: SplitAllowance,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
"""Yield one time window's rows a page at a time, stopping on the first short page."""
page_size = config.page_size or 0
for page_number in range(MAX_PAGES_PER_TIME_WINDOW):
# Only the first page of each window is counted by the fan-out estimate, so the rest
# draw from the same per-sync allowance window bisection spends from.
if page_number > 0 and not split_allowance.take():
logger.warning(
f"AppDynamics: '{config.name}' stopped paging for application_id={application_id} at the "
"per-sync request limit; later pages of that window were not synced."
)
return
rows = _rows_from_payload(
config,
client.get_json(
path,
{**params, "pageSize": page_size, "pageNumber": page_number},
output_json=config.sends_output_json_param,
),
)
if rows:
yield [{**row, "application_id": application_id} for row in rows]
if len(rows) < page_size:
return
logger.warning(
f"AppDynamics: '{config.name}' hit the {MAX_PAGES_PER_TIME_WINDOW}-page cap for "
f"application_id={application_id}; later pages of that window were not synced."
)
def _get_window_rows(
client: AppdynamicsClient,
config: AppdynamicsEndpointConfig,
path: str,
base_params: dict[str, Any],
application_id: int,
window_start: int,
window_end: int,
split_allowance: SplitAllowance,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
"""Yield one time window's rows, bisecting the window when the response comes back capped.
`events` and `request-snapshots` return at most `result_cap` rows for a window and expose
no cursor to page past that, so a full response means rows were dropped. Halving the window
and refetching is the only way to reach them. Endpoints without a cap fetch once.
"""
pending = [(window_start, window_end)]
splits = 0
while pending:
start, end = pending.pop()
window_params = {**base_params, **_window_params(config, start, end)}
if config.page_size is not None:
yield from _get_paged_window_rows(
client, config, path, window_params, application_id, split_allowance, logger
)
continue
rows = _rows_from_payload(
config, client.get_json(path, window_params, output_json=config.sends_output_json_param)
)
if config.result_cap is not None and len(rows) >= config.result_cap:
# `take` spends from the sync-wide allowance, so ask for it last.
if end - start > MIN_WINDOW_SPLIT_MS and splits < MAX_WINDOW_SPLITS and split_allowance.take():
midpoint = start + (end - start) // 2
# Pushed newest-first so the older half pops first and rows stay in time order.
pending.extend([(midpoint, end), (start, midpoint)])
splits += 1
continue
logger.warning(
f"AppDynamics: '{config.name}' hit the {config.result_cap}-row response cap for "
f"application_id={application_id} between {start} and {end} and cannot be split further; "
"some rows in that window were not synced."
)
if rows:
yield [{**row, "application_id": application_id} for row in rows]
def _escape_metric_path_segment(name: str) -> str:
"""Escape a metric name so it survives being joined into a `metric-path` value.
The Controller reads `|` as the path separator and `\\` as its escape character, so a name
containing either has to be escaped before the path can be sent back in a request.
"""
return name.replace("\\", "\\\\").replace("|", "\\|")
def _get_metric_tree_rows(
client: AppdynamicsClient,
config: AppdynamicsEndpointConfig,
application_id: int,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
"""Walk one application's metric hierarchy, yielding a row per folder or metric found.
`/metrics` lists only the immediate children of a path, so each folder costs a request.
The hierarchy is unbounded, so the walk stops at `METRIC_TREE_MAX_DEPTH` and at the
per-application request budget.
"""
path = config.path.format(application_id=application_id)
pending: list[tuple[str, int]] = [("", 0)]
requests_made = 0
while pending:
if requests_made >= METRIC_TREE_MAX_REQUESTS_PER_APPLICATION:
logger.warning(
f"AppDynamics: stopped walking the metric hierarchy for application_id={application_id} at the "
f"{METRIC_TREE_MAX_REQUESTS_PER_APPLICATION}-request budget; deeper metric paths were not listed."
)
return
parent_path, depth = pending.pop(0)
items = client.get_json(path, {"metric-path": parent_path} if parent_path else {}) or []
requests_made += 1
rows: list[dict[str, Any]] = []
for item in items:
name = item.get("name")
if not name:
continue
segment = _escape_metric_path_segment(name)
item_path = f"{parent_path}|{segment}" if parent_path else segment
rows.append(
{
"application_id": application_id,
"path": item_path,
"parent_path": parent_path or None,
"name": name,
"type": item.get("type"),
"depth": depth + 1,
}
)
if item.get("type") == "folder" and depth + 1 < METRIC_TREE_MAX_DEPTH:
pending.append((item_path, depth + 1))
if rows:
yield rows
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],
event_types: list[str],
resumable_source_manager: ResumableSourceManager[AppdynamicsResumeConfig],
split_allowance: SplitAllowance,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
path = config.path.format(application_id=application_id)
base_params: dict[str, Any] = dict(config.extra_params)
if config.is_events:
base_params["event-types"] = ",".join(event_types)
for window_start, window_end in _iter_windows(start_ms, end_ms, config.window_chunk_days):
if config.is_metric_data:
window_params = _window_params(config, window_start, window_end)
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:
yield from _get_window_rows(
client,
config,
path,
base_params,
application_id,
window_start,
window_end,
split_allowance,
logger,
)
# 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],
event_types: 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 = _rows_from_payload(config, client.get_json(config.path, {}, output_json=config.sends_output_json_param))
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
)
requests_per_application = num_windows
dimensions = [f"{len(application_ids)} applications"]
if config.is_metric_data:
requests_per_application *= len(metric_paths)
dimensions.append(f"{len(metric_paths)} metric paths")
if config.is_metric_tree:
requests_per_application *= METRIC_TREE_MAX_REQUESTS_PER_APPLICATION
dimensions.append(f"up to {METRIC_TREE_MAX_REQUESTS_PER_APPLICATION} metric hierarchy requests")
if config.time_windowed:
dimensions.append(f"{num_windows} time windows")
estimated_requests = len(application_ids) * requests_per_application
if estimated_requests > MAX_FANOUT_REQUESTS:
raise AppdynamicsError(
f"This AppDynamics sync would issue about {estimated_requests} requests "
f"({' × '.join(dimensions)}), above the {MAX_FANOUT_REQUESTS} limit for one sync. "
"Reduce the metric paths or narrow the applications."
)
# Bisecting a capped window costs requests the estimate above cannot predict, so those
# draw from the same per-sync limit. Once the headroom is gone the windows stay whole.
split_allowance = SplitAllowance(MAX_FANOUT_REQUESTS - estimated_requests)
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,
event_types,
resumable_source_manager,
split_allowance,
logger,
)
elif config.is_metric_tree:
yield from _get_metric_tree_rows(client, config, application_id, logger)
else:
rows = _rows_from_payload(
config,
client.get_json(
config.path.format(application_id=application_id),
{},
output_json=config.sends_output_json_param,
),
)
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],
event_types: 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,
event_types=event_types,
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",
)