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 solarwinds_service_desk import source (#69384)

Tom Owers4cfaaa3e5d35
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 d69f602a9dce..0edabc6a0063 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -322,6 +322,7 @@ the row lists both.
| smartsheet | HTTP | requests | ✅ |
| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| snowflake | DB protocol | snowflake-connector-python | ➖ |
+| solarwinds_service_desk | HTTP | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
| squarespace | HTTP | requests | ✅ |
@@ -696,7 +697,6 @@ doesn't conflict with concurrent PRs.
- smaily
- smartengage
- smartwaiver
-- solarwinds_service_desk
- sonar_cloud
- split_io
- spotify_ads
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 795e4c9e0f56..e149c5e3f5a6 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
@@ -3208,7 +3208,8 @@ class SnowflakeSourceConfig(config.Config):
@config.config
class SolarwindsServiceDeskSourceConfig(config.Config):
- pass
+ api_token: str
+ region: Literal["us", "eu", "au"] = config.value(default="us")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/canonical_descriptions.py
new file mode 100644
index 000000000000..11f87a4ce7f7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/canonical_descriptions.py
@@ -0,0 +1,169 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "incidents": {
+ "description": "Help desk incidents and service requests, including state, priority, assignment, requester, and SLA violation details.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Incident",
+ "columns": {
+ "id": "Unique identifier for the incident.",
+ "number": "Human-readable incident number shown in the service desk UI.",
+ "name": "Title of the incident.",
+ "description": "Incident description, as HTML.",
+ "description_no_html": "Incident description with HTML markup stripped.",
+ "state": "Current workflow state of the incident (e.g. New, Assigned, Resolved, Closed).",
+ "priority": "Priority of the incident (e.g. Low, Medium, High, Critical).",
+ "category": "Category assigned to the incident, with its id, name, and defaults.",
+ "sub_category": "Subcategory assigned to the incident.",
+ "assignee": "User or group the incident is currently assigned to.",
+ "group_assignee": "Group the incident is assigned to, including its memberships.",
+ "requester": "User who requested or reported the incident.",
+ "created_by": "User who created the incident record.",
+ "site": "Site the incident is associated with.",
+ "department": "Department the incident is associated with.",
+ "is_service_request": "Whether the record is a service request rather than an incident.",
+ "origin": "Channel the incident was created from (e.g. email, portal).",
+ "sla_violations": "SLA violations recorded against the incident.",
+ "number_of_comments": "Count of comments on the incident.",
+ "resolution_code": "Resolution code selected when the incident was resolved.",
+ "resolution_description": "Free-text resolution description.",
+ "resolved_by": "User who resolved the incident.",
+ "due_at": "When the incident is due, per its SLA.",
+ "created_at": "When the incident was created (ISO 8601).",
+ "updated_at": "When the incident was last updated (ISO 8601).",
+ },
+ },
+ "problems": {
+ "description": "Problem records tracking root causes behind one or more incidents, with symptoms, workarounds, and linked records.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Problem",
+ "columns": {
+ "id": "Unique identifier for the problem.",
+ "number": "Human-readable problem number.",
+ "name": "Title of the problem.",
+ "description": "Problem description.",
+ "state": "Current workflow state of the problem.",
+ "priority": "Priority of the problem.",
+ "root_cause": "Root cause analysis for the problem.",
+ "symptoms": "Observed symptoms of the problem.",
+ "workaround": "Documented workaround while the problem is open.",
+ "assignee": "User or group the problem is assigned to.",
+ "requester": "User who raised the problem.",
+ "site": "Site the problem is associated with.",
+ "department": "Department the problem is associated with.",
+ "incidents": "Incidents linked to this problem.",
+ },
+ },
+ "changes": {
+ "description": "Change management records with plans, state, priority, and links to related incidents, problems, and releases.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Change",
+ "columns": {
+ "id": "Unique identifier for the change.",
+ "number": "Human-readable change number.",
+ "name": "Title of the change.",
+ "description": "Change description.",
+ "state": "Current workflow state of the change.",
+ "priority": "Priority of the change.",
+ "change_plan": "Plan describing how the change will be implemented.",
+ "rollback_plan": "Plan describing how the change will be rolled back if needed.",
+ "test_plan": "Plan describing how the change will be tested.",
+ "planned_start_at": "Planned start time of the change window.",
+ "planned_end_at": "Planned end time of the change window.",
+ "assignee": "User or group the change is assigned to.",
+ "requester": "User who requested the change.",
+ "site": "Site the change is associated with.",
+ "department": "Department the change is associated with.",
+ "created_at": "When the change was created (ISO 8601).",
+ },
+ },
+ "releases": {
+ "description": "Release records grouping changes that are deployed together.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Release",
+ },
+ "solutions": {
+ "description": "Knowledge base solution articles, with their content and attachments.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Solution",
+ "columns": {
+ "id": "Unique identifier for the solution.",
+ "number": "Human-readable solution number.",
+ "name": "Title of the solution article.",
+ "description": "Solution body, as HTML.",
+ "description_no_html": "Solution body with HTML markup stripped.",
+ "creator": "User who authored the solution.",
+ "attachments": "Files attached to the solution.",
+ "created_at": "When the solution was created (ISO 8601).",
+ },
+ },
+ "catalog_items": {
+ "description": "Service catalog items users can request through the service portal.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Catalog-Item",
+ },
+ "users": {
+ "description": "Users of the service desk account, with contact details, site, department, and role information.",
+ "docs_url": "https://apidoc.samanage.com/#tag/User",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "Full name of the user.",
+ "email": "Email address of the user.",
+ "title": "Job title of the user.",
+ "phone": "Phone number of the user.",
+ "mobile_phone": "Mobile phone number of the user.",
+ "disabled": "Whether the user is disabled and can no longer sign in.",
+ "site": "Site the user belongs to.",
+ "department": "Department the user belongs to.",
+ "created_at": "When the user was created (ISO 8601).",
+ },
+ },
+ "groups": {
+ "description": "Groups used for assignment and notifications, with their memberships.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Group",
+ },
+ "departments": {
+ "description": "Departments records can be associated with (incidents, assets, users).",
+ "docs_url": "https://apidoc.samanage.com/#tag/Department",
+ },
+ "sites": {
+ "description": "Physical sites/locations records can be associated with.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Site",
+ },
+ "hardwares": {
+ "description": "Hardware assets (computers) tracked in asset management, with hardware specs, network details, and ownership.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Hardware",
+ "columns": {
+ "id": "Unique identifier for the hardware asset.",
+ "name": "Name of the hardware asset.",
+ "asset_tag": "Asset tag assigned to the hardware.",
+ "status": "Status of the hardware asset.",
+ "category": "Category of the hardware asset.",
+ "ip": "IP address of the hardware.",
+ "external_ip": "External IP address of the hardware.",
+ "domain": "Domain the hardware belongs to.",
+ "operating_system": "Operating system installed on the hardware.",
+ "memory": "Installed memory.",
+ "cpu": "CPU description.",
+ "owner": "User who owns the hardware asset.",
+ "technical_contact": "Technical contact for the hardware asset.",
+ "site": "Site the hardware is located at.",
+ "department": "Department the hardware belongs to.",
+ },
+ },
+ "other_assets": {
+ "description": "Non-computer assets (peripherals, furniture, equipment) tracked in asset management.",
+ "docs_url": "https://apidoc.samanage.com/#tag/Other-Asset",
+ "columns": {
+ "id": "Unique identifier for the asset.",
+ "name": "Name of the asset.",
+ "asset_id": "Asset identifier assigned in the service desk.",
+ "asset_type": "Type of the asset.",
+ "serial_number": "Serial number of the asset.",
+ "manufacturer": "Manufacturer of the asset.",
+ "model": "Model of the asset.",
+ "owner": "User who owns the asset.",
+ "user": "User the asset is assigned to.",
+ "site": "Site the asset is located at.",
+ "department": "Department the asset belongs to.",
+ "created_at": "When the asset was created (ISO 8601).",
+ "updated_at": "When the asset was last updated (ISO 8601).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/settings.py
new file mode 100644
index 000000000000..b5e845c5b958
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/settings.py
@@ -0,0 +1,116 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# The API docs' pagination examples request 100 rows per page; no hard maximum is documented, so we
+# stay at the documented example value.
+PER_PAGE = 100
+
+
+def _updated_at_incremental_fields() -> list[IncrementalField]:
+ # The server-side `updated_from` filter (ISO 8601 UTC, "until now") keys off `updated_at`.
+ return [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@dataclass
+class SolarwindsServiceDeskEndpointConfig:
+ name: str
+ path: str # Path on the regional API host, e.g. "/incidents.json"
+ # Singular resource key some list payloads wrap each row in (e.g. {"problem": {...}}). The
+ # official response samples are inconsistent about this, so the transport unwraps defensively.
+ wrapper_key: str
+ # Only /incidents documents the server-side `updated_from` time filter; every other list
+ # endpoint is full refresh (they expose only field-equality search params).
+ supports_incremental: bool = False
+ # Stable creation-time field to partition by. Only set where the documented response sample
+ # actually includes `created_at`.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Record ids are account-unique integers, so `id` is a safe primary key on every endpoint.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+SOLARWINDS_SERVICE_DESK_ENDPOINTS: dict[str, SolarwindsServiceDeskEndpointConfig] = {
+ "incidents": SolarwindsServiceDeskEndpointConfig(
+ name="incidents",
+ path="/incidents.json",
+ wrapper_key="incident",
+ supports_incremental=True,
+ partition_key="created_at",
+ incremental_fields=_updated_at_incremental_fields(),
+ ),
+ "problems": SolarwindsServiceDeskEndpointConfig(
+ name="problems",
+ path="/problems.json",
+ wrapper_key="problem",
+ ),
+ "changes": SolarwindsServiceDeskEndpointConfig(
+ name="changes",
+ path="/changes.json",
+ wrapper_key="change",
+ partition_key="created_at",
+ ),
+ "releases": SolarwindsServiceDeskEndpointConfig(
+ name="releases",
+ path="/releases.json",
+ wrapper_key="release",
+ ),
+ "solutions": SolarwindsServiceDeskEndpointConfig(
+ name="solutions",
+ path="/solutions.json",
+ wrapper_key="solution",
+ partition_key="created_at",
+ ),
+ "catalog_items": SolarwindsServiceDeskEndpointConfig(
+ name="catalog_items",
+ path="/catalog_items.json",
+ wrapper_key="catalog_item",
+ ),
+ "users": SolarwindsServiceDeskEndpointConfig(
+ name="users",
+ path="/users.json",
+ wrapper_key="user",
+ ),
+ "groups": SolarwindsServiceDeskEndpointConfig(
+ name="groups",
+ path="/groups.json",
+ wrapper_key="group",
+ ),
+ "departments": SolarwindsServiceDeskEndpointConfig(
+ name="departments",
+ path="/departments.json",
+ wrapper_key="department",
+ ),
+ "sites": SolarwindsServiceDeskEndpointConfig(
+ name="sites",
+ path="/sites.json",
+ wrapper_key="site",
+ ),
+ "hardwares": SolarwindsServiceDeskEndpointConfig(
+ name="hardwares",
+ path="/hardwares.json",
+ wrapper_key="hardware",
+ ),
+ "other_assets": SolarwindsServiceDeskEndpointConfig(
+ name="other_assets",
+ path="/other_assets.json",
+ wrapper_key="other_asset",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(SOLARWINDS_SERVICE_DESK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields
+ for name, config in SOLARWINDS_SERVICE_DESK_ENDPOINTS.items()
+ if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/solarwinds_service_desk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/solarwinds_service_desk.py
new file mode 100644
index 000000000000..8ed281e093c7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/solarwinds_service_desk.py
@@ -0,0 +1,257 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from dateutil import parser as dateutil_parser
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.settings import (
+ PER_PAGE,
+ SOLARWINDS_SERVICE_DESK_ENDPOINTS,
+)
+
+# SolarWinds Service Desk runs independent regional stacks that do not share data.
+SOLARWINDS_SERVICE_DESK_HOSTS: dict[str, str] = {
+ "us": "https://api.samanage.com",
+ "eu": "https://apieu.samanage.com",
+ "au": "https://apiau.samanage.com",
+}
+DEFAULT_REGION = "us"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Cheap list probe used to confirm a token is genuine. The token inherits its creator's role, so a
+# 403 here can still mean a valid token — the caller decides how to treat it.
+DEFAULT_PROBE_PATH = "/users.json"
+
+
+class SolarwindsServiceDeskRetryableError(Exception):
+ pass
+
+
+class SolarwindsServiceDeskResumeConfig:
+ # Next 1-indexed page to fetch. None means start from page 1.
+ next_page: int | None = None
+ # `updated_from` filter computed when the run started. Persisted so a resumed run issues the
+ # exact same query instead of recomputing a window whose page boundaries would shift mid-crawl.
+ updated_from: str | None = None
+
+
+def base_url(region: Optional[str]) -> str:
+ resolved = (region or DEFAULT_REGION).lower()
+ return SOLARWINDS_SERVICE_DESK_HOSTS.get(resolved, SOLARWINDS_SERVICE_DESK_HOSTS[DEFAULT_REGION])
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ # Auth rides a vendor-specific header, and the versioned Accept header pins the payload format —
+ # without it the API may serve legacy shapes.
+ return {
+ "X-Samanage-Authorization": f"Bearer {api_token}",
+ "Accept": "application/vnd.samanage.v2.1+json",
+ }
+
+
+def _format_updated_from(value: Any) -> Optional[str]:
+ """Format an incremental cursor as the ISO 8601 UTC value the `updated_from` filter expects.
+
+ Returns None when the watermark can't be interpreted, which safely degrades that run to a full
+ crawl rather than guessing at a window.
+ """
+ if isinstance(value, str):
+ try:
+ value = dateutil_parser.parse(value)
+ except (ValueError, OverflowError):
+ return None
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ aware = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ return None
+ # The documented examples use minute precision ('2023-11-29T08:00'); truncating rounds the
+ # window start down, so boundary rows are re-fetched and merge dedupes them on `id`.
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M")
+
+
+def _build_url(host: str, path: str, page: int, updated_from: Optional[str]) -> str:
+ params: dict[str, Any] = {"per_page": PER_PAGE, "page": page}
+ if updated_from is not None:
+ params["updated_from"] = updated_from
+ return f"{host}{path}?{urlencode(params)}"
+
+
+def _unwrap_rows(items: list[Any], wrapper_key: str) -> list[dict[str, Any]]:
+ """Normalize list items to bare record dicts.
+
+ The official response samples are inconsistent: some list endpoints show bare records while
+ others wrap each row under its singular resource name (e.g. ``{"problem": {...}}``). A real
+ record is never a single-key dict of its own singular name, so unwrapping is unambiguous.
+ """
+ rows: list[dict[str, Any]] = []
+ for item in items:
+ if isinstance(item, dict) and set(item.keys()) == {wrapper_key} and isinstance(item[wrapper_key], dict):
+ rows.append(item[wrapper_key])
+ elif isinstance(item, dict):
+ rows.append(item)
+ return rows
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (SolarwindsServiceDeskRetryableError, requests.ReadTimeout, requests.ConnectionError)
+ ),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[Any], Optional[int]]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # The API allows 1000 requests/min but sends no rate-limit or Retry-After headers, so back off
+ # blind on 429 and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SolarwindsServiceDeskRetryableError(
+ f"SolarWinds Service Desk API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(
+ f"SolarWinds Service Desk API error: status={response.status_code}, body={response.text}, url={url}"
+ )
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, list):
+ raise SolarwindsServiceDeskRetryableError(
+ f"SolarWinds Service Desk returned an unexpected payload for {url}: {type(data).__name__}"
+ )
+
+ total_pages_header = response.headers.get("X-Total-Pages")
+ total_pages = int(total_pages_header) if total_pages_header and total_pages_header.isdigit() else None
+ return data, total_pages
+
+
+def get_rows(
+ region: Optional[str],
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SolarwindsServiceDeskResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SOLARWINDS_SERVICE_DESK_ENDPOINTS[endpoint]
+ host = base_url(region)
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_page:
+ page = resume.next_page
+ updated_from = resume.updated_from
+ logger.debug(f"SolarWinds Service Desk: resuming {endpoint} from page {page}")
+ else:
+ page = 1
+ updated_from = None
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:
+ updated_from = _format_updated_from(db_incremental_field_last_value)
+
+ while True:
+ items, total_pages = _fetch_page(session, _build_url(host, config.path, page, updated_from), logger)
+ rows = _unwrap_rows(items, config.wrapper_key)
+ if rows:
+ yield rows
+
+ # Stop on an empty page, or once the documented X-Total-Pages header says this was the last
+ # one. Never infer the end from a short page — the server may clamp `per_page` below what we
+ # requested, which would silently truncate the sync.
+ if not items or (total_pages is not None and page >= total_pages):
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches the last unpersisted page; merge dedupes on `id`.
+ resumable_source_manager.save_state(
+ SolarwindsServiceDeskResumeConfig(next_page=page, updated_from=updated_from)
+ )
+
+
+def solarwinds_service_desk_source(
+ region: Optional[str],
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SolarwindsServiceDeskResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SOLARWINDS_SERVICE_DESK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ api_token=api_token,
+ endpoint=endpoint,
+ 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_keys,
+ # List ordering is undocumented (no sort params, likely newest-first): "desc" makes the
+ # pipeline commit the incremental watermark only after a completed sync instead of
+ # checkpointing a possibly-too-high value per batch.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(region: Optional[str], api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single list endpoint to validate the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+ url = f"{base_url(region)}{path}?{urlencode({'per_page': 1, 'page': 1})}"
+ try:
+ response = session.get(url, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to SolarWinds Service Desk: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"SolarWinds Service Desk returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(region: Optional[str], api_token: str, path: str | None = None) -> tuple[bool, str | None]:
+ status, message = check_access(region, api_token, path or DEFAULT_PROBE_PATH)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid SolarWinds Service Desk API token"
+ if status == 403:
+ # The token is genuine but its owner's role can't read this resource. At source-create
+ # (no specific schema requested) that must not block connecting the source.
+ if path is None:
+ return True, None
+ return False, "Your SolarWinds Service Desk token does not have permission to read this resource"
+ return False, message or "Could not validate SolarWinds Service Desk API token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/source.py
index 8723e0526b2f..d64183ba7982 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/source.py
@@ -1,32 +1,178 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.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 (
SolarwindsServiceDeskSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SOLARWINDS_SERVICE_DESK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.solarwinds_service_desk import (
+ SOLARWINDS_SERVICE_DESK_HOSTS,
+ SolarwindsServiceDeskResumeConfig,
+ solarwinds_service_desk_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SolarwindsServiceDeskSource(SimpleSource[SolarwindsServiceDeskSourceConfig]):
+class SolarwindsServiceDeskSource(
+ ResumableSource[SolarwindsServiceDeskSourceConfig, SolarwindsServiceDeskResumeConfig]
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SOLARWINDSSERVICEDESK
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API token is sent to the host derived from `region`, so changing the region must
+ # re-require the token rather than reusing it against a different host.
+ return ["region"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SOLARWINDS_SERVICE_DESK,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
- label="Solarwinds Service Desk",
- iconPath="/static/services/solarwinds_service_desk.png",
- fields=cast(list[FieldType], []),
+ label="SolarWinds Service Desk",
+ keywords=["samanage", "swsd", "solarwinds", "itsm", "service desk"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Kept hidden for now: the implementation follows the public API docs but its
+ # end-to-end sync behavior hasn't been exercised against a live account yet.
unreleasedSource=True,
+ caption="""Enter your SolarWinds Service Desk JSON web token to pull your service desk data into the PostHog Data warehouse.
+
+You can generate a token in SolarWinds Service Desk under **Setup → Users & Access → Users** — open the user and use **Actions → Generate JSON Web Token**. The token inherits that user's role, so it needs read access to the records you want to sync, and requests stop working if that user is ever disabled.
+
+SolarWinds Service Desk runs independent regional stacks that do not share data — pick the region your account is on.""",
+ iconPath="/static/services/solarwinds_service_desk.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/solarwinds-service-desk",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.samanage.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (apieu.samanage.com)", value="eu"),
+ SourceFieldSelectConfigOption(label="APJ (apiau.samanage.com)", value="au"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="JSON web token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ invalid_token = (
+ "Your SolarWinds Service Desk token is invalid or its user has been disabled. "
+ "Generate a new JSON web token and reconnect."
+ )
+ missing_role = (
+ "Your SolarWinds Service Desk token does not have permission to read this data. "
+ "Check the token owner's role, then reconnect."
+ )
+ errors: dict[str, str | None] = {}
+ for host in SOLARWINDS_SERVICE_DESK_HOSTS.values():
+ errors[f"401 Client Error: Unauthorized for url: {host}"] = invalid_token
+ errors[f"403 Client Error: Forbidden for url: {host}"] = missing_role
+ return errors
+
+ def get_schemas(
+ self,
+ config: SolarwindsServiceDeskSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint in INCREMENTAL_FIELDS,
+ supports_append=endpoint in INCREMENTAL_FIELDS,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: SolarwindsServiceDeskSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # At source-create only the token is probed (a 403 there can just mean the token's role
+ # doesn't cover the probe resource); with a schema_name we probe that endpoint's own path.
+ endpoint = SOLARWINDS_SERVICE_DESK_ENDPOINTS.get(schema_name) if schema_name else None
+ return validate_credentials(config.region, config.api_token, endpoint.path if endpoint else None)
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[SolarwindsServiceDeskResumeConfig]:
+ return ResumableSourceManager[SolarwindsServiceDeskResumeConfig](inputs, SolarwindsServiceDeskResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SolarwindsServiceDeskSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SolarwindsServiceDeskResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SOLARWINDS_SERVICE_DESK_ENDPOINTS:
+ raise ValueError(f"Unknown SolarWinds Service Desk schema '{inputs.schema_name}'")
+
+ return solarwinds_service_desk_source(
+ region=config.region,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ 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/solarwinds_service_desk/tests/test_solarwinds_service_desk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/tests/test_solarwinds_service_desk.py
new file mode 100644
index 000000000000..c2c785cdcbc4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/tests/test_solarwinds_service_desk.py
@@ -0,0 +1,366 @@
+from collections.abc import Mapping
+from datetime import UTC, date, datetime, timedelta, timezone
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk import (
+ solarwinds_service_desk,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.settings import (
+ ENDPOINTS,
+ PER_PAGE,
+ SOLARWINDS_SERVICE_DESK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.solarwinds_service_desk import (
+ SolarwindsServiceDeskResumeConfig,
+ SolarwindsServiceDeskRetryableError,
+ _format_updated_from,
+ _headers,
+ _unwrap_rows,
+ base_url,
+ check_access,
+ get_rows,
+ solarwinds_service_desk_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = solarwinds_service_desk._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SolarwindsServiceDeskResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SolarwindsServiceDeskResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SolarwindsServiceDeskResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SolarwindsServiceDeskResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ pages: Mapping[str, tuple[list[Any], int | None]],
+ endpoint: str = "incidents",
+ **kwargs: Any,
+ ) -> tuple[list[dict], list[str]]:
+ requested_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> tuple[list[Any], int | None]:
+ requested_urls.append(url)
+ return pages[url]
+
+ rows: list[dict] = []
+ with (
+ patch.object(solarwinds_service_desk, "_fetch_page", fake_fetch),
+ patch.object(solarwinds_service_desk, "make_tracked_session", return_value=MagicMock()),
+ ):
+ for batch in get_rows(
+ region="us",
+ api_token="swsd-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, requested_urls
+
+ @staticmethod
+ def _url(endpoint: str, page: int, updated_from: str | None = None, host: str = "https://api.samanage.com") -> str:
+ path = SOLARWINDS_SERVICE_DESK_ENDPOINTS[endpoint].path
+ base = f"{host}{path}?per_page={PER_PAGE}&page={page}"
+ if updated_from is not None:
+ return f"{base}&updated_from={updated_from.replace(':', '%3A')}"
+ return base
+
+ def test_stops_after_last_page_per_total_pages_header(self) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ self._url("incidents", 1): ([{"id": 1}], 2),
+ self._url("incidents", 2): ([{"id": 2}], 2),
+ }
+ rows, urls = self._collect(manager, pages)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert len(urls) == 2
+ # State is saved after each yielded page, pointing at the next page to fetch.
+ assert [s.next_page for s in manager.saved] == [2]
+
+ def test_short_page_does_not_stop_pagination(self) -> None:
+ # A page smaller than PER_PAGE must not be treated as the end: the server may clamp
+ # `per_page`, so only an empty page or the X-Total-Pages header terminates the crawl.
+ manager = _FakeResumableManager()
+ pages: Mapping[str, tuple[list[Any], int | None]] = {
+ self._url("incidents", 1): ([{"id": 1}], None),
+ self._url("incidents", 2): ([{"id": 2}], None),
+ self._url("incidents", 3): ([], None),
+ }
+ rows, urls = self._collect(manager, pages)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert len(urls) == 3
+
+ def test_resumes_from_saved_page_with_saved_filter(self) -> None:
+ manager = _FakeResumableManager(SolarwindsServiceDeskResumeConfig(next_page=3, updated_from="2026-01-01T00:00"))
+ pages = {self._url("incidents", 3, "2026-01-01T00:00"): ([{"id": 9}], 3)}
+ rows, urls = self._collect(
+ manager,
+ pages,
+ # A resumed run must reuse the persisted filter, not recompute one from this watermark.
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-02-02T00:00:00Z",
+ )
+ assert rows == [{"id": 9}]
+ assert urls == [self._url("incidents", 3, "2026-01-01T00:00")]
+
+ def test_incremental_watermark_adds_updated_from_param(self) -> None:
+ manager = _FakeResumableManager()
+ pages: Mapping[str, tuple[list[Any], int | None]] = {self._url("incidents", 1, "2026-01-05T08:30"): ([], None)}
+ _, urls = self._collect(
+ manager,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 5, 8, 30, tzinfo=UTC),
+ )
+ assert urls == [self._url("incidents", 1, "2026-01-05T08:30")]
+
+ @parameterized.expand(
+ [
+ ("full_refresh_endpoint", "users", True, datetime(2026, 1, 5, tzinfo=UTC)),
+ ("incremental_disabled", "incidents", False, datetime(2026, 1, 5, tzinfo=UTC)),
+ ("no_watermark", "incidents", True, None),
+ ("unparseable_watermark", "incidents", True, "not a datetime"),
+ ]
+ )
+ def test_no_updated_from_param(self, _name: str, endpoint: str, use_incremental: bool, watermark: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: Mapping[str, tuple[list[Any], int | None]] = {self._url(endpoint, 1): ([], None)}
+ _, urls = self._collect(
+ manager,
+ pages,
+ endpoint=endpoint,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=watermark,
+ )
+ assert urls == [self._url(endpoint, 1)]
+
+ def test_wrapped_rows_are_unwrapped(self) -> None:
+ manager = _FakeResumableManager()
+ pages = {self._url("problems", 1): ([{"problem": {"id": 7, "name": "P"}}], 1)}
+ rows, _ = self._collect(manager, pages, endpoint="problems")
+ assert rows == [{"id": 7, "name": "P"}]
+
+
+class TestFormatUpdatedFrom:
+ @parameterized.expand(
+ [
+ ("aware_utc", datetime(2026, 1, 5, 8, 30, 59, tzinfo=UTC), "2026-01-05T08:30"),
+ ("aware_offset", datetime(2026, 1, 5, 9, 30, tzinfo=timezone(timedelta(hours=1))), "2026-01-05T08:30"),
+ ("naive_treated_as_utc", datetime(2026, 1, 5, 8, 30), "2026-01-05T08:30"),
+ ("iso_string", "2026-01-05T08:30:59.000+00:00", "2026-01-05T08:30"),
+ ("date", date(2026, 1, 5), "2026-01-05T00:00"),
+ ("garbage_string", "not a datetime", None),
+ ("integer", 12345, None),
+ ("none", None, None),
+ ]
+ )
+ def test_formats(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _format_updated_from(value) == expected
+
+
+class TestUnwrapRows:
+ def test_handles_both_documented_list_shapes(self) -> None:
+ # The official response samples show bare records on some endpoints and singularly wrapped
+ # records on others — both must normalize to the bare record.
+ items = [
+ {"user": {"id": 1, "name": "A"}},
+ {"id": 2, "name": "B"},
+ {"user": "not a record", "id": 3},
+ "junk",
+ ]
+ assert _unwrap_rows(items, "user") == [
+ {"id": 1, "name": "A"},
+ {"id": 2, "name": "B"},
+ {"user": "not a record", "id": 3},
+ ]
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None, headers: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.headers = headers or {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SolarwindsServiceDeskRetryableError):
+ _fetch_page_unwrapped(session, "https://api.samanage.com/incidents.json", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "https://api.samanage.com/incidents.json", MagicMock())
+
+ def test_non_list_body_is_retryable(self) -> None:
+ session = self._session_returning(200, {"error": "weird"})
+ with pytest.raises(SolarwindsServiceDeskRetryableError):
+ _fetch_page_unwrapped(session, "https://api.samanage.com/incidents.json", MagicMock())
+
+ @parameterized.expand(
+ [
+ ("header_present", {"X-Total-Pages": "7"}, 7),
+ ("header_missing", {}, None),
+ ("header_garbage", {"X-Total-Pages": "lots"}, None),
+ ]
+ )
+ def test_total_pages_header_parsing(self, _name: str, headers: dict, expected: int | None) -> None:
+ session = self._session_returning(200, [{"id": 1}], headers)
+ items, total_pages = _fetch_page_unwrapped(session, "https://api.samanage.com/incidents.json", MagicMock())
+ assert items == [{"id": 1}]
+ assert total_pages == expected
+
+
+class TestAuthAndHosts:
+ def test_headers_carry_vendor_auth_and_versioned_accept(self) -> None:
+ # The versioned Accept header is mandatory — without it the API can serve legacy payloads.
+ headers = _headers("swsd-token")
+ assert headers["X-Samanage-Authorization"] == "Bearer swsd-token"
+ assert headers["Accept"] == "application/vnd.samanage.v2.1+json"
+
+ @parameterized.expand(
+ [
+ ("us", "https://api.samanage.com"),
+ ("eu", "https://apieu.samanage.com"),
+ ("au", "https://apiau.samanage.com"),
+ (None, "https://api.samanage.com"),
+ ("unknown", "https://api.samanage.com"),
+ ]
+ )
+ def test_base_url_per_region(self, region: str | None, expected: str) -> None:
+ assert base_url(region) == expected
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "SolarWinds Service Desk returned HTTP 500"),
+ ]
+ )
+ @patch(f"{solarwinds_service_desk.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_session.return_value = self._session(response)
+ assert check_access("us", "swsd-token") == (expected_status, expected_message)
+
+ @patch(f"{solarwinds_service_desk.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("us", "swsd-token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok_at_create", 200, None, True, None),
+ ("bad_token_at_create", 401, None, False, "Invalid SolarWinds Service Desk API token"),
+ # A 403 with a genuine token must not block source-create, but must fail a
+ # schema-scoped probe so the user sees which table their role can't read.
+ ("forbidden_at_create", 403, None, True, None),
+ (
+ "forbidden_for_schema",
+ 403,
+ "/incidents.json",
+ False,
+ "Your SolarWinds Service Desk token does not have permission to read this resource",
+ ),
+ ("server_error", 500, None, False, "SolarWinds Service Desk returned HTTP 500"),
+ ]
+ )
+ @patch(f"{solarwinds_service_desk.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ path: str | None,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ assert validate_credentials("us", "swsd-token", path) == (expected_valid, expected_message)
+
+
+class TestSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ config = SOLARWINDS_SERVICE_DESK_ENDPOINTS[endpoint]
+ response = solarwinds_service_desk_source(
+ region="us",
+ api_token="swsd-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Ordering is undocumented, so the watermark must only commit after a completed sync.
+ assert response.sort_mode == "desc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+ def test_partition_keys_are_stable_creation_fields(self) -> None:
+ # updated_at-style partition keys rewrite partitions on every sync.
+ assert all(
+ config.partition_key in (None, "created_at") for config in SOLARWINDS_SERVICE_DESK_ENDPOINTS.values()
+ )
+ assert set(SOLARWINDS_SERVICE_DESK_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/tests/test_solarwinds_service_desk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/tests/test_solarwinds_service_desk_source.py
new file mode 100644
index 000000000000..c8d30c97b834
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/solarwinds_service_desk/tests/test_solarwinds_service_desk_source.py
@@ -0,0 +1,170 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+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 (
+ SolarwindsServiceDeskSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.solarwinds_service_desk import (
+ SolarwindsServiceDeskResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.source import (
+ SolarwindsServiceDeskSource,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.solarwinds_service_desk.source"
+
+
+class TestSolarwindsServiceDeskSource:
+ def setup_method(self) -> None:
+ self.source = SolarwindsServiceDeskSource()
+ self.team_id = 123
+ self.config = SolarwindsServiceDeskSourceConfig(api_token="swsd-token", region="eu")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SOLARWINDSSERVICEDESK
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "SolarwindsServiceDesk"
+ assert config.label == "SolarWinds Service Desk"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Deliberately hidden until the sync has been exercised against a live account.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/solarwinds-service-desk"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["region", "api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_region_field_covers_documented_hosts(self) -> None:
+ config = self.source.get_source_config
+ region = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")
+ assert [option.value for option in region.options] == ["us", "eu", "au"]
+ assert region.defaultValue == "us"
+
+ def test_region_is_a_connection_host_field(self) -> None:
+ # The token is sent to the host derived from `region`; retargeting the region must force
+ # re-entering the token, or an editor could exfiltrate it to another regional stack.
+ assert self.source.connection_host_fields == ["region"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ 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)
+ # Only /incidents documents a server-side updated_from filter.
+ assert schemas["incidents"].supports_incremental is True
+ assert [f["field"] for f in schemas["incidents"].incremental_fields] == ["updated_at"]
+ for name, schema in schemas.items():
+ if name not in INCREMENTAL_FIELDS:
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["incidents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "incidents"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("unauthorized_us", "401 Client Error: Unauthorized for url: https://api.samanage.com/incidents.json"),
+ ("forbidden_eu", "403 Client Error: Forbidden for url: https://apieu.samanage.com/users.json"),
+ ("unauthorized_au", "401 Client Error: Unauthorized for url: https://apiau.samanage.com/problems.json"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.samanage.com"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://apieu.samanage.com"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ # At create only the token is probed; per-schema validation probes that endpoint's path.
+ ("at_create", None, None),
+ ("for_schema", "incidents", "/incidents.json"),
+ ("unknown_schema", "not_a_table", None),
+ ]
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.validate_credentials")
+ def test_validate_credentials_probes_the_right_path(
+ self, _name: str, schema_name: str | None, expected_path: str | None, mock_validate: mock.MagicMock
+ ) -> None:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name)
+ mock_validate.assert_called_once_with("eu", "swsd-token", expected_path)
+ assert result == (True, None)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SolarwindsServiceDeskResumeConfig
+
+ @mock.patch(f"{_SOURCE_MODULE}.solarwinds_service_desk_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "incidents"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-05T08:30:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["region"] == "eu"
+ assert kwargs["api_token"] == "swsd-token"
+ assert kwargs["endpoint"] == "incidents"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-05T08:30:00Z"
+
+ @mock.patch(f"{_SOURCE_MODULE}.solarwinds_service_desk_source")
+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "incidents"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-05T08:30:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown SolarWinds Service Desk schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)