Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement instana import source (#71181)

Tom Owersd6abee1ccc90
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 8ea04b80d634..d6be39a739ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -245,6 +245,7 @@ the row lists both.
| inflowinventory | HTTP | requests | ✅ |
| inngest | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
+| instana | HTTP | requests | ✅ |
| instatus | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| intruder | HTTP | requests | ✅ |
@@ -710,7 +711,6 @@ doesn't conflict with concurrent PRs.
- infor_nexus
- insightful
- instagram
-- instana
- instantly
- interzoid
- jamf_pro
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 4cc0d3106dc5..74fd561fd04e 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
@@ -2091,7 +2091,8 @@ class InstagramSourceConfig(config.Config):
@config.config
class InstanaSourceConfig(config.Config):
- pass
+ base_url: str
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py
new file mode 100644
index 000000000000..8955f4aa34e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py
@@ -0,0 +1,116 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Instana OpenAPI specification
+# (https://instana.github.io/openapi/). Keyed by endpoint name as returned by `get_schemas`.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "Incidents, issues, and changes detected by Instana across your monitored environment.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getEvents",
+ "columns": {
+ "eventId": "Unique identifier of the event.",
+ "start": "Timestamp when the event started, in epoch milliseconds.",
+ "end": "Timestamp when the event ended, in epoch milliseconds; unset while the event is still open.",
+ "type": "Event type: INCIDENT, ISSUE, or CHANGE.",
+ "state": "Current state of the event (e.g. OPEN or CLOSED).",
+ "severity": "Numeric severity of the event (5 = warning, 10 = critical).",
+ "problem": "Short description of the detected problem.",
+ "detail": "Detailed description of the event.",
+ "entityName": "Type of the entity the event was detected on (e.g. host, jvm).",
+ "entityLabel": "Display label of the entity the event was detected on.",
+ "entityType": "Category of the affected entity.",
+ "snapshotId": "Identifier of the infrastructure snapshot the event relates to.",
+ "eventSpecificationId": "Identifier of the event specification (rule) that triggered the event.",
+ "fixSuggestion": "Suggested remediation for the detected problem.",
+ },
+ },
+ "applications": {
+ "description": "Application perspectives defined in Instana's application monitoring.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getApplications",
+ "columns": {
+ "id": "Unique identifier of the application perspective.",
+ "label": "Display name of the application perspective.",
+ "boundaryScope": "Which calls are part of the application: INBOUND or ALL.",
+ "entityType": "Entity type of the record (application).",
+ },
+ },
+ "services": {
+ "description": "Services discovered by Instana's application monitoring.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getServices",
+ "columns": {
+ "id": "Unique identifier of the service.",
+ "label": "Display name of the service.",
+ "types": "Service types (e.g. HTTP, DATABASE, MESSAGING).",
+ "technologies": "Technologies detected for the service.",
+ "snapshotIds": "Infrastructure snapshot identifiers backing the service.",
+ "entityType": "Entity type of the record (service).",
+ },
+ },
+ "endpoints": {
+ "description": "Service endpoints (HTTP paths, RPC methods, queues) discovered by Instana.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getApplicationEndpoints",
+ "columns": {
+ "id": "Unique identifier of the endpoint.",
+ "label": "Display name of the endpoint.",
+ "serviceId": "Identifier of the service the endpoint belongs to.",
+ "type": "Endpoint type (e.g. HTTP, DATABASE, MESSAGING).",
+ "technologies": "Technologies detected for the endpoint.",
+ "synthetic": "Whether the endpoint only receives synthetic traffic.",
+ },
+ },
+ "websites": {
+ "description": "Websites configured for Instana end-user (website) monitoring.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getWebsites",
+ "columns": {
+ "id": "Unique identifier of the website configuration.",
+ "name": "Name of the monitored website.",
+ "appName": "Application name associated with the website.",
+ },
+ },
+ "synthetic_tests": {
+ "description": "Synthetic monitoring tests configured in Instana.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSyntheticTests",
+ "columns": {
+ "id": "Unique identifier of the synthetic test.",
+ "label": "Display name of the synthetic test.",
+ "active": "Whether the test is currently active.",
+ "testFrequency": "How often the test runs, in minutes.",
+ "locations": "Identifiers of the locations the test runs from.",
+ "createdAt": "Timestamp when the test was created, in epoch milliseconds.",
+ "modifiedAt": "Timestamp when the test was last modified, in epoch milliseconds.",
+ },
+ },
+ "alerting_channels": {
+ "description": "Alert channels (integrations) configured in Instana's alerting settings.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getAlertingChannels",
+ "columns": {
+ "id": "Unique identifier of the alert channel.",
+ "name": "Display name of the alert channel.",
+ "kind": "Channel type (e.g. EMAIL, SLACK, WEB_HOOK, OPS_GENIE).",
+ },
+ },
+ "alert_configs": {
+ "description": "Alerting configurations that route triggered events to alert channels.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getAlerts",
+ "columns": {
+ "id": "Unique identifier of the alerting configuration.",
+ "alertName": "Display name of the alerting configuration.",
+ "integrationIds": "Identifiers of the alert channels this configuration notifies.",
+ "eventFilteringConfiguration": "Rules selecting which events trigger this alert.",
+ "muteUntil": "Timestamp the alert is muted until, in epoch milliseconds.",
+ "lastUpdated": "Timestamp of the last modification, in epoch milliseconds.",
+ },
+ },
+ "infrastructure_snapshots": {
+ "description": "Snapshot summaries of infrastructure entities currently monitored by Instana agents.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSnapshots",
+ "columns": {
+ "snapshotId": "Unique identifier of the infrastructure snapshot.",
+ "plugin": "Entity type (plugin) that produced the snapshot (e.g. host, jvmRuntimePlatform).",
+ "label": "Display label of the monitored entity.",
+ "host": "Identifier of the host the entity runs on.",
+ "tags": "Tags attached to the monitored entity.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py
new file mode 100644
index 000000000000..6882c0c0a1be
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py
@@ -0,0 +1,430 @@
+import json
+import time
+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 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.instana.settings import (
+ EVENTS_DEFAULT_LOOKBACK_DAYS,
+ EVENTS_WINDOW_CHUNK_MS,
+ INSTANA_ENDPOINTS,
+ MAX_CATALOG_PAGES,
+ MAX_CATALOG_WALK_SECONDS,
+ PAGE_SIZE,
+ SNAPSHOTS_MAX_SIZE,
+ InstanaEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+# The base URL is customer-controlled, so a body must never be buffered unbounded: requests reads
+# the whole response into memory by default, and the read timeout only guards idle gaps between
+# reads, not a steady large (or gzip-expanded) transfer. Cap what we read into memory — generous
+# for any real Instana page, anything past it is refused.
+MAX_RESPONSE_BYTES = 256 * 1024 * 1024
+RESPONSE_CHUNK_BYTES = 256 * 1024
+# Error bodies are customer-controlled and can be as large as the response cap, so never
+# interpolate the whole thing into a log event — log a small decoded preview plus the byte length.
+ERROR_BODY_LOG_PREVIEW_BYTES = 8 * 1024
+# Wall-clock budget for downloading one response body. The per-read timeout can't stop a host that
+# dribbles the body slowly enough to stay under it while holding a shared worker open. 256 MiB in
+# 300s is a ~0.85 MiB/s floor — far below any real API response, far above a slow-drip stall.
+MAX_DOWNLOAD_SECONDS = 300
+
+HOST_NOT_ALLOWED_ERROR = "Instana base URL is not allowed"
+RESPONSE_TOO_LARGE_ERROR = "Instana response body was too large"
+RESPONSE_TOO_SLOW_ERROR = "Instana response download was too slow"
+PAGINATION_LIMIT_ERROR = "Instana catalog pagination exceeded the page limit"
+
+
+class InstanaRetryableError(Exception):
+ pass
+
+
+class InstanaHostNotAllowedError(Exception):
+ pass
+
+
+class InstanaResponseTooLargeError(Exception):
+ pass
+
+
+class InstanaResponseTooSlowError(Exception):
+ pass
+
+
+class InstanaPaginationLimitError(Exception):
+ pass
+
+
+def _read_capped_body(response: requests.Response) -> bytes:
+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.
+
+ The host is customer-controlled, so a body must never be buffered unbounded (size cap) nor be
+ allowed to hold the connection open indefinitely by dribbling under the per-read timeout (time
+ cap). Both are non-retryable: re-fetching the same request yields the same oversized/slow body.
+ """
+ chunks: list[bytes] = []
+ total = 0
+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS
+ try:
+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):
+ if time.monotonic() > deadline:
+ raise InstanaResponseTooSlowError(
+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"
+ )
+ if not chunk:
+ continue
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise InstanaResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes")
+ chunks.append(chunk)
+ finally:
+ response.close()
+ return b"".join(chunks)
+
+
+class InstanaResumeConfig:
+ # Next page to fetch for the page-paginated application-monitoring catalogs.
+ next_page: int | None = None
+ # Epoch-ms start of the next `/api/events` window chunk.
+ events_window_from: int | None = None
+
+
+def normalize_base_url(url: str) -> str:
+ """Reduce user input to a validated ``https://<host>`` Instana base URL.
+
+ Accepts a SaaS tenant URL (``https://unit-tenant.instana.io``) or a self-hosted domain, with
+ or without a scheme. Forcing https prevents a plaintext downgrade, and dropping any
+ path/query/credentials means the API token is only ever sent to endpoint paths we build.
+ """
+ cleaned = url.strip()
+ if not cleaned:
+ raise ValueError("Instana base URL is required")
+ if "://" not in cleaned:
+ cleaned = f"https://{cleaned}"
+ parsed = urlparse(cleaned)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
+ raise ValueError(f"Invalid Instana base URL: {url!r}. Enter it like 'https://unit-tenant.instana.io'.")
+ port = f":{parsed.port}" if parsed.port else ""
+ return f"https://{parsed.hostname}{port}"
+
+
+def _host_from_url(base_url: str) -> str:
+ return (urlparse(normalize_base_url(base_url)).hostname or "").lower()
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {"Authorization": f"apiToken {api_token}", "Accept": "application/json"}
+
+
+def _to_epoch_ms(value: Any) -> int | None:
+ """Coerce an incremental cursor to epoch milliseconds (Instana's native timestamp unit)."""
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ return None
+ return None
+
+
+def _build_url(root: str, path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{root}{path}"
+ return f"{root}{path}?{urlencode(params)}"
+
+
+def _check_host(base_url: str, team_id: int) -> None:
+ # The base URL is fully customer-controlled (self-hosted Instana is a supported target), so
+ # block hosts that resolve to private/internal addresses (SSRF). Re-checked at run time, not
+ # just source-create, to cover URL edits and DNS rebinding. Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)
+ if not host_ok:
+ raise InstanaHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+
+def validate_credentials(base_url: str, api_token: str, team_id: int | None = None) -> tuple[bool, int | None]:
+ """Probe ``/api/instana/version`` — the cheapest authenticated endpoint — to confirm the token.
+
+ Returns ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error. Raises
+ ``ValueError`` on a malformed base URL and ``InstanaHostNotAllowedError`` on a blocked host so
+ the caller can surface precise messages.
+ """
+ root = normalize_base_url(base_url)
+ if team_id is not None:
+ _check_host(base_url, team_id)
+ url = _build_url(root, "/api/instana/version", {})
+ try:
+ # stream=True so a customer-controlled host can't force us to buffer an unbounded probe
+ # body; we only need the status, so read nothing and close immediately.
+ response = make_tracked_session(allow_redirects=False, redact_values=(api_token,)).get(
+ url, headers=_headers(api_token), timeout=10, stream=True
+ )
+ except requests.exceptions.RequestException:
+ return False, None
+ try:
+ return response.status_code == 200, response.status_code
+ finally:
+ response.close()
+
+
+def _fetch(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> Any:
+ @retry(
+ retry=retry_if_exception_type((InstanaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_once() -> Any:
+ # stream=True so the body isn't buffered until we cap it — see _read_capped_body.
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
+
+ # Instana rate-limits to 5000 calls/hour and answers excess with 429; transient 5xx are
+ # retryable too. Back off and retry rather than failing the sync.
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ raise InstanaRetryableError(f"Instana API error (retryable): status={response.status_code}, url={url}")
+
+ body = _read_capped_body(response)
+
+ if not response.ok:
+ preview = body[:ERROR_BODY_LOG_PREVIEW_BYTES].decode(errors="replace")
+ logger.error(
+ f"Instana API error: status={response.status_code}, body_bytes={len(body)}, "
+ f"body_preview={preview}, url={url}"
+ )
+ response.raise_for_status()
+
+ return json.loads(body or b"null")
+
+ return fetch_once()
+
+
+def _extract_items(response_json: Any, config: InstanaEndpointConfig) -> list[dict[str, Any]]:
+ if config.data_path is None:
+ return response_json if isinstance(response_json, list) else []
+ if isinstance(response_json, dict):
+ items = response_json.get(config.data_path, [])
+ return items if isinstance(items, list) else []
+ return []
+
+
+def _get_event_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Chunk `/api/events` into ascending from/to windows and yield each chunk's events.
+
+ The endpoint has no pagination — the window bounds the response — so wide ranges are walked in
+ fixed chunks. Chunk boundaries are inclusive on both requests, and an incremental run restarts
+ exactly at the watermark, so boundary events are re-fetched and merge dedupes them on
+ `eventId`. Ongoing events that started before the window are returned in every chunk they are
+ active in; the merge refreshes their mutable `state`/`end` fields.
+ """
+ now_ms = int(datetime.now(UTC).timestamp() * 1000)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ watermark = _to_epoch_ms(db_incremental_field_last_value) if should_use_incremental_field else None
+ if resume is not None and resume.events_window_from is not None:
+ window_from = resume.events_window_from
+ logger.debug(f"Instana: resuming events from window_from={window_from}")
+ elif watermark is not None:
+ # A future-dated watermark (bad clock upstream) would build an empty forward window every
+ # run; clamping to now keeps the sync self-healing.
+ window_from = min(watermark, now_ms)
+ else:
+ window_from = now_ms - EVENTS_DEFAULT_LOOKBACK_DAYS * 24 * 60 * 60 * 1000
+
+ while window_from < now_ms:
+ window_to = min(window_from + EVENTS_WINDOW_CHUNK_MS, now_ms)
+ url = _build_url(root, config.path, {"from": window_from, "to": window_to})
+ items = _extract_items(_fetch(session, url, logger), config)
+
+ if items:
+ yield items
+
+ if window_to >= now_ms:
+ break
+ # Save AFTER yielding, and only while more windows remain, so a crash re-fetches the last
+ # chunk rather than skipping it — merge dedupes on the primary key.
+ resumable_source_manager.save_state(InstanaResumeConfig(events_window_from=window_to))
+ window_from = window_to
+
+
+def _get_paged_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a page/pageSize-paginated application-monitoring catalog.
+
+ The OpenAPI spec doesn't document the first page index, so the first request omits `page` and
+ the server's default page is read back from the response body (ApplicationResult et al. echo
+ `page`), making the walk correct for either indexing base.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume is not None else None
+ if page is not None:
+ logger.debug(f"Instana: resuming {config.name} from page={page}")
+
+ fetched = 0
+ pages_walked = 0
+ walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
+ while True:
+ # A self-hosted host can return a full page forever while omitting `totalHits`, so the
+ # termination conditions below never trip; bound the walk so the loop (and its ingestion)
+ # can't run for the whole activity. Both bounds are non-retryable — the same host replays
+ # the same loop. The wall-clock budget is the effective bound: a slow host can stay under
+ # the page cap while streaming each page for MAX_DOWNLOAD_SECONDS, so pages alone wouldn't
+ # cap worker time.
+ if time.monotonic() > walk_deadline:
+ raise InstanaPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: exceeded {MAX_CATALOG_WALK_SECONDS}s walk budget for {config.name}"
+ )
+ if pages_walked >= MAX_CATALOG_PAGES:
+ raise InstanaPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: stopped after {MAX_CATALOG_PAGES} pages for {config.name}"
+ )
+ params: dict[str, Any] = {"pageSize": PAGE_SIZE}
+ if page is not None:
+ params["page"] = page
+ url = _build_url(root, config.path, params)
+ data = _fetch(session, url, logger)
+ pages_walked += 1
+
+ items = _extract_items(data, config)
+ if not items:
+ break
+
+ yield items
+ fetched += len(items)
+
+ current_page = data.get("page") if isinstance(data, dict) else None
+ total_hits = data.get("totalHits") if isinstance(data, dict) else None
+ if len(items) < PAGE_SIZE:
+ break
+ if isinstance(total_hits, int) and fetched >= total_hits:
+ break
+
+ next_page = (current_page if isinstance(current_page, int) else page or 1) + 1
+ resumable_source_manager.save_state(InstanaResumeConfig(next_page=next_page))
+ page = next_page
+
+
+def _get_list_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fetch a single-shot list endpoint (websites, alerting settings, snapshots)."""
+ url = _build_url(root, config.path, dict(config.extra_params))
+ items = _extract_items(_fetch(session, url, logger), config)
+ if config.name == "infrastructure_snapshots" and len(items) >= SNAPSHOTS_MAX_SIZE:
+ logger.warning(
+ f"Instana: infrastructure_snapshots returned {len(items)} items, hitting the size cap "
+ f"({SNAPSHOTS_MAX_SIZE}) — the inventory may be truncated"
+ )
+ if items:
+ yield items
+
+
+def get_rows(
+ base_url: str,
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INSTANA_ENDPOINTS[endpoint]
+ root = normalize_base_url(base_url)
+ _check_host(base_url, team_id)
+
+ # One tracked session reused across every request; the token is redacted from logged URLs and
+ # captured samples, and redirects are never followed (SSRF boundary for user-supplied hosts).
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,), allow_redirects=False)
+
+ if config.is_events:
+ yield from _get_event_rows(
+ session,
+ root,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.pagination == "page":
+ yield from _get_paged_rows(session, root, config, logger, resumable_source_manager)
+ else:
+ yield from _get_list_rows(session, root, config, logger)
+
+
+def instana_source(
+ base_url: str,
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = INSTANA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ base_url=base_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],
+ # Event windows ascend, so batches arrive in (chunk-level) ascending `start` order; the
+ # catalog endpoints are full refresh where the watermark is unused.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ # Instana timestamps are epoch-ms integers rather than ISO datetimes, so there is no safe
+ # datetime partition key — tables are left unpartitioned.
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py
new file mode 100644
index 000000000000..d7931459cad7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py
@@ -0,0 +1,132 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Instana's paginated application-monitoring catalogs accept a `pageSize` param; their analyze
+# endpoints cap page sizes at 200, so stay at that known-safe value here too.
+PAGE_SIZE = 200
+
+# A self-hosted server the user controls can return a full page on every request while never
+# signalling the end of pagination, keeping the catalog walk (and its ingestion) running for the
+# whole activity. Two independent bounds stop the walk and fail non-retryably:
+#
+# - A cumulative wall-clock budget is the effective bound. A page count alone doesn't cap worker
+# time — each page may stream for MAX_DOWNLOAD_SECONDS, so a slow host could stay under a page
+# cap yet hold the worker for days. 30 minutes is far longer than any real catalog walk (which
+# is minutes) but far below the import activity timeout, so a slow-drip host is evicted quickly.
+# - A page ceiling is a secondary record/memory bound (10k pages x 200 = 2M records), far above
+# any real catalog, so a legitimate inventory is never truncated.
+MAX_CATALOG_WALK_SECONDS = 30 * 60
+MAX_CATALOG_PAGES = 10_000
+
+# `/api/events` has no pagination — the window itself bounds the response — so wide ranges must be
+# chunked. One-day chunks keep responses small while the first sync stays at ~30 requests.
+EVENTS_WINDOW_CHUNK_MS = 24 * 60 * 60 * 1000
+
+# First sync / full refresh reaches back this far. Instana retains events for a limited window
+# (typically ~31 days), so asking for more returns nothing extra.
+EVENTS_DEFAULT_LOOKBACK_DAYS = 30
+
+# `/api/infrastructure-monitoring/snapshots` has a `size` cap instead of pagination. The window
+# only needs to cover entities currently reporting, so keep it short.
+SNAPSHOTS_WINDOW_MS = 60 * 60 * 1000
+SNAPSHOTS_MAX_SIZE = 1000
+
+PaginationStyle = Literal["page", "none"]
+
+
+@dataclass
+class InstanaEndpointConfig:
+ name: str
+ path: str
+ # Key in the response body holding the list of records. ``None`` means the body itself is the list.
+ data_path: Optional[str] = None
+ primary_key: str = "id"
+ pagination: PaginationStyle = "none"
+ # Only `events` filters server-side (from/to epoch-ms window on the event `start`); everything
+ # else is a config/topology catalog with no updated-since cursor, so it ships full refresh.
+ is_events: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Extra query params sent on every request.
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+ @property
+ def supports_incremental(self) -> bool:
+ return self.is_events
+
+
+def _start_incremental_fields() -> list[IncrementalField]:
+ # Instana timestamps are epoch milliseconds (int64), not ISO datetimes.
+ return [
+ {
+ "label": "start",
+ "type": IncrementalFieldType.Integer,
+ "field": "start",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ]
+
+
+# Endpoint catalog, verified against the official OpenAPI spec
+# (https://instana.github.io/openapi/openapi.yaml). Instana has no Airbyte/Fivetran connector to
+# mirror, so coverage follows what the UI surfaces: events, the application-monitoring catalogs
+# (applications/services/endpoints), website + synthetic monitoring configs, alerting settings,
+# and the infrastructure snapshot inventory. Metric time-series and trace analytics endpoints are
+# POST-with-body cursor APIs and are intentionally out of scope for the first release.
+INSTANA_ENDPOINTS: dict[str, InstanaEndpointConfig] = {
+ "events": InstanaEndpointConfig(
+ name="events",
+ path="/api/events",
+ primary_key="eventId",
+ is_events=True,
+ incremental_fields=_start_incremental_fields(),
+ ),
+ "applications": InstanaEndpointConfig(
+ name="applications",
+ path="/api/application-monitoring/applications",
+ data_path="items",
+ pagination="page",
+ ),
+ "services": InstanaEndpointConfig(
+ name="services",
+ path="/api/application-monitoring/services",
+ data_path="items",
+ pagination="page",
+ ),
+ "endpoints": InstanaEndpointConfig(
+ name="endpoints",
+ path="/api/application-monitoring/applications/services/endpoints",
+ data_path="items",
+ pagination="page",
+ ),
+ "websites": InstanaEndpointConfig(
+ name="websites",
+ path="/api/website-monitoring/config",
+ ),
+ "synthetic_tests": InstanaEndpointConfig(
+ name="synthetic_tests",
+ path="/api/synthetics/settings/tests",
+ ),
+ "alerting_channels": InstanaEndpointConfig(
+ name="alerting_channels",
+ path="/api/events/settings/alertingChannels",
+ ),
+ "alert_configs": InstanaEndpointConfig(
+ name="alert_configs",
+ path="/api/events/settings/alerts",
+ ),
+ "infrastructure_snapshots": InstanaEndpointConfig(
+ name="infrastructure_snapshots",
+ path="/api/infrastructure-monitoring/snapshots",
+ data_path="items",
+ primary_key="snapshotId",
+ extra_params={"windowSize": str(SNAPSHOTS_WINDOW_MS), "size": str(SNAPSHOTS_MAX_SIZE)},
+ ),
+}
+
+ENDPOINTS = tuple(INSTANA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in INSTANA_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
index 3d2aa8fc123c..4b88aa2d8c71 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
@@ -1,30 +1,180 @@
-from typing import cast
+from typing import Optional, cast
from 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.generated_configs import InstanaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.instana import (
+ PAGINATION_LIMIT_ERROR,
+ RESPONSE_TOO_LARGE_ERROR,
+ RESPONSE_TOO_SLOW_ERROR,
+ InstanaHostNotAllowedError,
+ InstanaResumeConfig,
+ instana_source,
+ validate_credentials as validate_instana_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.settings import (
+ ENDPOINTS,
+ EVENTS_DEFAULT_LOOKBACK_DAYS,
+ INCREMENTAL_FIELDS,
+ INSTANA_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class InstanaSource(SimpleSource[InstanaSourceConfig]):
+class InstanaSource(ResumableSource[InstanaSourceConfig, InstanaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INSTANA
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API token is sent to whatever host `base_url` points at, so retargeting it must
+ # re-require the token (prevents credential exfiltration to another host).
+ return ["base_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.INSTANA,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="IBM Instana Observability",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["ibm", "apm", "observability", "monitoring"],
+ caption="""Enter your Instana tenant URL and API token to pull your Instana data into the PostHog Data warehouse.
+
+Your base URL is the address you use to open the Instana UI, e.g. `https://unit-tenant.instana.io` (or your self-hosted domain). Create an API token under **Settings → Team Settings → API Tokens**; the token's permission scopes control which tables can be synced.""",
iconPath="/static/services/instana.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/instana",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Base URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://unit-tenant.instana.io",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.instana.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch` calls `raise_for_status()`.
+ # Retrying can never fix a credential/permission problem, so fail the sync. The host is
+ # per-tenant, so match only the stable status text.
+ "401 Client Error: Unauthorized": "Your Instana API token is invalid or has been revoked. Create a new API token under Settings → Team Settings → API Tokens, then reconnect.",
+ "403 Client Error: Forbidden": "Your Instana API token is missing the permission scopes needed to sync this data. Grant the required scopes on the token, then reconnect.",
+ RESPONSE_TOO_LARGE_ERROR: "Instana returned a response that was too large to process. Please contact support if this persists.",
+ RESPONSE_TOO_SLOW_ERROR: "Instana took too long to send a response. Check that the base URL points at a healthy Instana instance, then reconnect.",
+ PAGINATION_LIMIT_ERROR: "Instana returned an unexpectedly large catalog that exceeded the pagination limit. Please contact support if this persists.",
+ }
+
+ def get_schemas(
+ self,
+ config: InstanaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = INSTANA_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ # Events mutate after creation (`state` and `end` change while an issue is open),
+ # so append mode would materialize each update as a duplicate row — merge only.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=(
+ f"Only syncs the last {EVENTS_DEFAULT_LOOKBACK_DAYS} days on initial sync"
+ if endpoint == "events"
+ else None
+ ),
+ )
+
+ schemas = [_build_schema(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: InstanaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ ok, status_code = validate_instana_credentials(config.base_url, config.api_token, team_id)
+ except (ValueError, InstanaHostNotAllowedError) as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Instana API token"
+ # A 403 means the token is genuine but lacks the probed endpoint's scope — users may
+ # legitimately only grant scopes for the tables they want to sync, so accept it at
+ # source-create. Sync-time 403s are handled by `get_non_retryable_errors`.
+ if status_code == 403:
+ return True, None
+ return False, "Could not connect to Instana with the provided base URL and API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InstanaResumeConfig]:
+ return ResumableSourceManager[InstanaResumeConfig](inputs, InstanaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: InstanaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return instana_source(
+ base_url=config.base_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/instana/tests/test_instana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
new file mode 100644
index 000000000000..6b1315d05083
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
@@ -0,0 +1,394 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana import instana as inst
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.instana import (
+ InstanaResumeConfig,
+ _to_epoch_ms,
+ instana_source,
+ normalize_base_url,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.settings import (
+ EVENTS_DEFAULT_LOOKBACK_DAYS,
+ EVENTS_WINDOW_CHUNK_MS,
+ PAGE_SIZE,
+)
+
+BASE_URL = "https://unit-tenant.instana.io"
+
+
+def _patch_host_safe():
+ return mock.patch.object(inst, "_is_host_safe", return_value=(True, None))
+
+
+def _make_response(status_code: int, payload: Any = None, ok: bool | None = None) -> Any:
+ """Build a streaming-response mock: `_read_capped_body` reads it via `iter_content`."""
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = ok if ok is not None else status_code < 400
+ body = b"" if payload is None else json.dumps(payload).encode()
+ resp.iter_content.return_value = iter([body]) if body else iter([])
+ resp.text = body.decode()
+ return resp
+
+
+class TestNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("https://unit-tenant.instana.io", "https://unit-tenant.instana.io"),
+ ("unit-tenant.instana.io", "https://unit-tenant.instana.io"),
+ (" https://unit-tenant.instana.io/ ", "https://unit-tenant.instana.io"),
+ # http is upgraded so the token never travels in plaintext.
+ ("http://selfhosted.example.com", "https://selfhosted.example.com"),
+ # Paths/queries are dropped so endpoint paths always join against the bare host.
+ ("https://unit-tenant.instana.io/some/path?q=1", "https://unit-tenant.instana.io"),
+ ("https://selfhosted.example.com:8443", "https://selfhosted.example.com:8443"),
+ ],
+ )
+ def test_normalizes(self, raw: str, expected: str) -> None:
+ assert normalize_base_url(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "",
+ " ",
+ "https://",
+ "ftp://unit-tenant.instana.io",
+ # Embedded credentials could smuggle the request elsewhere.
+ "https://user:[email protected]",
+ ],
+ )
+ def test_rejects_invalid(self, raw: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_base_url(raw)
+
+
+class TestToEpochMs:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (1767225600000, 1767225600000),
+ (1767225600000.0, 1767225600000),
+ ("1767225600000", 1767225600000),
+ (datetime(2026, 1, 1, tzinfo=UTC), 1767225600000),
+ (datetime(2026, 1, 1), 1767225600000), # naive treated as UTC
+ (date(2026, 1, 1), 1767225600000),
+ ("not-a-number", None),
+ (None, None),
+ (True, None),
+ ],
+ )
+ def test_coercion(self, value: Any, expected: int | None) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+def _run_get_rows(
+ endpoint: str,
+ pages: list[Any],
+ can_resume: bool = False,
+ resume_state: InstanaResumeConfig | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> tuple[list[Any], list[InstanaResumeConfig], list[str]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = resume_state
+ saved: list[InstanaResumeConfig] = []
+ manager.save_state.side_effect = saved.append
+
+ fetched_urls: list[str] = []
+
+ def fake_get(url: str, timeout: Any = None, stream: bool = False) -> Any:
+ fetched_urls.append(url)
+ payload = pages[min(len(fetched_urls), len(pages)) - 1]
+ return _make_response(200, payload)
+
+ with _patch_host_safe(), mock.patch.object(inst, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ rows = list(
+ inst.get_rows(
+ base_url=BASE_URL,
+ api_token="token",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+ return rows, saved, fetched_urls
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+@freeze_time("2026-01-10T00:00:00Z")
+class TestEventRows:
+ NOW_MS = 1768003200000
+
+ def test_incremental_run_chunks_from_watermark(self) -> None:
+ watermark = self.NOW_MS - int(1.5 * EVENTS_WINDOW_CHUNK_MS)
+ pages = [[{"eventId": "a", "start": watermark + 1}]]
+ rows, saved, fetched = _run_get_rows(
+ "events",
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert len(fetched) == 2
+ first, second = _query(fetched[0]), _query(fetched[1])
+ assert first["from"] == [str(watermark)]
+ assert first["to"] == [str(watermark + EVENTS_WINDOW_CHUNK_MS)]
+ assert second["from"] == [str(watermark + EVENTS_WINDOW_CHUNK_MS)]
+ assert second["to"] == [str(self.NOW_MS)]
+ # Both chunks yielded rows.
+ assert len(rows) == 2
+ # State saved only between chunks (after the yield), never after the final chunk.
+ assert [s.events_window_from for s in saved] == [watermark + EVENTS_WINDOW_CHUNK_MS]
+
+ def test_first_sync_reaches_back_the_default_lookback(self) -> None:
+ rows, _saved, fetched = _run_get_rows("events", [[]])
+
+ expected_from = self.NOW_MS - EVENTS_DEFAULT_LOOKBACK_DAYS * 24 * 60 * 60 * 1000
+ assert _query(fetched[0])["from"] == [str(expected_from)]
+ assert _query(fetched[-1])["to"] == [str(self.NOW_MS)]
+ assert len(fetched) == EVENTS_DEFAULT_LOOKBACK_DAYS
+ # Empty windows keep advancing without yielding.
+ assert rows == []
+
+ def test_resume_starts_at_saved_window(self) -> None:
+ resume_from = self.NOW_MS - EVENTS_WINDOW_CHUNK_MS // 2
+ _rows, _saved, fetched = _run_get_rows(
+ "events",
+ [[]],
+ can_resume=True,
+ resume_state=InstanaResumeConfig(events_window_from=resume_from),
+ )
+
+ assert len(fetched) == 1
+ assert _query(fetched[0])["from"] == [str(resume_from)]
+
+ def test_future_watermark_is_clamped_and_makes_no_requests(self) -> None:
+ rows, saved, fetched = _run_get_rows(
+ "events",
+ [[]],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=self.NOW_MS + 10_000,
+ )
+
+ assert fetched == []
+ assert rows == []
+ assert saved == []
+
+
+class TestPagedRows:
+ def _page(self, count: int, page: int, total_hits: int) -> dict[str, Any]:
+ return {"items": [{"id": f"p{page}-{i}"} for i in range(count)], "page": page, "totalHits": total_hits}
+
+ def test_first_request_omits_page_and_follows_server_page_number(self) -> None:
+ pages = [
+ self._page(PAGE_SIZE, page=1, total_hits=PAGE_SIZE + 1),
+ self._page(1, page=2, total_hits=PAGE_SIZE + 1),
+ ]
+ rows, saved, fetched = _run_get_rows("applications", pages)
+
+ assert "page" not in _query(fetched[0])
+ assert _query(fetched[0])["pageSize"] == [str(PAGE_SIZE)]
+ assert _query(fetched[1])["page"] == ["2"]
+ assert [s.next_page for s in saved] == [2]
+ assert len(rows) == 2
+
+ def test_zero_indexed_server_does_not_skip_a_page(self) -> None:
+ # The spec doesn't document the first page index; the walk must follow the index base the
+ # server reports back rather than assuming 1-based.
+ pages = [
+ self._page(PAGE_SIZE, page=0, total_hits=PAGE_SIZE + 1),
+ self._page(1, page=1, total_hits=PAGE_SIZE + 1),
+ ]
+ _rows, _saved, fetched = _run_get_rows("applications", pages)
+
+ assert _query(fetched[1])["page"] == ["1"]
+
+ def test_short_page_terminates(self) -> None:
+ pages = [self._page(3, page=1, total_hits=3)]
+ rows, saved, fetched = _run_get_rows("services", pages)
+
+ assert len(fetched) == 1
+ assert saved == []
+ assert len(rows[0]) == 3
+
+ def test_total_hits_terminates_a_full_final_page(self) -> None:
+ pages = [self._page(PAGE_SIZE, page=1, total_hits=PAGE_SIZE)]
+ _rows, saved, fetched = _run_get_rows("endpoints", pages)
+
+ assert len(fetched) == 1
+ assert saved == []
+
+ def test_resume_starts_at_saved_page(self) -> None:
+ pages = [self._page(2, page=5, total_hits=1000)]
+ _rows, _saved, fetched = _run_get_rows(
+ "applications", pages, can_resume=True, resume_state=InstanaResumeConfig(next_page=5)
+ )
+
+ assert _query(fetched[0])["page"] == ["5"]
+
+ def test_pagination_limit_aborts_runaway_walk(self) -> None:
+ # A self-hosted host can return a full page forever while omitting a reliable totalHits, so
+ # the normal termination conditions never trip; the walk must abort past MAX_CATALOG_PAGES.
+ full_page = self._page(PAGE_SIZE, page=1, total_hits=10**9)
+ with mock.patch.object(inst, "MAX_CATALOG_PAGES", 3):
+ with pytest.raises(inst.InstanaPaginationLimitError):
+ _run_get_rows("applications", [full_page])
+
+ def test_pagination_walk_stops_at_time_budget(self) -> None:
+ # A slow host can stay under the per-page limits (and the page cap) while holding the worker,
+ # so the walk must also stop on a cumulative wall-clock budget. Fetch is stubbed to isolate
+ # the loop from the body-reader's own clock; monotonic advances 1s per call.
+ full_page = self._page(PAGE_SIZE, page=1, total_hits=10**9)
+ ticker = iter(range(0, 10_000))
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ manager.load_state.return_value = None
+ with (
+ mock.patch.object(inst, "MAX_CATALOG_WALK_SECONDS", 5),
+ mock.patch.object(inst.time, "monotonic", lambda: next(ticker)),
+ mock.patch.object(inst, "_fetch", return_value=full_page),
+ ):
+ with pytest.raises(inst.InstanaPaginationLimitError):
+ list(
+ inst._get_paged_rows(
+ mock.MagicMock(),
+ BASE_URL,
+ inst.INSTANA_ENDPOINTS["applications"],
+ mock.MagicMock(),
+ manager,
+ )
+ )
+
+
+class TestListRows:
+ def test_bare_list_body_is_yielded(self) -> None:
+ pages: list[Any] = [[{"id": "w1", "name": "site"}]]
+ rows, saved, fetched = _run_get_rows("websites", pages)
+
+ assert len(fetched) == 1
+ assert rows == [[{"id": "w1", "name": "site"}]]
+ assert saved == []
+
+ def test_snapshots_items_are_extracted_with_window_params(self) -> None:
+ pages: list[Any] = [{"items": [{"snapshotId": "s1", "plugin": "host"}]}]
+ rows, _saved, fetched = _run_get_rows("infrastructure_snapshots", pages)
+
+ query = _query(fetched[0])
+ assert "windowSize" in query
+ assert "size" in query
+ assert rows == [[{"snapshotId": "s1", "plugin": "host"}]]
+
+
+class TestErrorBodyLogging:
+ def test_large_error_body_is_bounded_in_log(self) -> None:
+ # A customer-controlled host can return a huge 4xx body; the log must carry only a bounded
+ # preview plus the byte length, never interpolate the whole body (log-flooding guard).
+ oversized = b"x" * (inst.ERROR_BODY_LOG_PREVIEW_BYTES + 5000)
+ resp = mock.MagicMock()
+ resp.status_code = 400
+ resp.ok = False
+ resp.iter_content.return_value = iter([oversized])
+ resp.raise_for_status.side_effect = requests.HTTPError("400", response=resp)
+
+ session = mock.MagicMock()
+ session.get.return_value = resp
+ logger = mock.MagicMock()
+
+ with pytest.raises(requests.HTTPError):
+ inst._fetch(session, f"{BASE_URL}/api/events", logger)
+
+ logged = logger.error.call_args[0][0]
+ assert f"body_bytes={len(oversized)}" in logged
+ # Only the preview is interpolated, not the full body.
+ assert logged.count("x") == inst.ERROR_BODY_LOG_PREVIEW_BYTES
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [
+ (200, (True, 200)),
+ (401, (False, 401)),
+ (403, (False, 403)),
+ (500, (False, 500)),
+ ],
+ )
+ def test_status_mapping(self, status_code: int, expected: tuple[bool, int]) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+
+ with _patch_host_safe(), mock.patch.object(inst, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials(BASE_URL, "token", team_id=1) == expected
+
+ def test_transport_error_returns_none_status(self) -> None:
+ with _patch_host_safe(), mock.patch.object(inst, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ assert validate_credentials(BASE_URL, "token", team_id=1) == (False, None)
+
+ def test_blocked_host_raises(self) -> None:
+ with mock.patch.object(inst, "_is_host_safe", return_value=(False, "blocked")):
+ with pytest.raises(inst.InstanaHostNotAllowedError):
+ validate_credentials(BASE_URL, "token", team_id=1)
+
+
+class TestGetRowsHostCheck:
+ def test_blocked_host_fails_the_sync(self) -> None:
+ with mock.patch.object(inst, "_is_host_safe", return_value=(False, "blocked")):
+ with pytest.raises(inst.InstanaHostNotAllowedError):
+ list(
+ inst.get_rows(
+ base_url=BASE_URL,
+ api_token="token",
+ endpoint="websites",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ )
+
+
+class TestInstanaSourceResponse:
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_pk"),
+ [
+ ("events", "eventId"),
+ ("applications", "id"),
+ ("infrastructure_snapshots", "snapshotId"),
+ ],
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pk: str) -> None:
+ response = instana_source(
+ base_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 == "asc"
+ # Instana timestamps are epoch-ms integers, so tables are unpartitioned.
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py
new file mode 100644
index 000000000000..f8ece127d2dd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py
@@ -0,0 +1,189 @@
+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.generated_configs import InstanaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.instana import (
+ InstanaHostNotAllowedError,
+ InstanaResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.instana.source import InstanaSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "events",
+ "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 TestInstanaSource:
+ def setup_method(self) -> None:
+ self.source = InstanaSource()
+ self.team_id = 123
+ self.config = InstanaSourceConfig(base_url="https://unit-tenant.instana.io", api_token="secret-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.INSTANA
+
+ def test_base_url_is_a_connection_host_field(self) -> None:
+ # Changing the base 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 == ["base_url"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Instana"
+ assert config.label == "IBM Instana Observability"
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ base_url_field, api_token_field = config.fields
+
+ assert isinstance(base_url_field, SourceFieldInputConfig)
+ assert base_url_field.name == "base_url"
+ assert base_url_field.type == SourceFieldInputConfigType.TEXT
+ assert base_url_field.required is True
+ assert base_url_field.secret is False
+
+ assert isinstance(api_token_field, SourceFieldInputConfig)
+ assert api_token_field.name == "api_token"
+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_token_field.required is True
+ assert api_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 any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_incremental_flags(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+
+ assert schemas["events"].supports_incremental is True
+ # Events mutate while open (state/end change), so append mode is never offered.
+ assert schemas["events"].supports_append is False
+ assert schemas["events"].incremental_fields == [
+ {
+ "label": "start",
+ "type": "integer",
+ "field": "start",
+ "field_type": "integer",
+ }
+ ]
+ assert schemas["events"].description is not None
+
+ for name in set(ENDPOINTS) - {"events"}:
+ 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=["applications"])
+ assert [s.name for s in schemas] == ["applications"]
+
+ @pytest.mark.parametrize(
+ ("probe_result", "expected_valid"),
+ [
+ ((True, 200), True),
+ # 403 = genuine token missing the probe's scope; must not block source-create.
+ ((False, 403), True),
+ ((False, 401), False),
+ ((False, 500), False),
+ ((False, None), False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.instana.source.validate_instana_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ probe_result: tuple[bool, int | None],
+ expected_valid: bool,
+ ) -> None:
+ mock_validate.return_value = probe_result
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert (error_message is None) is expected_valid
+ mock_validate.assert_called_once_with("https://unit-tenant.instana.io", "secret-token", self.team_id)
+
+ @pytest.mark.parametrize("exception", [ValueError("bad url"), InstanaHostNotAllowedError("blocked")])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.instana.source.validate_instana_credentials"
+ )
+ def test_validate_credentials_surfaces_url_errors(
+ self, mock_validate: mock.MagicMock, exception: Exception
+ ) -> None:
+ mock_validate.side_effect = exception
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == str(exception)
+
+ 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 InstanaResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.instana.source.instana_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="applications", team_id=99)
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ base_url="https://unit-tenant.instana.io",
+ api_token="secret-token",
+ endpoint="applications",
+ 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.instana.source.instana_source")
+ def test_source_for_pipeline_drops_watermark_when_incremental_disabled(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value=1767225600000)
+ 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 None
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.instana.source.instana_source")
+ def test_source_for_pipeline_passes_watermark_when_incremental_enabled(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(should_use_incremental_field=True, db_incremental_field_last_value=1767225600000)
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1767225600000