: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 dynatrace import source (#71238)
Tom Owers6d901fb9d241
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7758c8a0fb8a..e4a33439d10f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -176,6 +176,7 @@ the row lists both.| drata | HTTP | requests | ✅ || dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ |+| dynatrace | HTTP | requests | ✅ || e2b | HTTP | requests | ✅ || e_conomic | HTTP | requests | ✅ || easypost | HTTP | requests | ✅ |@@ -664,7 +665,6 @@ doesn't conflict with concurrent PRs.- dwolla- dynamics365- dynamodb-- dynatrace- e2b- ebay- eloquadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.pynew file mode 100644index 000000000000..20a856fd361f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.py@@ -0,0 +1,148 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_ENTITY_COLUMNS = {+ "entityId": "Unique identifier of the monitored entity (e.g. HOST-ABC123).",+ "displayName": "Display name of the entity as shown in the Dynatrace UI.",+ "type": "Type of the monitored entity (e.g. HOST, SERVICE, APPLICATION).",+ "firstSeenTms": "Timestamp when the entity was first seen, in UTC milliseconds.",+ "lastSeenTms": "Timestamp when the entity was last seen, in UTC milliseconds.",+ "properties": "Type-specific properties of the entity (e.g. OS type, bitness).",+ "tags": "Tags assigned to the entity.",+ "managementZones": "Management zones the entity is part of.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "problems": {+ "description": "Problems detected by Davis AI within the environment, including their impact, root cause, and lifecycle.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/problems-v2/problems",+ "columns": {+ "problemId": "Unique identifier of the problem.",+ "displayId": "Human-friendly identifier of the problem (e.g. P-12345).",+ "title": "Short summary of the problem.",+ "status": "Status of the problem: OPEN or CLOSED.",+ "severityLevel": "Severity of the problem (e.g. AVAILABILITY, ERROR, PERFORMANCE, RESOURCE_CONTENTION).",+ "impactLevel": "Level of impact: APPLICATION, ENVIRONMENT, INFRASTRUCTURE, or SERVICES.",+ "startTime": "Start time of the problem, in UTC milliseconds.",+ "endTime": "End time of the problem, in UTC milliseconds. -1 while the problem is still open.",+ "affectedEntities": "Entities affected by the problem.",+ "impactedEntities": "Entities impacted by the problem.",+ "rootCauseEntity": "The entity identified as the root cause of the problem.",+ "entityTags": "Tags of the entities affected by the problem.",+ "managementZones": "Management zones the problem affects.",+ "problemFilters": "Alerting profiles that match the problem.",+ "recentComments": "Most recent comments on the problem.",+ },+ },+ "events": {+ "description": "Events observed within the environment, such as deployments, restarts, and anomaly events.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/events-v2",+ "columns": {+ "eventId": "Unique identifier of the event.",+ "eventType": "Type of the event (e.g. PROCESS_RESTART, CUSTOM_DEPLOYMENT).",+ "title": "Title of the event.",+ "status": "Status of the event: OPEN or CLOSED.",+ "startTime": "Start time of the event, in UTC milliseconds.",+ "endTime": "End time of the event, in UTC milliseconds. Null while the event is still active.",+ "correlationId": "Correlation ID of the event.",+ "entityId": "The monitored entity the event relates to.",+ "entityTags": "Tags of the related entity.",+ "managementZones": "Management zones the related entity is part of.",+ "properties": "Key/value properties of the event.",+ "underMaintenance": "Whether the event happened while the entity was under maintenance.",+ "suppressAlert": "Whether alerting was suppressed for the event.",+ "suppressProblem": "Whether problem creation was suppressed for the event.",+ "frequentEvent": "Whether the event is a frequent event (does not open problems).",+ },+ },+ "audit_logs": {+ "description": "Audit log of configuration changes, token operations, and user logins in the environment.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/audit-logs",+ "columns": {+ "logId": "Unique identifier of the log entry.",+ "eventType": "Type of the recorded operation (e.g. CREATE, UPDATE, DELETE, LOGIN).",+ "category": "Category of the recorded operation (e.g. CONFIG, TOKEN, WEB_UI).",+ "entityId": "Identifier of the changed object.",+ "environmentId": "Identifier of the environment where the operation happened.",+ "message": "Description of the recorded operation.",+ "patch": "JSON patch describing the change, including old values.",+ "success": "Whether the recorded operation succeeded.",+ "timestamp": "Timestamp of the operation, in UTC milliseconds.",+ "user": "User or token that performed the operation.",+ "userOrigin": "Origin (IP address or client) of the user.",+ "userType": "Type of the actor: USER_NAME, TOKEN_HASH, PUBLIC_TOKEN_IDENTIFIER, or SERVICE_NAME.",+ },+ },+ "security_problems": {+ "description": "Vulnerabilities (security problems) detected by Dynatrace Application Security.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/application-security/vulnerabilities",+ "columns": {+ "securityProblemId": "Unique identifier of the security problem.",+ "displayId": "Human-friendly identifier of the security problem (e.g. S-1234).",+ "status": "Status of the security problem: OPEN or RESOLVED.",+ "muted": "Whether the security problem is muted.",+ "externalVulnerabilityId": "Identifier of the vulnerability in the external source (e.g. CVE).",+ "vulnerabilityType": "Type of the vulnerability (e.g. THIRD_PARTY, CODE_LEVEL).",+ "title": "Title of the security problem.",+ "packageName": "Name of the vulnerable package.",+ "technology": "Affected technology (e.g. JAVA, DOTNET).",+ "firstSeenTimestamp": "Timestamp when the security problem was first seen, in UTC milliseconds.",+ "lastUpdatedTimestamp": "Timestamp of the most recent update, in UTC milliseconds.",+ },+ },+ "hosts": {+ "description": "Monitored host entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "services": {+ "description": "Monitored service entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "applications": {+ "description": "Monitored application entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "process_groups": {+ "description": "Monitored process group entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "metrics": {+ "description": "Catalog of metric descriptors available in the environment (built-in and custom).",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2",+ "columns": {+ "metricId": "Fully qualified key of the metric (e.g. builtin:host.cpu.usage).",+ "displayName": "Display name of the metric.",+ "description": "Short description of the metric.",+ "unit": "Unit of the metric.",+ "created": "Timestamp when the metric was created, in UTC milliseconds. Null for built-in metrics.",+ "lastWritten": "Timestamp when the metric last received a data point, in UTC milliseconds.",+ "entityType": "Entity types the metric applies to.",+ "aggregationTypes": "Aggregations available for the metric.",+ "tags": "Tags applied to the metric.",+ },+ },+ "slos": {+ "description": "Service-level objectives with their current evaluation status and error budget.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/service-level-objectives",+ "columns": {+ "id": "Unique identifier of the SLO.",+ "name": "Name of the SLO.",+ "description": "Description of the SLO.",+ "enabled": "Whether the SLO is enabled.",+ "target": "Target value of the SLO, in percent.",+ "warning": "Warning threshold of the SLO, in percent.",+ "timeframe": "Timeframe the SLO is evaluated over.",+ "status": "Evaluation status: SUCCESS, WARNING, or FAILURE.",+ "evaluatedPercentage": "Calculated value of the SLO, in percent. -1 if the calculation failed.",+ "errorBudget": "Remaining error budget of the SLO, in percent.",+ "metricExpression": "Metric expression the SLO is based on.",+ "filter": "Entity filter of the SLO.",+ "relatedOpenProblems": "Number of open problems related to the SLO.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.pynew file mode 100644index 000000000000..901dac4486f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py@@ -0,0 +1,393 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.settings import (+ DYNATRACE_ENDPOINTS,+ ENDPOINT_SCOPES,+ DynatraceEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+# Cheap probe used to confirm the token is genuine at source-create. A 403 still proves the token+# is real (it authenticated but lacks the problems.read scope), so it's accepted there.+PROBE_PATH = "/api/v2/problems"++HOST_NOT_ALLOWED_ERROR = "Dynatrace environment URL is not allowed"+++class DynatraceRetryableError(Exception):+ pass+++class DynatraceHostNotAllowedError(Exception):+ pass+++class DynatraceResumeConfig:+ # Cursor from the last yielded page. Follow-up URLs are rebuilt from the configured+ # environment URL, so tampered resume state can't redirect the authenticated request.+ next_page_key: str+++def normalize_environment_url(environment_url: str) -> str:+ """Turn whatever the user typed into a consistent environment base URL.++ SaaS environments live at ``https://{env-id}.live.dynatrace.com``; Managed deployments at+ ``https://{domain}/e/{env-id}``, so a path prefix must be preserved — we only strip a+ scheme-less prefix, trailing slashes, and an accidentally-pasted ``/api``-style suffix.+ """+ url = environment_url.strip().rstrip("/")+ # Only default the scheme for bare hosts — a non-http(s) scheme must survive normalization+ # so _validated_hostname can reject it.+ if url and "://" not in url:+ url = f"https://{url}"+ for suffix in ("/api/v2", "/api/v1", "/api"):+ if url.lower().endswith(suffix):+ url = url[: -len(suffix)]+ break+ return url.rstrip("/")+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Api-Token {api_token}", "Accept": "application/json"}+++def _get_session(api_token: str) -> requests.Session:+ # The environment URL is user-supplied, so pin redirects off so host validation and the+ # outbound request stay on the same target (SSRF defense-in-depth). Redact the token from logs.+ # Body capture stays off: event properties and audit-log patches are free-form customer data+ # that can carry secrets under keys the name-based scrubbers can't recognize. Requests are+ # still metered and logged.+ return make_tracked_session(+ headers=_headers(api_token), redact_values=(api_token,), allow_redirects=False, capture=False+ )+++def _validated_hostname(base_url: str) -> Optional[str]:+ """Hostname of the normalized environment URL, or None when the URL is malformed or ambiguous.++ SSRF guard: urlparse treats a backslash as ordinary userinfo and an "@" as a userinfo+ separator, but urllib3/requests treat the backslash as an authority separator, so+ ``https://127.0.0.1\\@example.com`` validates as example.com yet connects to 127.0.0.1.+ A legitimate environment URL has no userinfo, so reject either construct outright and+ require a plain http(s) URL with a clean hostname.+ """+ if "\\" in base_url or "%5c" in base_url.lower():+ return None+ parsed = urlparse(base_url)+ if parsed.scheme not in ("http", "https") or "@" in parsed.netloc:+ return None+ # The API token rides in the Authorization header on every request, so plaintext http would+ # leak it to any network observer. On PostHog Cloud the request egresses over the public+ # internet, so require https. Self-hosted operators control their own network path (e.g. a+ # Managed cluster reachable only over http), so http stays allowed there.+ if parsed.scheme == "http" and is_cloud():+ return None+ hostname = parsed.hostname+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):+ return None+ return hostname+++def _check_host(environment_url: str, team_id: int) -> None:+ hostname = _validated_hostname(normalize_environment_url(environment_url))+ if not hostname:+ raise DynatraceHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ raise DynatraceHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+++def _format_from_value(value: Any) -> str:+ """Format an incremental cursor value for Dynatrace's ``from`` param.++ Dynatrace timestamps are epoch-ms integers, so the stored watermark is usually an int already;+ datetimes are converted for safety, and relative strings (``now-30d``) pass through.+ """+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return str(int(dt.timestamp() * 1000))+ if isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return str(int(dt.timestamp() * 1000))+ return str(value)+++def _build_first_page_params(+ config: DynatraceEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ params: dict[str, str] = {"pageSize": str(config.page_size)}++ if config.entity_selector:+ params["entitySelector"] = config.entity_selector++ if config.supports_time_filter or config.default_from:+ # Continue from the stored watermark on incremental runs; otherwise seed the first sync /+ # full refresh with the endpoint's lookback so Dynatrace doesn't fall back to its very+ # narrow defaults (problems/events default to now-2h).+ if config.supports_time_filter and should_use_incremental_field and db_incremental_field_last_value:+ params["from"] = _format_from_value(db_incremental_field_last_value)+ elif config.default_from:+ params["from"] = config.default_from++ params.update(config.extra_params)+ return params+++def _build_url(base_url: str, path: str, params: dict[str, str]) -> str:+ url = f"{base_url}{path}"+ if not params:+ return url+ return f"{url}?{urlencode(params)}"+++def _next_page_url(base_url: str, config: DynatraceEndpointConfig, next_page_key: str) -> str:+ # Dynatrace requires follow-up pages to carry ONLY nextPageKey — the key encodes the original+ # query (filters, page size, fields), and mixing it with other params is rejected.+ return _build_url(base_url, config.path, {"nextPageKey": next_page_key})+++def _extract_items(response_json: Any, config: DynatraceEndpointConfig) -> list[dict[str, Any]]:+ if not isinstance(response_json, dict):+ return []+ items = response_json.get(config.data_key, [])+ return items if isinstance(items, list) else []+++def validate_credentials(+ environment_url: str,+ api_token: str,+ team_id: Optional[int] = None,+ schema_name: Optional[str] = None,+) -> tuple[bool, str | None]:+ """Validate Dynatrace credentials with a single cheap probe.++ With no ``schema_name`` (source-create) a 403 is accepted: the token authenticated but lacks+ the probed endpoint's scope, and users may legitimately only grant scopes for the endpoints+ they sync. With a ``schema_name`` the probe must actually reach that endpoint.+ """+ base_url = normalize_environment_url(environment_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return (+ False,+ "Dynatrace environment URL is invalid. Enter the full environment URL, e.g. https://abc12345.live.dynatrace.com",+ )+ if team_id is not None:+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ if schema_name is not None and schema_name in DYNATRACE_ENDPOINTS:+ config = DYNATRACE_ENDPOINTS[schema_name]+ probe_params: dict[str, str] = {"pageSize": "1"}+ if config.entity_selector:+ probe_params["entitySelector"] = config.entity_selector+ if config.supports_time_filter or config.default_from:+ probe_params["from"] = "now-1h"+ url = _build_url(base_url, config.path, probe_params)+ required_scope = ENDPOINT_SCOPES.get(schema_name)+ else:+ url = _build_url(base_url, PROBE_PATH, {"pageSize": "1", "from": "now-1h"})+ required_scope = None++ try:+ session = _get_session(api_token)+ response = session.get(url, timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Dynatrace API token. Check the token and environment URL, then try again."+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ scope_hint = f" (`{required_scope}`)" if required_scope else ""+ return False, f"Your Dynatrace API token is missing the scope required for this table{scope_hint}."+ if 300 <= response.status_code < 400:+ return False, HOST_NOT_ALLOWED_ERROR+ return False, f"Dynatrace credential validation failed (status {response.status_code})."+++def check_endpoint_permissions(+ environment_url: str, api_token: str, endpoints: list[str], team_id: int+) -> dict[str, str | None]:+ """Per-endpoint scope probe for the schema picker. ``None`` = reachable, else a short reason.++ Endpoints sharing a scope (the four entity tables) share one probe. Only a real 403 denial is+ reported — throttles, 5xx, and network blips must not mark a table as missing permissions.+ """+ base_url = normalize_environment_url(environment_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return dict.fromkeys(endpoints, HOST_NOT_ALLOWED_ERROR)+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return dict.fromkeys(endpoints, host_err or HOST_NOT_ALLOWED_ERROR)++ session = _get_session(api_token)+ results: dict[str, str | None] = {}+ denial_by_scope: dict[str, str | None] = {}++ for endpoint in endpoints:+ config = DYNATRACE_ENDPOINTS.get(endpoint)+ if config is None:+ results[endpoint] = None+ continue++ scope = ENDPOINT_SCOPES.get(endpoint, "")+ if scope in denial_by_scope:+ results[endpoint] = denial_by_scope[scope]+ continue++ probe_params: dict[str, str] = {"pageSize": "1"}+ if config.entity_selector:+ probe_params["entitySelector"] = config.entity_selector+ if config.supports_time_filter or config.default_from:+ probe_params["from"] = "now-1h"++ try:+ response = session.get(+ _build_url(base_url, config.path, probe_params),+ timeout=10,+ )+ except requests.exceptions.RequestException:+ results[endpoint] = None+ continue++ denial = f"Your API token is missing the `{scope}` scope" if response.status_code == 403 else None+ denial_by_scope[scope] = denial+ results[endpoint] = denial++ return results+++def get_rows(+ environment_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DynatraceResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = DYNATRACE_ENDPOINTS[endpoint]+ # Re-check at run time (not just at source-create) in case the environment URL was edited or+ # now resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ _check_host(environment_url, team_id)++ base_url = normalize_environment_url(environment_url)+ # One tracked session reused across pages and retries; the token is redacted from logged URLs+ # and captured samples.+ session = _get_session(api_token)++ @retry(+ retry=retry_if_exception_type(+ (+ DynatraceRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_url: str) -> Any:+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ # The session never follows redirects: a 3xx would move the sync off the validated host+ # (SSRF), so refuse it rather than silently fetching an empty body.+ if 300 <= response.status_code < 400:+ raise DynatraceHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)++ if response.status_code == 429 or response.status_code >= 500:+ raise DynatraceRetryableError(+ f"Dynatrace API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Dynatrace API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.next_page_key:+ url = _next_page_url(base_url, config, resume_config.next_page_key)+ logger.debug(f"Dynatrace: resuming {endpoint} from saved nextPageKey")+ else:+ params = _build_first_page_params(config, should_use_incremental_field, db_incremental_field_last_value)+ url = _build_url(base_url, config.path, params)++ while True:+ data = fetch_page(url)++ items = _extract_items(data, config)+ if items:+ yield items++ next_page_key = data.get("nextPageKey") if isinstance(data, dict) else None+ if not next_page_key:+ break++ # Save state AFTER yielding the batch — a crash re-yields the last batch (merge dedupes on+ # the primary key) instead of skipping it.+ resumable_source_manager.save_state(DynatraceResumeConfig(next_page_key=next_page_key))+ url = _next_page_url(base_url, config, next_page_key)+++def dynatrace_source(+ environment_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DynatraceResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = DYNATRACE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ environment_url=environment_url,+ api_token=api_token,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[config.primary_key],+ # Dynatrace documents no reliable ascending sort we can verify for the time-filtered+ # endpoints (audit logs default to newest-first), so incremental endpoints run in desc+ # mode: the watermark is the max seen across the run, persisted only at successful job+ # end — correct regardless of the order rows actually arrive in.+ sort_mode="desc" if config.supports_time_filter else "asc",+ partition_count=1,+ partition_size=1,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.pynew file mode 100644index 000000000000..69e233b11130--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py@@ -0,0 +1,155 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Dynatrace timestamps (startTime, endTime, timestamp, firstSeenTms, ...) are integers in UTC+# milliseconds, not ISO datetimes, so no endpoint declares a datetime partition key — an epoch-ms+# integer isn't a safe partition key for `partition_mode="datetime"`.+++@dataclass+class DynatraceEndpointConfig:+ name: str+ path: str+ # Key in the response body holding the list of records (e.g. "problems", "events").+ data_key: str+ primary_key: str = "id"+ page_size: int = 100+ # Server-side timeframe filter: the endpoint accepts `from`/`to` params. Only endpoints where+ # the docs guarantee a genuine server-side time filter are marked incremental via this.+ supports_time_filter: bool = False+ # Row field the incremental watermark tracks (epoch-ms integer, e.g. startTime / timestamp).+ incremental_field: Optional[str] = None+ # Relative `from` value seeded on the first sync / full refresh of time-filtered endpoints,+ # since Dynatrace defaults to very narrow windows (problems/events: now-2h) when `from` is+ # omitted. Dynatrace relative format: now-NU with units m, h, d, w, M, y.+ default_from: Optional[str] = None+ # Required `entitySelector` for the entities endpoint (must specify a type on the first page).+ entity_selector: Optional[str] = None+ # Extra query params sent on the first page only — follow-up pages must carry nothing but+ # `nextPageKey` (the key encodes the original query).+ extra_params: dict[str, str] = field(default_factory=dict)++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if not self.supports_time_filter or not self.incremental_field:+ return []+ return [+ {+ "label": self.incremental_field,+ "type": IncrementalFieldType.Integer,+ "field": self.incremental_field,+ "field_type": IncrementalFieldType.Integer,+ }+ ]+++# Entity inventory tables share the entities endpoint, fanned out by type. `from` bounds the+# activity window (entities endpoint defaults to now-3d, which would drop hosts idle over a+# weekend), and `fields` adds the properties/tags the default response omits.+_ENTITY_FIELDS = "+firstSeenTms,+lastSeenTms,+properties,+tags,+managementZones"+++def _entity_endpoint(name: str, entity_type: str) -> DynatraceEndpointConfig:+ return DynatraceEndpointConfig(+ name=name,+ path="/api/v2/entities",+ data_key="entities",+ primary_key="entityId",+ page_size=100,+ entity_selector=f'type("{entity_type}")',+ default_from="now-30d",+ extra_params={"fields": _ENTITY_FIELDS},+ )+++# Endpoint catalog for the Dynatrace Environment API v2. Coverage follows the streams an+# SRE/observability team wants in a warehouse: problem history, events, audit trail,+# vulnerabilities, entity inventory, metric catalog, and SLO status.+#+# Incremental vs full refresh: only problems, events, and audit logs expose a documented+# server-side `from`/`to` timeframe filter, so only those are marked incremental. The rest are+# full refresh and dedupe on their primary key.+DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {+ "problems": DynatraceEndpointConfig(+ name="problems",+ path="/api/v2/problems",+ data_key="problems",+ primary_key="problemId",+ page_size=500,+ supports_time_filter=True,+ incremental_field="startTime",+ # Without `from` Dynatrace only returns the last 2 hours of problems.+ default_from="now-365d",+ ),+ "events": DynatraceEndpointConfig(+ name="events",+ path="/api/v2/events",+ data_key="events",+ primary_key="eventId",+ page_size=1000,+ supports_time_filter=True,+ incremental_field="startTime",+ default_from="now-30d",+ ),+ "audit_logs": DynatraceEndpointConfig(+ name="audit_logs",+ path="/api/v2/auditlogs",+ data_key="auditLogs",+ primary_key="logId",+ page_size=1000,+ supports_time_filter=True,+ incremental_field="timestamp",+ default_from="now-30d",+ ),+ "security_problems": DynatraceEndpointConfig(+ name="security_problems",+ path="/api/v2/securityProblems",+ data_key="securityProblems",+ primary_key="securityProblemId",+ page_size=100,+ ),+ "hosts": _entity_endpoint("hosts", "HOST"),+ "services": _entity_endpoint("services", "SERVICE"),+ "applications": _entity_endpoint("applications", "APPLICATION"),+ "process_groups": _entity_endpoint("process_groups", "PROCESS_GROUP"),+ "metrics": DynatraceEndpointConfig(+ name="metrics",+ path="/api/v2/metrics",+ data_key="metrics",+ primary_key="metricId",+ page_size=500,+ extra_params={"fields": "+created,+lastWritten,+entityType,+aggregationTypes,+tags"},+ ),+ "slos": DynatraceEndpointConfig(+ name="slos",+ path="/api/v2/slo",+ data_key="slo",+ primary_key="id",+ # With `evaluate=true` (needed for status / error budget) the endpoint caps pageSize at 25.+ page_size=25,+ extra_params={"evaluate": "true"},+ ),+}++ENDPOINTS = tuple(DYNATRACE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DYNATRACE_ENDPOINTS.items()+}++# Token scope each endpoint needs, surfaced in the setup caption and per-endpoint permission+# probes. Scopes are granular per API area, so users only need to grant what they sync.+ENDPOINT_SCOPES: dict[str, str] = {+ "problems": "problems.read",+ "events": "events.read",+ "audit_logs": "auditLogs.read",+ "security_problems": "securityProblems.read",+ "hosts": "entities.read",+ "services": "entities.read",+ "applications": "entities.read",+ "process_groups": "entities.read",+ "metrics": "metrics.read",+ "slos": "slo.read",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.pyindex c958a8bb52d9..9e30585df8e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py@@ -1,30 +1,177 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.dynatrace import (+ DynatraceResumeConfig,+ check_endpoint_permissions,+ dynatrace_source,+ validate_credentials as validate_dynatrace_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.settings import (+ DYNATRACE_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DynatraceSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+_SCHEMA_DESCRIPTIONS: dict[str, str] = {+ "problems": "Only syncs the last 365 days on initial sync",+ "events": "Only syncs the last 30 days on initial sync; limited by your Dynatrace event retention",+ "audit_logs": "Only syncs the last 30 days on initial sync; requires audit logging to be enabled in the environment",+ "hosts": "Hosts active in the last 30 days",+ "services": "Services active in the last 30 days",+ "applications": "Applications active in the last 30 days",+ "process_groups": "Process groups active in the last 30 days",+ "slos": "Includes the current evaluation (status, error budget) of each SLO",+}+@SourceRegistry.register-class DynatraceSource(SimpleSource[DynatraceSourceConfig]):+class DynatraceSource(ResumableSource[DynatraceSourceConfig, DynatraceResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DYNATRACE+ @property+ def connection_host_fields(self) -> list[str]:+ # `environment_url` is where the stored API token is sent; retargeting it must re-require+ # the token.+ return ["environment_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DYNATRACE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Dynatrace",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["apm", "observability", "monitoring"],+ caption="""Enter your Dynatrace environment URL and an API access token to sync problems, events, entity inventory, audit logs, vulnerabilities, metric metadata, and SLOs into the PostHog Data warehouse.++The environment URL is where you open Dynatrace — for SaaS it looks like `https://abc12345.live.dynatrace.com`; for Managed it's `https://your-domain/e/your-environment-id`.++Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-management/access-tokens-and-oauth-clients/access-tokens) in Dynatrace and grant read scopes for the data you want to sync:+- `problems.read`+- `events.read`+- `entities.read`+- `auditLogs.read`+- `securityProblems.read`+- `metrics.read`+- `slo.read`+""",iconPath="/static/services/dynatrace.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/dynatrace",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="environment_url",+ label="Environment URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://abc12345.live.dynatrace.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="dt0c01.…",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Dynatrace API token. Generate a new access token and reconnect.",+ "403 Client Error": "Your Dynatrace API token is missing the read scope required for this data. Grant the scope in Dynatrace and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: DynatraceSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=DYNATRACE_ENDPOINTS[endpoint].supports_time_filter,+ supports_append=DYNATRACE_ENDPOINTS[endpoint].supports_time_filter,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=_SCHEMA_DESCRIPTIONS.get(endpoint),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: DynatraceSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_dynatrace_credentials(config.environment_url, config.api_token, team_id, schema_name)++ def get_endpoint_permissions(+ self, config: DynatraceSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ # Dynatrace scopes are granted per API area, so per-table access varies with the token.+ # Probe each scope so the schema picker can flag tables the token can't read.+ return check_endpoint_permissions(config.environment_url, config.api_token, endpoints, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DynatraceResumeConfig]:+ return ResumableSourceManager[DynatraceResumeConfig](inputs, DynatraceResumeConfig)++ def source_for_pipeline(+ self,+ config: DynatraceSourceConfig,+ resumable_source_manager: ResumableSourceManager[DynatraceResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return dynatrace_source(+ environment_url=config.environment_url,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.pynew file mode 100644index 000000000000..e828b36e13cc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.py@@ -0,0 +1,382 @@+from datetime import UTC, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace import dynatrace as dt+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.dynatrace import (+ DynatraceHostNotAllowedError,+ DynatraceResumeConfig,+ _build_first_page_params,+ _build_url,+ _format_from_value,+ _next_page_url,+ _validated_hostname,+ check_endpoint_permissions,+ dynatrace_source,+ normalize_environment_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.settings import DYNATRACE_ENDPOINTS++BASE_URL = "https://abc12345.live.dynatrace.com"+++class TestNormalizeEnvironmentUrl:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("https://abc12345.live.dynatrace.com", "https://abc12345.live.dynatrace.com"),+ ("https://abc12345.live.dynatrace.com/", "https://abc12345.live.dynatrace.com"),+ ("abc12345.live.dynatrace.com", "https://abc12345.live.dynatrace.com"),+ (" https://abc12345.live.dynatrace.com ", "https://abc12345.live.dynatrace.com"),+ # A pasted API path must not double up when endpoint paths are appended.+ ("https://abc12345.live.dynatrace.com/api/v2", "https://abc12345.live.dynatrace.com"),+ ("https://abc12345.live.dynatrace.com/api", "https://abc12345.live.dynatrace.com"),+ # Managed environments carry a path prefix that must be preserved.+ ("https://dynatrace.example.com/e/abc-123", "https://dynatrace.example.com/e/abc-123"),+ ("https://dynatrace.example.com/e/abc-123/api/v2", "https://dynatrace.example.com/e/abc-123"),+ ],+ )+ def test_normalize(self, raw: str, expected: str) -> None:+ assert normalize_environment_url(raw) == expected+++class TestValidatedHostname:+ def test_accepts_clean_https_url(self) -> None:+ assert _validated_hostname(BASE_URL) == "abc12345.live.dynatrace.com"++ @pytest.mark.parametrize(+ "url",+ [+ "https://127.0.0.1\\@example.com", # backslash userinfo smuggling+ "https://127.0.0.1%[email protected]", # percent-encoded backslash+ "https://[email protected]", # userinfo+ "ftp://example.com", # non-http scheme+ "https://exa mple.com", # invalid hostname characters+ ],+ )+ def test_rejects_ambiguous_urls(self, url: str) -> None:+ assert _validated_hostname(url) is None++ def test_rejects_plain_http_on_cloud(self) -> None:+ with mock.patch.object(dt, "is_cloud", return_value=True):+ assert _validated_hostname("http://dynatrace.internal.example.com") is None++ def test_allows_plain_http_when_self_hosted(self) -> None:+ with mock.patch.object(dt, "is_cloud", return_value=False):+ assert _validated_hostname("http://dynatrace.internal.example.com") == "dynatrace.internal.example.com"+++class TestFormatFromValue:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (1735689600000, "1735689600000"), # epoch-ms watermark passes through+ (datetime(2025, 1, 1, tzinfo=UTC), "1735689600000"),+ (datetime(2025, 1, 1), "1735689600000"), # naive datetimes treated as UTC+ ("now-30d", "now-30d"), # relative seeds pass through+ ],+ )+ def test_format(self, value: Any, expected: str) -> None:+ assert _format_from_value(value) == expected+++class TestBuildFirstPageParams:+ def test_incremental_run_uses_watermark(self) -> None:+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["problems"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=1735689600000,+ )+ assert params["from"] == "1735689600000"+ assert params["pageSize"] == "500"++ def test_first_sync_seeds_lookback(self) -> None:+ # Without an explicit `from`, Dynatrace only returns the last 2 hours of problems.+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["problems"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert params["from"] == "now-365d"++ def test_full_refresh_ignores_watermark(self) -> None:+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["problems"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=1735689600000,+ )+ assert params["from"] == "now-365d"++ def test_entity_endpoint_sends_selector_and_fields(self) -> None:+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["hosts"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert params["entitySelector"] == 'type("HOST")'+ assert params["from"] == "now-30d"+ assert params["fields"].startswith("+firstSeenTms")++ def test_non_time_filtered_endpoint_never_sends_from(self) -> None:+ # `metrics` has no timeframe filter; a stray watermark must not leak into the request.+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["metrics"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=1735689600000,+ )+ assert "from" not in params++ def test_slos_request_evaluation(self) -> None:+ params = _build_first_page_params(+ DYNATRACE_ENDPOINTS["slos"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ # With evaluate=true the endpoint caps pageSize at 25.+ assert params["evaluate"] == "true"+ assert params["pageSize"] == "25"+++class TestNextPageUrl:+ def test_carries_only_next_page_key(self) -> None:+ # Dynatrace rejects follow-up pages that mix nextPageKey with any other query param.+ url = _next_page_url(BASE_URL, DYNATRACE_ENDPOINTS["problems"], "AQAAABQBAAAABQ==")+ parsed = urlparse(url)+ assert parsed.path == "/api/v2/problems"+ assert parse_qs(parsed.query) == {"nextPageKey": ["AQAAABQBAAAABQ=="]}++ def test_key_is_url_encoded(self) -> None:+ url = _next_page_url(BASE_URL, DYNATRACE_ENDPOINTS["problems"], "a+b/c==")+ assert "nextPageKey=a%2Bb%2Fc%3D%3D" in url+++class TestValidateCredentials:+ def _validate(self, status_code: int, schema_name: str | None = None) -> tuple[bool, str | None]:+ response = mock.MagicMock()+ response.status_code = status_code+ with mock.patch.object(dt, "make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = response+ return validate_credentials(BASE_URL, "token", team_id=None, schema_name=schema_name)++ @pytest.mark.parametrize(+ ("status_code", "schema_name", "expected_valid"),+ [+ (200, None, True),+ (401, None, False),+ # 403 at source-create means the token is genuine but lacks the probed scope —+ # users may legitimately only grant scopes for the tables they sync.+ (403, None, True),+ (403, "problems", False),+ (200, "hosts", True),+ (500, None, False),+ ],+ )+ def test_status_mapping(self, status_code: int, schema_name: str | None, expected_valid: bool) -> None:+ is_valid, error = self._validate(status_code, schema_name)+ assert is_valid is expected_valid+ if not expected_valid:+ assert error is not None++ def test_malformed_url_fails_without_network(self) -> None:+ with mock.patch.object(dt, "make_tracked_session") as mock_session:+ is_valid, error = validate_credentials("ftp://example.com", "token")+ assert is_valid is False+ assert error is not None+ mock_session.assert_not_called()++ def test_request_exception_is_caught(self) -> None:+ with mock.patch.object(dt, "make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ is_valid, error = validate_credentials(BASE_URL, "token")+ assert is_valid is False+ assert error is not None+++class TestCheckEndpointPermissions:+ def test_403_reports_missing_scope_and_shares_probe_across_entity_tables(self) -> None:+ def fake_get(url: str, timeout: Any = None) -> Any:+ response = mock.MagicMock()+ response.status_code = 403 if "entities" in url else 200+ return response++ with (+ mock.patch.object(dt, "make_tracked_session") as mock_session,+ mock.patch.object(dt, "_is_host_safe", return_value=(True, None)),+ ):+ mock_session.return_value.get.side_effect = fake_get+ results = check_endpoint_permissions(+ BASE_URL, "token", ["problems", "hosts", "services", "applications", "process_groups"], team_id=1+ )+ call_count = mock_session.return_value.get.call_count++ assert results["problems"] is None+ for endpoint in ("hosts", "services", "applications", "process_groups"):+ reason = results[endpoint]+ assert reason is not None+ assert "entities.read" in reason+ # The four entity tables share the entities.read scope, so one probe covers them all.+ assert call_count == 2++ def test_network_blip_is_not_reported_as_missing_permission(self) -> None:+ with (+ mock.patch.object(dt, "make_tracked_session") as mock_session,+ mock.patch.object(dt, "_is_host_safe", return_value=(True, None)),+ ):+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ results = check_endpoint_permissions(BASE_URL, "token", ["problems"], team_id=1)++ assert results == {"problems": None}+++class TestDynatraceSourceResponse:+ @pytest.mark.parametrize(+ ("endpoint", "expected_pk", "expected_sort_mode"),+ [+ ("problems", "problemId", "desc"),+ ("events", "eventId", "desc"),+ ("audit_logs", "logId", "desc"),+ ("security_problems", "securityProblemId", "asc"),+ ("hosts", "entityId", "asc"),+ ("metrics", "metricId", "asc"),+ ("slos", "id", "asc"),+ ],+ )+ def test_source_response_shape(self, endpoint: str, expected_pk: str, expected_sort_mode: str) -> None:+ response = dynatrace_source(+ environment_url=BASE_URL,+ api_token="token",+ endpoint=endpoint,+ team_id=1,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == [expected_pk]+ assert response.sort_mode == expected_sort_mode+++class TestGetRows:+ def _run(+ self,+ pages: list[Any],+ can_resume: bool = False,+ resume_key: str | None = None,+ endpoint: str = "problems",+ ) -> tuple[list[Any], list[str], list[str]]:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = DynatraceResumeConfig(next_page_key=resume_key) if resume_key else None+ saved: list[str] = []+ manager.save_state.side_effect = lambda state: saved.append(state.next_page_key)++ fetched_urls: list[str] = []++ def fake_get(url: str, timeout: Any = None) -> Any:+ fetched_urls.append(url)+ response = mock.MagicMock()+ response.status_code = 200+ response.ok = True+ response.json.return_value = pages[len(fetched_urls) - 1]+ return response++ with mock.patch.object(dt, "make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = fake_get+ rows = list(+ dt.get_rows(+ environment_url=BASE_URL,+ api_token="token",+ endpoint=endpoint,+ team_id=1,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )+ return rows, saved, fetched_urls++ def test_cursor_pagination_yields_and_saves_state_after_yield(self) -> None:+ pages = [+ {"problems": [{"problemId": "P-1"}], "nextPageKey": "key-2"},+ {"problems": [{"problemId": "P-2"}], "nextPageKey": None},+ ]+ rows, saved, fetched = self._run(pages)++ assert rows == [[{"problemId": "P-1"}], [{"problemId": "P-2"}]]+ assert saved == ["key-2"]+ # Follow-up request carries only the cursor — Dynatrace rejects mixed params.+ assert parse_qs(urlparse(fetched[1]).query) == {"nextPageKey": ["key-2"]}++ def test_first_page_carries_filters(self) -> None:+ pages: list[Any] = [{"problems": [], "nextPageKey": None}]+ _rows, _saved, fetched = self._run(pages)+ query = parse_qs(urlparse(fetched[0]).query)+ assert query["pageSize"] == ["500"]+ assert query["from"] == ["now-365d"]++ def test_resumes_from_saved_cursor(self) -> None:+ pages = [{"problems": [{"problemId": "P-9"}], "nextPageKey": None}]+ _rows, _saved, fetched = self._run(pages, can_resume=True, resume_key="resume-key")+ assert parse_qs(urlparse(fetched[0]).query) == {"nextPageKey": ["resume-key"]}++ def test_empty_page_with_cursor_still_advances(self) -> None:+ # A page can be empty while more pages remain; termination is the null nextPageKey,+ # not an empty batch.+ pages = [+ {"problems": [], "nextPageKey": "key-2"},+ {"problems": [{"problemId": "P-1"}], "nextPageKey": None},+ ]+ rows, _saved, fetched = self._run(pages)+ assert rows == [[{"problemId": "P-1"}]]+ assert len(fetched) == 2++ def test_redirect_is_refused(self) -> None:+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ response = mock.MagicMock()+ response.status_code = 302++ with mock.patch.object(dt, "make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = response+ with pytest.raises(DynatraceHostNotAllowedError):+ list(+ dt.get_rows(+ environment_url=BASE_URL,+ api_token="token",+ endpoint="problems",+ team_id=1,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )++ def test_unsafe_host_is_refused_before_any_request(self) -> None:+ with (+ mock.patch.object(dt, "_is_host_safe", return_value=(False, "blocked")),+ mock.patch.object(dt, "make_tracked_session") as mock_session,+ ):+ with pytest.raises(DynatraceHostNotAllowedError):+ list(+ dt.get_rows(+ environment_url=BASE_URL,+ api_token="token",+ endpoint="problems",+ team_id=1,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ )+ )+ mock_session.assert_not_called()+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url(BASE_URL, "/api/v2/metrics", {}) == f"{BASE_URL}/api/v2/metrics"++ def test_managed_path_prefix_is_preserved(self) -> None:+ url = _build_url("https://dynatrace.example.com/e/abc-123", "/api/v2/problems", {"pageSize": "500"})+ assert url == "https://dynatrace.example.com/e/abc-123/api/v2/problems?pageSize=500"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.pynew file mode 100644index 000000000000..8be15dc44433--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.py@@ -0,0 +1,156 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.dynatrace import DynatraceResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.source import DynatraceSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DynatraceSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"problems", "events", "audit_logs"}+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "problems",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestDynatraceSource:+ def setup_method(self) -> None:+ self.source = DynatraceSource()+ self.team_id = 123+ self.config = DynatraceSourceConfig(+ environment_url="https://abc12345.live.dynatrace.com", api_token="dt0c01.token"+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DYNATRACE++ def test_environment_url_is_a_connection_host_field(self) -> None:+ # Changing the environment URL must force the token to be re-entered so it's never+ # sent to a freshly-specified host.+ assert self.source.connection_host_fields == ["environment_url"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Dynatrace"+ assert config.label == "Dynatrace"+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ url_field, token_field = config.fields++ assert isinstance(url_field, SourceFieldInputConfig)+ assert url_field.name == "environment_url"+ assert url_field.type == SourceFieldInputConfigType.TEXT+ assert url_field.required is True+ assert url_field.secret is False++ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.name == "api_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_flags(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ for name in INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert len(schemas[name].incremental_fields) == 1+ assert schemas[name].incremental_fields[0]["field_type"] == "integer"++ for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["problems", "nonexistent"])+ assert [s.name for s in schemas] == ["problems"]++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid"),+ [+ ((True, None), True),+ ((False, "Invalid Dynatrace API token."), False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.source.validate_dynatrace_credentials"+ )+ def test_validate_credentials(+ self, mock_validate: mock.MagicMock, mock_return: tuple[bool, str | None], expected_valid: bool+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name="problems")++ assert is_valid is expected_valid+ assert error_message == mock_return[1]+ mock_validate.assert_called_once_with(+ "https://abc12345.live.dynatrace.com", "dt0c01.token", self.team_id, "problems"+ )++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DynatraceResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.source.dynatrace_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="metrics", team_id=99)+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ environment_url="https://abc12345.live.dynatrace.com",+ api_token="dt0c01.token",+ endpoint="metrics",+ team_id=99,+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.source.dynatrace_source")+ def test_source_for_pipeline_gates_incremental_value(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark must not leak into a full-refresh run.+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value=1735689600000)+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mock_source.call_args.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 dedbd076ac0f..04625240c991 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@@ -1360,7 +1360,8 @@ class DynamoDBSourceConfig(config.Config):@config.configclass DynatraceSourceConfig(config.Config):- pass+ environment_url: str+ api_token: str@config.config