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 freshservice import source (#67794)

Tom Owers9fa999b9962a
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 0aafab3173c1..6650c707e9d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -133,6 +133,7 @@ the row lists both.
| easypromos | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
| freshsales | HTTP | requests | ✅ |
+| freshservice | HTTP | requests | ✅ |
| elasticemail | HTTP | requests | ✅ |
| elasticsearch | HTTP | requests | ✅ |
| emailoctopus | HTTP | requests | ✅ |
@@ -415,7 +416,6 @@ doesn't conflict with concurrent PRs.
- freshbooks
- freshcaller
- freshchat
-- freshservice
- fulcrum
- gainsight_px
- gitbook
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/canonical_descriptions.py
new file mode 100644
index 000000000000..efa21224244f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/canonical_descriptions.py
@@ -0,0 +1,257 @@
+"""Canonical, documentation-sourced descriptions for Freshservice endpoints and columns.
+
+Sourced from the official Freshservice API v2 reference (https://api.freshservice.com/).
+Keyed by the endpoint names in `settings.py` `FRESHSERVICE_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Freshservice table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields shared by most Freshservice objects; merged into each entry so we don't repeat them.
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the object.",
+ "created_at": "Time at which the object was created.",
+ "updated_at": "Time at which the object was last updated.",
+}
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "tickets": {
+ "description": "A service request or incident raised by a requester and tracked through to resolution.",
+ "docs_url": "https://api.freshservice.com/#tickets",
+ "columns": _columns(
+ subject="Subject of the ticket.",
+ description="Description (body) of the ticket, in HTML.",
+ description_text="Plain-text version of the ticket description.",
+ status="Status of the ticket (2=open, 3=pending, 4=resolved, 5=closed).",
+ priority="Priority of the ticket (1=low, 2=medium, 3=high, 4=urgent).",
+ source="Channel the ticket came in through (1=email, 2=portal, 3=phone, …).",
+ type="Type categorizing the ticket (e.g. Incident, Service Request).",
+ requester_id="ID of the requester who raised the ticket.",
+ responder_id="ID of the agent the ticket is assigned to.",
+ group_id="ID of the agent group the ticket is assigned to.",
+ department_id="ID of the department the requester belongs to.",
+ email="Email address of the requester.",
+ category="Ticket category.",
+ sub_category="Ticket sub-category.",
+ item_category="Ticket item category.",
+ tags="List of tags applied to the ticket.",
+ due_by="Time by which the ticket is due for resolution.",
+ fr_due_by="Time by which the first response is due.",
+ spam="Whether the ticket has been marked as spam.",
+ ),
+ },
+ "problems": {
+ "description": "A problem record tracking the root cause behind one or more incidents.",
+ "docs_url": "https://api.freshservice.com/#problems",
+ "columns": _columns(
+ subject="Subject of the problem.",
+ description="Description of the problem, in HTML.",
+ status="Status of the problem (1=open, 2=change requested, 3=closed).",
+ priority="Priority of the problem (1=low, 2=medium, 3=high, 4=urgent).",
+ impact="Impact of the problem (1=low, 2=medium, 3=high).",
+ agent_id="ID of the agent the problem is assigned to.",
+ group_id="ID of the agent group the problem is assigned to.",
+ department_id="ID of the department the problem relates to.",
+ due_by="Time by which the problem is due to be resolved.",
+ ),
+ },
+ "changes": {
+ "description": "A change request tracking a planned modification to the IT environment.",
+ "docs_url": "https://api.freshservice.com/#changes",
+ "columns": _columns(
+ subject="Subject of the change.",
+ description="Description of the change, in HTML.",
+ status="Status of the change (1=open, 2=planning, 3=approval, 4=pending release, 5=pending review, 6=closed).",
+ priority="Priority of the change (1=low, 2=medium, 3=high, 4=urgent).",
+ impact="Impact of the change (1=low, 2=medium, 3=high).",
+ risk="Risk of the change (1=minor, 2=standard, 3=major, 4=high).",
+ change_type="Type of change (1=minor, 2=standard, 3=major, 4=emergency).",
+ agent_id="ID of the agent the change is assigned to.",
+ group_id="ID of the agent group the change is assigned to.",
+ department_id="ID of the department the change relates to.",
+ planned_start_date="Planned start of the change.",
+ planned_end_date="Planned end of the change.",
+ ),
+ },
+ "releases": {
+ "description": "A release record tracking the rollout of changes to production.",
+ "docs_url": "https://api.freshservice.com/#releases",
+ "columns": _columns(
+ subject="Subject of the release.",
+ description="Description of the release, in HTML.",
+ status="Status of the release (1=open, 2=on hold, 3=in progress, 4=incomplete, 5=completed).",
+ priority="Priority of the release (1=low, 2=medium, 3=high, 4=urgent).",
+ release_type="Type of release (1=minor, 2=standard, 3=major, 4=emergency).",
+ agent_id="ID of the agent the release is assigned to.",
+ group_id="ID of the agent group the release is assigned to.",
+ department_id="ID of the department the release relates to.",
+ planned_start_date="Planned start of the release.",
+ planned_end_date="Planned end of the release.",
+ ),
+ },
+ "requesters": {
+ "description": "An end user who can raise tickets with the service desk.",
+ "docs_url": "https://api.freshservice.com/#requesters",
+ "columns": _columns(
+ first_name="The requester's first name.",
+ last_name="The requester's last name.",
+ primary_email="The requester's primary email address.",
+ secondary_emails="The requester's additional email addresses.",
+ work_phone_number="The requester's work phone number.",
+ mobile_phone_number="The requester's mobile phone number.",
+ department_ids="IDs of the departments the requester belongs to.",
+ job_title="The requester's job title.",
+ location_id="ID of the requester's location.",
+ active="Whether the requester is active.",
+ time_zone="The requester's time zone.",
+ language="The requester's language.",
+ ),
+ },
+ "requester_groups": {
+ "description": "A group of requesters, used to scope access and automation.",
+ "docs_url": "https://api.freshservice.com/#requester-groups",
+ "columns": _columns(
+ name="The requester group's name.",
+ description="Description of the requester group.",
+ type="Type of the requester group (manual or rule_based).",
+ ),
+ },
+ "agents": {
+ "description": "A service desk agent who responds to and works on tickets.",
+ "docs_url": "https://api.freshservice.com/#agents",
+ "columns": _columns(
+ first_name="The agent's first name.",
+ last_name="The agent's last name.",
+ email="The agent's email address.",
+ occasional="Whether the agent is an occasional (vs. full-time) agent.",
+ active="Whether the agent is active.",
+ department_ids="IDs of the departments the agent belongs to.",
+ group_ids="IDs of the agent groups the agent belongs to.",
+ role_ids="IDs of the roles assigned to the agent.",
+ location_id="ID of the agent's location.",
+ time_zone="The agent's time zone.",
+ ),
+ },
+ "agent_groups": {
+ "description": "A group of agents that tickets can be assigned to.",
+ "docs_url": "https://api.freshservice.com/#groups",
+ "columns": _columns(
+ name="The group's name.",
+ description="Description of the group.",
+ agent_ids="IDs of the agents in the group.",
+ business_hours_id="ID of the business hours applied to the group.",
+ escalate_to="ID of the agent tickets escalate to.",
+ ),
+ },
+ "agent_roles": {
+ "description": "A role defining the set of privileges granted to agents.",
+ "docs_url": "https://api.freshservice.com/#roles",
+ "columns": _columns(
+ name="The role's name.",
+ description="Description of the role.",
+ default="Whether this is a default (system) role.",
+ ),
+ },
+ "assets": {
+ "description": "A configuration item (hardware, software, or other tracked asset) in the CMDB.",
+ "docs_url": "https://api.freshservice.com/#assets",
+ "columns": _columns(
+ display_id="Human-readable identifier for the asset.",
+ name="The asset's name.",
+ description="Description of the asset.",
+ asset_type_id="ID of the asset type.",
+ impact="Impact level of the asset (1=low, 2=medium, 3=high).",
+ usage_type="Usage type of the asset (loaner or permanent).",
+ user_id="ID of the user the asset is assigned to.",
+ department_id="ID of the department the asset belongs to.",
+ location_id="ID of the asset's location.",
+ agent_id="ID of the agent managing the asset.",
+ group_id="ID of the agent group managing the asset.",
+ ),
+ },
+ "asset_types": {
+ "description": "A classification for assets in the CMDB (e.g. Hardware, Software, Business Service).",
+ "docs_url": "https://api.freshservice.com/#asset-types",
+ "columns": _columns(
+ name="The asset type's name.",
+ description="Description of the asset type.",
+ parent_asset_type_id="ID of the parent asset type, if any.",
+ visible="Whether the asset type is visible.",
+ ),
+ },
+ "software": {
+ "description": "A software application tracked for software asset management.",
+ "docs_url": "https://api.freshservice.com/#software",
+ "columns": _columns(
+ name="The application's name.",
+ description="Description of the application.",
+ application_type="Type of application (desktop, saas, or mobile).",
+ status="Status of the application (blacklisted, ignored, or managed).",
+ publisher_id="ID of the application's publisher.",
+ managed_by_id="ID of the agent managing the application.",
+ category="Category of the application.",
+ ),
+ },
+ "purchase_orders": {
+ "description": "A purchase order for procuring assets or services.",
+ "docs_url": "https://api.freshservice.com/#purchase-order",
+ "columns": _columns(
+ name="Name of the purchase order.",
+ po_number="Purchase order number.",
+ vendor_id="ID of the vendor the order is placed with.",
+ status="Status of the purchase order (20=open, 25=ordered, 30=partially received, 35=received, 40=cancelled).",
+ department_id="ID of the department the order is for.",
+ expected_delivery_date="Expected delivery date.",
+ total_cost="Total cost of the purchase order.",
+ ),
+ },
+ "products": {
+ "description": "A product in the product catalog that assets can be associated with.",
+ "docs_url": "https://api.freshservice.com/#products",
+ "columns": _columns(
+ name="The product's name.",
+ description="Description of the product.",
+ asset_type_id="ID of the asset type the product maps to.",
+ manufacturer="Manufacturer of the product.",
+ status="Status of the product (In Production, In Pipeline, or Retired).",
+ ),
+ },
+ "vendors": {
+ "description": "A vendor or supplier that assets and purchase orders are associated with.",
+ "docs_url": "https://api.freshservice.com/#vendors",
+ "columns": _columns(
+ name="The vendor's name.",
+ description="Description of the vendor.",
+ primary_contact_id="ID of the vendor's primary contact.",
+ address="The vendor's address.",
+ ),
+ },
+ "locations": {
+ "description": "A physical location (site or office) that assets and users are associated with.",
+ "docs_url": "https://api.freshservice.com/#locations",
+ "columns": _columns(
+ name="The location's name.",
+ parent_location_id="ID of the parent location, if any.",
+ primary_contact_id="ID of the location's primary contact.",
+ address="The location's address.",
+ ),
+ },
+ "departments": {
+ "description": "A department that groups together requesters within the organization.",
+ "docs_url": "https://api.freshservice.com/#departments",
+ "columns": _columns(
+ name="The department's name.",
+ description="Description of the department.",
+ head_user_id="ID of the user who heads the department.",
+ prime_user_id="ID of the department's prime user.",
+ domains="Email domains associated with the department.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py
new file mode 100644
index 000000000000..fe37c046d609
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py
@@ -0,0 +1,216 @@
+import base64
+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 structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, 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.freshservice.settings import (
+ FRESHSERVICE_ENDPOINTS,
+ PER_PAGE,
+ FreshserviceEndpointConfig,
+)
+
+REQUEST_TIMEOUT = 60
+VALIDATE_TIMEOUT = 10
+MAX_RETRIES = 5
+MAX_RETRY_WAIT = 60.0
+
+_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT)
+
+
+class FreshserviceRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+def _parse_retry_after(value: str | None) -> float | None:
+ """Parse a Retry-After header. Freshservice sends an integer number of seconds on 429."""
+ if not value:
+ return None
+ try:
+ return float(value)
+ except ValueError:
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor a server-provided Retry-After (capped); otherwise fall back to exponential jitter."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, FreshserviceRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT)
+ return _EXPONENTIAL_WAIT(retry_state)
+
+
+class FreshserviceResumeConfig:
+ next_url: str
+
+
+def normalize_domain(domain: str) -> str:
+ """Accept either a bare subdomain ("acme") or a full host ("acme.freshservice.com")."""
+ domain = domain.strip().removeprefix("https://").removeprefix("http://")
+ domain = domain.split("/")[0]
+ return domain.removesuffix(".freshservice.com")
+
+
+def _base_url(domain: str) -> str:
+ return f"https://{normalize_domain(domain)}.freshservice.com"
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Freshservice uses HTTP Basic auth with the API key as the username and any
+ # non-empty string as the password.
+ token = base64.b64encode(f"{api_key}:X".encode("ascii")).decode("ascii")
+ return {"Authorization": f"Basic {token}", "Content-Type": "application/json"}
+
+
+def _format_updated_since(value: Any) -> str:
+ """Format an incremental cursor value as the ISO 8601 UTC string Freshservice expects."""
+ if isinstance(value, datetime):
+ utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def build_initial_url(
+ domain: str,
+ config: FreshserviceEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> str:
+ params: dict[str, str] = {"per_page": str(PER_PAGE)}
+ params.update(config.extra_params)
+
+ if should_use_incremental_field and config.updated_since_param and db_incremental_field_last_value:
+ params[config.updated_since_param] = _format_updated_since(db_incremental_field_last_value)
+
+ return f"{_base_url(domain)}{config.path}?{urlencode(params)}"
+
+
+def extract_items(data: Any, config: FreshserviceEndpointConfig) -> list[dict]:
+ """Every Freshservice v2 list endpoint wraps its results under a resource-named key
+ (e.g. {"tickets": [...]}). Fall back to a bare array defensively."""
+ if isinstance(data, dict):
+ if isinstance(data.get(config.data_key), list):
+ return data[config.data_key]
+ return []
+ if isinstance(data, list):
+ return data
+ return []
+
+
+def get_rows(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict]]:
+ config = FRESHSERVICE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ url: Optional[str] = resume.next_url
+ logger.debug(f"Freshservice: resuming from URL: {url}")
+ else:
+ url = build_initial_url(domain, config, should_use_incremental_field, db_incremental_field_last_value)
+
+ @retry(
+ retry=retry_if_exception_type((FreshserviceRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> tuple[Any, Optional[str]]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT)
+
+ # Freshservice throttles with 429 and a Retry-After header; honor it when present.
+ if response.status_code == 429:
+ raise FreshserviceRetryableError(
+ f"Freshservice API rate limited: url={page_url}",
+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),
+ )
+
+ # Transient upstream issues surface as 5xx.
+ if response.status_code >= 500:
+ raise FreshserviceRetryableError(
+ f"Freshservice API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Freshservice API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ next_url = response.links.get("next", {}).get("url")
+ return response.json(), next_url
+
+ while url:
+ data, next_url = fetch_page(url)
+
+ items = extract_items(data, config)
+ if items:
+ yield items
+
+ if not next_url:
+ break
+
+ # Save state AFTER yielding so a crash re-yields the last page (merge dedupes on
+ # primary key) rather than skipping it.
+ resumable_source_manager.save_state(FreshserviceResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def freshservice_source(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FRESHSERVICE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ domain=domain,
+ 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=["id"],
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(domain: str, api_key: str) -> Optional[int]:
+ """Probe the Freshservice API. Returns the HTTP status code, or ``None`` on a connection error."""
+ url = f"{_base_url(domain)}/api/v2/tickets?per_page=1"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=VALIDATE_TIMEOUT)
+ except Exception:
+ return None
+
+ return response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/settings.py
new file mode 100644
index 000000000000..a35690b5e9b8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/settings.py
@@ -0,0 +1,155 @@
+"""Freshservice source settings and endpoint catalog."""
+
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+PER_PAGE = 100
+
+
+@dataclass
+class FreshserviceEndpointConfig:
+ name: str
+ path: str
+ # Key the list lives under in the response envelope. Every Freshservice v2 list
+ # endpoint wraps its results in a resource-named object (e.g. {"tickets": [...]}),
+ # unlike Freshdesk which returns bare arrays for most endpoints.
+ data_key: str
+ # Server-side incremental filter param name (e.g. "updated_since"). ``None`` means the
+ # endpoint has no server-side timestamp filter -> full refresh only.
+ updated_since_param: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Stable field used for datetime partitioning. Always a creation timestamp, never a
+ # mutable field like ``updated_at`` (partitions must not rewrite on every sync).
+ partition_key: Optional[str] = None
+ # Extra static query params (e.g. ordering on incremental endpoints).
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+# Top-level Freshservice v2 endpoints. Fan-out resources (ticket conversations, solution
+# articles/folders/categories) and webhook-driven deltas are intentionally left out of this
+# first cut — see source.py module note.
+FRESHSERVICE_ENDPOINTS: dict[str, FreshserviceEndpointConfig] = {
+ "tickets": FreshserviceEndpointConfig(
+ name="tickets",
+ path="/api/v2/tickets",
+ data_key="tickets",
+ # The tickets list is the only Freshservice endpoint that documents a server-side
+ # `updated_since` filter. Syncing incrementally on it keeps each window small and lets
+ # the watermark advance across runs, which is also how you page past the deep-pagination
+ # slowdown (Freshservice discourages paging beyond page 500).
+ updated_since_param="updated_since",
+ default_incremental_field="updated_at",
+ incremental_fields=[_datetime_incremental_field("updated_at")],
+ partition_key="created_at",
+ # Force ascending updated_at so the incremental watermark advances monotonically and the
+ # declared sort_mode="asc" is honest. NOTE: this ordering could not be curl-verified against
+ # a live Freshservice account (no credentials); it mirrors the reviewed Freshdesk sibling
+ # source, whose v2 API is near-identical. Freshworks APIs ignore unknown query params rather
+ # than rejecting them, so an unsupported `order_by` degrades to the API default, not a 400.
+ extra_params={"order_by": "updated_at", "order_type": "asc"},
+ ),
+ "problems": FreshserviceEndpointConfig(
+ name="problems",
+ path="/api/v2/problems",
+ data_key="problems",
+ partition_key="created_at",
+ ),
+ "changes": FreshserviceEndpointConfig(
+ name="changes",
+ path="/api/v2/changes",
+ data_key="changes",
+ partition_key="created_at",
+ ),
+ "releases": FreshserviceEndpointConfig(
+ name="releases",
+ path="/api/v2/releases",
+ data_key="releases",
+ partition_key="created_at",
+ ),
+ "requesters": FreshserviceEndpointConfig(
+ name="requesters",
+ path="/api/v2/requesters",
+ data_key="requesters",
+ partition_key="created_at",
+ ),
+ "requester_groups": FreshserviceEndpointConfig(
+ name="requester_groups",
+ path="/api/v2/requester_groups",
+ data_key="requester_groups",
+ ),
+ "agents": FreshserviceEndpointConfig(
+ name="agents",
+ path="/api/v2/agents",
+ data_key="agents",
+ ),
+ "agent_groups": FreshserviceEndpointConfig(
+ name="agent_groups",
+ path="/api/v2/groups",
+ data_key="groups",
+ ),
+ "agent_roles": FreshserviceEndpointConfig(
+ name="agent_roles",
+ path="/api/v2/roles",
+ data_key="roles",
+ ),
+ "assets": FreshserviceEndpointConfig(
+ name="assets",
+ path="/api/v2/assets",
+ data_key="assets",
+ partition_key="created_at",
+ ),
+ "asset_types": FreshserviceEndpointConfig(
+ name="asset_types",
+ path="/api/v2/asset_types",
+ data_key="asset_types",
+ ),
+ "software": FreshserviceEndpointConfig(
+ name="software",
+ path="/api/v2/applications",
+ data_key="applications",
+ ),
+ "purchase_orders": FreshserviceEndpointConfig(
+ name="purchase_orders",
+ path="/api/v2/purchase_orders",
+ data_key="purchase_orders",
+ partition_key="created_at",
+ ),
+ "products": FreshserviceEndpointConfig(
+ name="products",
+ path="/api/v2/products",
+ data_key="products",
+ ),
+ "vendors": FreshserviceEndpointConfig(
+ name="vendors",
+ path="/api/v2/vendors",
+ data_key="vendors",
+ ),
+ "locations": FreshserviceEndpointConfig(
+ name="locations",
+ path="/api/v2/locations",
+ data_key="locations",
+ ),
+ "departments": FreshserviceEndpointConfig(
+ name="departments",
+ path="/api/v2/departments",
+ data_key="departments",
+ ),
+}
+
+ENDPOINTS = tuple(FRESHSERVICE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FRESHSERVICE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/source.py
index 0a126d28c002..d871837198c3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/source.py
@@ -1,30 +1,183 @@
-from typing import cast
+import re
+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.freshservice.freshservice import (
+ FreshserviceResumeConfig,
+ freshservice_source,
+ normalize_domain,
+ validate_credentials as validate_freshservice_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.settings import (
+ FRESHSERVICE_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshserviceSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# This first cut covers Freshservice's top-level v2 endpoints only. Fan-out resources
+# (ticket conversations, solution articles/folders/categories) and webhook-driven deltas
+# are deliberately left out: Freshservice has no documented public REST API for programmatic
+# webhook management (webhooks are configured manually as Workflow Automator outbound web
+# requests), so they can't be wired up reliably without live verification.
+
+_DOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")
+
@SourceRegistry.register
-class FreshserviceSource(SimpleSource[FreshserviceSourceConfig]):
+class FreshserviceSource(ResumableSource[FreshserviceSourceConfig, FreshserviceResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRESHSERVICE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # Freshservice's connection target is the domain, not a `host` field. Editing it on an
+ # existing source must force the API key to be re-entered.
+ return ["domain"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Freshservice authentication failed. Please check your API key and domain.",
+ "403 Client Error: Forbidden for url": "Your Freshservice API key does not have permission for this resource. Check the agent's role/scope.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FRESHSERVICE,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Freshservice",
+ caption="""Enter your Freshservice domain and API key to pull your Freshservice ITSM data into the PostHog Data warehouse.
+
+Your **domain** is the subdomain in your Freshservice URL — e.g. `acme` for `acme.freshservice.com`.
+
+Your **API key** is on your Freshservice profile settings page (click your profile picture → **Profile settings**; the API key is shown in the right sidebar).""",
iconPath="/static/services/freshservice.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/freshservice",
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Kept hidden while the connector's incremental/ordering behavior is verified against a
+ # live Freshservice account. Drop this flag to release the source to users.
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="domain",
+ label="Freshservice domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: FreshserviceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=name,
+ # Only the endpoints with a genuine server-side `updated_since` filter
+ # support incremental sync; everything else is full refresh.
+ supports_incremental=endpoint.updated_since_param is not None,
+ supports_append=endpoint.updated_since_param is not None,
+ incremental_fields=endpoint.incremental_fields,
+ )
+ for name, endpoint in FRESHSERVICE_ENDPOINTS.items()
+ ]
+ 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: FreshserviceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if not _DOMAIN_REGEX.match(normalize_domain(config.domain)):
+ return False, "Freshservice domain is invalid"
+
+ status = validate_freshservice_credentials(config.domain, config.api_key)
+
+ if status == 200:
+ return True, None
+
+ # A valid key that simply lacks scope for the probe endpoint returns 403. Accept it at
+ # source-create (schema_name is None) — users may only grant the scopes they want to sync.
+ if status == 403 and schema_name is None:
+ return True, None
+
+ # schema_name is set: a 403 means the key lacks permission for this specific resource.
+ if status == 403:
+ return (
+ False,
+ "Your Freshservice API key does not have permission for this resource. Check the agent's role/scope.",
+ )
+
+ if status == 401:
+ return False, "Freshservice authentication failed. Please check your API key and domain."
+
+ return False, "Could not connect to Freshservice. Please check your domain and API key."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FreshserviceResumeConfig]:
+ return ResumableSourceManager[FreshserviceResumeConfig](inputs, FreshserviceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FreshserviceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return freshservice_source(
+ api_key=config.api_key,
+ domain=config.domain,
+ 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/freshservice/tests/test_freshservice.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/tests/test_freshservice.py
new file mode 100644
index 000000000000..e6d335f81d0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/tests/test_freshservice.py
@@ -0,0 +1,229 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.freshservice import (
+ FreshserviceResumeConfig,
+ _format_updated_since,
+ _parse_retry_after,
+ build_initial_url,
+ extract_items,
+ get_rows,
+ normalize_domain,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.settings import (
+ FRESHSERVICE_ENDPOINTS,
+)
+
+logger = structlog.get_logger()
+
+PATCH_SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.freshservice.make_tracked_session"
+)
+
+
+class FakeResponse:
+ def __init__(
+ self,
+ json_data: Any = None,
+ status_code: int = 200,
+ links: Optional[dict] = None,
+ text: str = "",
+ headers: Optional[dict] = None,
+ ) -> None:
+ self._json = json_data
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 400
+ self.links = links or {}
+ self.text = text
+ self.headers = headers or {}
+
+ def json(self) -> Any:
+ return self._json
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ real_response = requests.Response()
+ real_response.status_code = self.status_code
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=real_response)
+
+
+class FakeResumableManager:
+ def __init__(self, resume: Optional[FreshserviceResumeConfig] = None) -> None:
+ self._resume = resume
+ self.saved: list[FreshserviceResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume is not None
+
+ def load_state(self) -> Optional[FreshserviceResumeConfig]:
+ return self._resume
+
+ def save_state(self, data: FreshserviceResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestNormalizeDomain:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("acme", "acme"),
+ ("acme.freshservice.com", "acme"),
+ ("https://acme.freshservice.com", "acme"),
+ ("http://acme.freshservice.com/", "acme"),
+ (" acme ", "acme"),
+ ("acme.freshservice.com/a/tickets", "acme"),
+ ],
+ )
+ def test_normalize_domain(self, raw: str, expected: str) -> None:
+ assert normalize_domain(raw) == expected
+
+
+class TestFormatUpdatedSince:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("some-cursor", "some-cursor"),
+ ],
+ )
+ def test_format_updated_since(self, value: Any, expected: str) -> None:
+ assert _format_updated_since(value) == expected
+
+ def test_no_offset_suffix(self) -> None:
+ assert "+00:00" not in _format_updated_since(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestParseRetryAfter:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("30", 30.0),
+ ("0", 0.0),
+ (None, None),
+ ("", None),
+ ("not-a-number", None),
+ ],
+ )
+ def test_parse_retry_after(self, value: Optional[str], expected: Optional[float]) -> None:
+ assert _parse_retry_after(value) == expected
+
+
+class TestBuildInitialUrl:
+ def test_full_refresh_has_per_page_only(self) -> None:
+ url = build_initial_url("acme", FRESHSERVICE_ENDPOINTS["agents"], False, None)
+ assert url.startswith("https://acme.freshservice.com/api/v2/agents?")
+ assert "per_page=100" in url
+ assert "updated_since" not in url
+
+ def test_tickets_incremental_uses_updated_since_and_ordering(self) -> None:
+ url = build_initial_url("acme", FRESHSERVICE_ENDPOINTS["tickets"], True, datetime(2026, 3, 4, tzinfo=UTC))
+ assert "updated_since=2026-03-04T00%3A00%3A00Z" in url
+ assert "order_by=updated_at" in url
+ assert "order_type=asc" in url
+
+ def test_incremental_without_last_value_omits_filter(self) -> None:
+ url = build_initial_url("acme", FRESHSERVICE_ENDPOINTS["tickets"], True, None)
+ assert "updated_since" not in url
+
+ def test_full_refresh_endpoint_ignores_incremental_flag(self) -> None:
+ # `problems` has no server-side filter, so it never gets an updated_since param even when
+ # the pipeline requests incremental.
+ url = build_initial_url("acme", FRESHSERVICE_ENDPOINTS["problems"], True, datetime(2026, 3, 4, tzinfo=UTC))
+ assert "updated_since" not in url
+
+
+class TestExtractItems:
+ def test_unwraps_resource_envelope(self) -> None:
+ assert extract_items({"tickets": [{"id": 1}]}, FRESHSERVICE_ENDPOINTS["tickets"]) == [{"id": 1}]
+
+ def test_software_uses_applications_key(self) -> None:
+ # The software table maps to /api/v2/applications, which wraps rows under "applications".
+ assert extract_items({"applications": [{"id": 7}]}, FRESHSERVICE_ENDPOINTS["software"]) == [{"id": 7}]
+
+ def test_agent_groups_uses_groups_key(self) -> None:
+ assert extract_items({"groups": [{"id": 3}]}, FRESHSERVICE_ENDPOINTS["agent_groups"]) == [{"id": 3}]
+
+ def test_wrong_key_returns_empty(self) -> None:
+ assert extract_items({"problems": [{"id": 1}]}, FRESHSERVICE_ENDPOINTS["tickets"]) == []
+
+ def test_bare_array_fallback(self) -> None:
+ assert extract_items([{"id": 1}], FRESHSERVICE_ENDPOINTS["tickets"]) == [{"id": 1}]
+
+
+class TestGetRows:
+ def test_paginates_via_link_header_and_saves_state(self) -> None:
+ next_url = "https://acme.freshservice.com/api/v2/tickets?per_page=100&page=2"
+ responses = [
+ FakeResponse({"tickets": [{"id": 1}]}, links={"next": {"url": next_url}}),
+ FakeResponse({"tickets": [{"id": 2}]}, links={}),
+ ]
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 1}], [{"id": 2}]]
+ # State saved once, after the first (only non-terminal) page.
+ assert manager.saved == [FreshserviceResumeConfig(next_url=next_url)]
+
+ def test_single_page_saves_no_state(self) -> None:
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse({"agents": [{"id": 1}]}, links={})]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme", "agents", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 1}]]
+ assert manager.saved == []
+
+ def test_resumes_from_saved_state(self) -> None:
+ resume_url = "https://acme.freshservice.com/api/v2/tickets?per_page=100&page=5"
+ manager = FakeResumableManager(resume=FreshserviceResumeConfig(next_url=resume_url))
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse({"tickets": [{"id": 50}]}, links={})]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ rows = list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]
+
+ assert rows == [[{"id": 50}]]
+ # First request must hit the resumed URL, not a freshly-built initial URL.
+ assert session.get.call_args_list[0].args[0] == resume_url
+
+ @pytest.mark.parametrize("status_code", [401, 403, 404])
+ def test_non_retryable_status_raises(self, status_code: int) -> None:
+ manager = FakeResumableManager()
+ session = mock.MagicMock()
+ session.get.side_effect = [FakeResponse(status_code=status_code, text="boom")]
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("key", "acme", "tickets", logger, manager)) # type: ignore[arg-type]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code", [200, 401, 403])
+ def test_returns_status_code(self, status_code: int) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = FakeResponse(status_code=status_code)
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ assert validate_credentials("acme", "key") == status_code
+
+ def test_connection_error_returns_none(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("nope")
+
+ with mock.patch(PATCH_SESSION, return_value=session):
+ assert validate_credentials("acme", "key") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/tests/test_freshservice_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/tests/test_freshservice_source.py
new file mode 100644
index 000000000000..5f298e1cab97
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/tests/test_freshservice_source.py
@@ -0,0 +1,152 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+import structlog
+
+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.freshservice.freshservice import (
+ FreshserviceResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.source import FreshserviceSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshserviceSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+PATCH_VALIDATE = "products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.source.validate_freshservice_credentials"
+
+
+def _make_inputs(schema_name: str = "tickets") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ 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=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestFreshserviceSource:
+ def setup_method(self) -> None:
+ self.source = FreshserviceSource()
+ self.team_id = 1
+ self.config = FreshserviceSourceConfig(domain="acme", api_key="key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FRESHSERVICE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Freshservice"
+ assert config.label == "Freshservice"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/freshservice.png"
+
+ fields = config.fields
+ assert len(fields) == 2
+ domain_field, api_key_field = fields
+ assert isinstance(domain_field, SourceFieldInputConfig)
+ assert domain_field.name == "domain"
+ assert domain_field.type == SourceFieldInputConfigType.TEXT
+ assert domain_field.secret is False
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error: Forbidden for url"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "name, supports_incremental",
+ [
+ ("tickets", True),
+ ("problems", False),
+ ("changes", False),
+ ("agents", False),
+ ("assets", False),
+ ("software", False),
+ ],
+ )
+ def test_schema_incremental_support(self, name: str, supports_incremental: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ schema = schemas[name]
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_incremental
+ if supports_incremental:
+ assert [f["field"] for f in schema.incremental_fields] == ["updated_at"]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tickets"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tickets"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "domain, status, schema_name, expected_valid",
+ [
+ ("acme", 200, None, True),
+ ("acme", 403, None, True), # missing scope at source-create is accepted
+ ("acme", 403, "tickets", False), # missing scope for a specific schema fails
+ ("acme", 401, None, False),
+ ("acme", None, None, False), # connection error
+ ("invalid domain!", 200, None, False), # domain regex rejects before probing
+ ],
+ )
+ def test_validate_credentials(
+ self, domain: str, status: Optional[int], schema_name: Optional[str], expected_valid: bool
+ ) -> None:
+ config = FreshserviceSourceConfig(domain=domain, api_key="key")
+ with mock.patch(PATCH_VALIDATE, return_value=status) as mock_validate:
+ is_valid, _ = self.source.validate_credentials(config, self.team_id, schema_name)
+
+ assert is_valid is expected_valid
+ if "!" in domain or " " in domain:
+ mock_validate.assert_not_called()
+
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FreshserviceResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = _make_inputs("tickets")
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert response.name == "tickets"
+ assert response.primary_keys == ["id"]
+ # tickets partitions on its stable created_at field.
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+
+ def test_source_for_pipeline_full_refresh_endpoint_has_no_partition(self) -> None:
+ inputs = _make_inputs("agents")
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert response.name == "agents"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
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 a6f3629c1b79..030a882424e2 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
@@ -1273,7 +1273,8 @@ class FreshsalesSourceConfig(config.Config):
@config.config
class FreshserviceSourceConfig(config.Config):
- pass
+ domain: str
+ api_key: str
@config.config