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): add contract, CMDB and software tables to freshservice (#108301)

Tom Owersf31f8f11b9e6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 41d2c30a2d3e..928cfadbe0dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3397,15 +3397,15 @@ Note: The `/api/selector/\*` family is a set of ~18 small lookup collections (al
## Freshservice — gaps
-Today (17): `agent_groups`, `agent_roles`, `agents`, `asset_types`, `assets`, `changes`, `departments`, `locations`, `problems`, `products`, `purchase_orders`, `releases`, `requester_groups`, `requesters`, `software`, `tickets`, `vendors`
+Today (24): `agent_groups`, `agent_roles`, `agents`, `asset_types`, `assets`, `changes`, `contract_types`, `contracts`, `departments`, `locations`, `problems`, `products`, `purchase_orders`, `relationship_types`, `relationships`, `releases`, `requester_groups`, `requesters`, `software`, `software_installations`, `software_users`, `ticket_time_entries`, `tickets`, `vendors`
Diffed against: <https://api.freshservice.com/>
- [ ] `tickets/{id}/conversations` — the actual reply and note bodies on every ticket — required for any response-content or agent-activity analysis (high)
-- [ ] `tickets/{id}/time_entries` — time tracked per ticket, the basis of effort and cost-per-ticket reporting (high)
-- [ ] `contracts (+ contract_types lookup)` — asset/vendor contracts with cost and renewal dates; contract_types resolves the type ID carried on each contract (high)
-- [ ] `applications/{id}/users and /installations (software users, software installations)` — membership tables joining the software we already sync to users and devices — license utilization is impossible without them (high)
-- [ ] `assets/{id}/relationships (+ relationship_types lookup)` — the CMDB dependency graph plus the lookup that names each relationship type (high)
+- [x] `tickets/{id}/time_entries` — time tracked per ticket, the basis of effort and cost-per-ticket reporting (high)
+- [x] `contracts (+ contract_types lookup)` — asset/vendor contracts with cost and renewal dates; contract_types resolves the type ID carried on each contract (high)
+- [x] `applications/{id}/users and /installations (software users, software installations)` — membership tables joining the software we already sync to users and devices — license utilization is impossible without them (high)
+- [x] `assets/{id}/relationships (+ relationship_types lookup)` — the CMDB dependency graph plus the lookup that names each relationship type (high) — synced through the account-wide `/api/v2/relationships` listing, which returns the same edges without fanning out per asset
- [ ] `sla_policies` — lookup that resolves the SLA policy ID on tickets into targets and escalation rules (medium)
- [ ] `tickets/{id}/tasks (and problem/change/release tasks)` — sub-task breakdown and completion state under each ticket (medium)
- [ ] `approvals` — account-wide approval records with approver, state and timestamps — the service-request bottleneck metric (medium)
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
index efa21224244f..dc91669c67ba 100644
--- 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
@@ -254,4 +254,112 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
domains="Email domains associated with the department.",
),
},
+ "contracts": {
+ "description": "A contract covering assets, software or vendor services, with its cost, term and renewal settings.",
+ "docs_url": "https://api.freshservice.com/#contracts",
+ "columns": _columns(
+ name="Name of the contract.",
+ description="Description of the contract.",
+ vendor_id="ID of the vendor the contract is with.",
+ contract_number="Contract number as recorded in Freshservice.",
+ contract_type_id="ID of the contract type, resolvable against the contract_types table.",
+ status="Status of the contract (draft, pending approval, approved, active, expired, terminated or rejected).",
+ start_date="Date the contract starts.",
+ end_date="Date the contract expires.",
+ cost="Total cost of the contract.",
+ auto_renew="Whether the contract renews automatically on expiry.",
+ notify_expiry="Whether expiry notifications are sent for the contract.",
+ notify_before="Number of days before expiry that the notification is sent.",
+ approver_id="ID of the agent who approves the contract.",
+ requester_id="ID of the user who requested the contract.",
+ delegatee_id="ID of the user contract approval is delegated to.",
+ visible_to_id="ID of the agent group the contract is visible to.",
+ notify_to="Email addresses notified about the contract.",
+ software_id="ID of the software the contract licenses, for software contracts.",
+ license_type="License type for a software contract (volume, enterprise, trial, open_source or free).",
+ billing_cycle="Term period of a software contract (monthly, quarterly, half_yearly, annual or one_time).",
+ item_cost_details="Line items on the contract, each with its own name, cost, count and pricing model.",
+ future_contract_id="ID of the contract that takes over when this one expires.",
+ has_associated_assets="Whether assets are associated with the contract.",
+ has_attachments="Whether the contract carries attachments.",
+ expiry_notified="Whether the expiry notification has already been sent.",
+ workspace_id="ID of the workspace the contract belongs to.",
+ ),
+ },
+ "contract_types": {
+ "description": "A contract type, resolving the contract_type_id carried on each contract.",
+ "docs_url": "https://api.freshservice.com/#contract_types",
+ "columns": _columns(
+ name="Name of the contract type.",
+ description="Description of the contract type.",
+ needs_approval="Whether contracts of this type need approval.",
+ is_default="Whether this is a built-in type rather than a custom one.",
+ ),
+ },
+ "relationships": {
+ "description": "One edge of the CMDB dependency graph, linking two records such as assets, agents, requesters, departments or software.",
+ "docs_url": "https://api.freshservice.com/#relationships",
+ "columns": _columns(
+ relationship_type_id="ID of the relationship type, resolvable against the relationship_types table.",
+ primary_id="ID of the record the relationship points from.",
+ primary_type="Kind of the record the relationship points from (asset, requester, agent, department or software).",
+ secondary_id="ID of the record the relationship points to.",
+ secondary_type="Kind of the record the relationship points to (asset, requester, agent, department or software).",
+ ),
+ },
+ "relationship_types": {
+ "description": "A relationship type, naming both directions of the edges in the CMDB dependency graph.",
+ "docs_url": "https://api.freshservice.com/#relationship_types",
+ "columns": _columns(
+ description="Description of the relationship type.",
+ is_default="Whether this is a built-in type rather than a custom one.",
+ downstream_relation="Label for the relationship read from the primary record to the secondary one.",
+ upstream_relation="Label for the relationship read from the secondary record back to the primary one.",
+ downstream_impact="Whether a change to the primary record impacts the secondary one.",
+ upstream_impact="Whether a change to the secondary record impacts the primary one.",
+ ),
+ },
+ "software_users": {
+ "description": "A user of a piece of software, with the license allocated to them and when they last used it.",
+ "docs_url": "https://api.freshservice.com/#software-users",
+ "columns": _columns(
+ application_id="ID of the software the user is attached to, injected from the parent application.",
+ user_id="ID of the user using the software.",
+ license_id="Display ID of the software license contract allocated to the user.",
+ allocated_date="Time at which the license was allocated.",
+ first_used="Time at which the user first used the software.",
+ last_used="Time at which the user last used the software.",
+ source="Where the user record came from (API, Okta, Google and so on).",
+ ),
+ },
+ "software_installations": {
+ "description": "An installation of a piece of software on a device.",
+ "docs_url": "https://api.freshservice.com/#software-installations",
+ "columns": _columns(
+ application_id="ID of the software installed, injected from the parent application.",
+ installation_machine_id="Display ID of the device the software is installed on.",
+ installation_path="Path the software is installed at.",
+ version="Version of the installed software.",
+ user_id="ID of the user of the device.",
+ department_id="ID of the department the device belongs to.",
+ installation_date="Time at which the software was installed.",
+ ),
+ },
+ "ticket_time_entries": {
+ "description": "Time tracked by an agent against a ticket.",
+ "docs_url": "https://api.freshservice.com/#time-entries",
+ "columns": _columns(
+ ticket_id="ID of the ticket the time was tracked against, injected from the parent ticket.",
+ agent_id="ID of the agent the time entry is assigned to.",
+ task_id="ID of the ticket task the time entry is assigned to.",
+ time_spent="Time spent, in hh:mm.",
+ timer_running="Whether the timer is still running.",
+ billable="Whether the time entry is billable.",
+ start_time="Time at which the timer was started.",
+ executed_at="Time at which the work was carried out.",
+ note="Description of the time entry.",
+ workspace_id="ID of the workspace the time entry belongs to.",
+ custom_fields="Values of the account's custom time-entry fields.",
+ ),
+ },
}
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
index 398e692c4a02..a765f4ac930d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/freshservice.py
@@ -1,23 +1,29 @@
-import dataclasses
+from collections.abc import Iterable
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from requests.auth import HTTPBasicAuth
+from posthog.dataclasses import frozen
+
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.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
HeaderLinkPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.freshservice.settings import (
FRESHSERVICE_ENDPOINTS,
- PER_PAGE,
+ FreshserviceEndpointConfig,
)
VALIDATE_TIMEOUT = 10
@@ -27,9 +33,15 @@ VALIDATE_TIMEOUT = 10
_BASIC_AUTH_PASSWORD = "X"
+@frozen
class FreshserviceResumeConfig:
- next_url: str
+ # Top-level endpoints resume from the opaque Link-header `next` URL.
+ next_url: Optional[str] = None
+ # Fan-out endpoints resume by parent: the child paths already swept, the one in progress,
+ # and that path's paginator state — see `common.rest_source.__init__`.
+ completed: Optional[list[str]] = None
+ current: Optional[str] = None
+ child_state: Optional[dict[str, Any]] = None
def normalize_domain(domain: str) -> str:
@@ -53,19 +65,47 @@ def _format_updated_since(value: Any) -> str:
return str(value)
-def freshservice_source(
- api_key: str,
+def _client_config(domain: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": _base_url(domain),
+ "headers": {"Content-Type": "application/json"},
+ # Auth (HTTP Basic) is supplied via the framework auth config so the credential is
+ # redacted from logs rather than hand-built into an Authorization header.
+ "auth": {"type": "http_basic", "username": api_key, "password": _BASIC_AUTH_PASSWORD},
+ # Freshservice v2 paginates via RFC 5988 Link headers (rel="next").
+ "paginator": HeaderLinkPaginator(),
+ }
+
+
+def _make_source_response(
+ config: FreshserviceEndpointConfig,
+ items: Any,
+ column_hints: Optional[dict[str, Any]] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_keys,
+ 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,
+ column_hints=column_hints,
+ )
+
+
+def _top_level_source(
+ config: FreshserviceEndpointConfig,
domain: str,
- endpoint: str,
+ api_key: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
) -> SourceResponse:
- config = FRESHSERVICE_ENDPOINTS[endpoint]
-
- params: dict[str, Any] = {"per_page": PER_PAGE}
+ params: dict[str, Any] = {"per_page": config.page_size}
params.update(config.extra_params)
# Server-side incremental filter: only endpoints with a documented `updated_since` param
# narrow the window, and only once a watermark exists.
@@ -73,18 +113,10 @@ def freshservice_source(
params[config.updated_since_param] = _format_updated_since(db_incremental_field_last_value)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(domain),
- "headers": {"Content-Type": "application/json"},
- # Auth (HTTP Basic) is supplied via the framework auth config so the credential is
- # redacted from logs rather than hand-built into an Authorization header.
- "auth": {"type": "http_basic", "username": api_key, "password": _BASIC_AUTH_PASSWORD},
- # Freshservice v2 paginates via RFC 5988 Link headers (rel="next").
- "paginator": HeaderLinkPaginator(),
- },
+ "client": _client_config(domain, api_key),
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
"params": params,
@@ -99,7 +131,7 @@ def freshservice_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
- if resume is not None:
+ if resume is not None and resume.next_url:
initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -117,16 +149,86 @@ def freshservice_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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,
- column_hints=resource.column_hints,
+ return _make_source_response(config, lambda: resource, column_hints=resource.column_hints)
+
+
+def _fanout_source(
+ config: FreshserviceEndpointConfig,
+ domain: str,
+ api_key: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
+) -> SourceResponse:
+ assert config.fanout is not None
+ parent_config = FRESHSERVICE_ENDPOINTS[config.fanout.parent_name]
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ FreshserviceResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=FRESHSERVICE_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=_client_config(domain, api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector": parent_config.data_key},
+ child_endpoint_extra={"data_selector": config.data_key},
+ page_size_param="per_page",
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+
+ return _make_source_response(config, lambda: dependent_resource)
+
+
+def freshservice_source(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[FreshserviceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FRESHSERVICE_ENDPOINTS[endpoint]
+
+ if config.fanout is not None:
+ return _fanout_source(config, domain, api_key, team_id, job_id, resumable_source_manager)
+
+ return _top_level_source(
+ config,
+ domain,
+ api_key,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
)
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
index a35690b5e9b8..49c41465527e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshservice/settings.py
@@ -3,12 +3,47 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
PER_PAGE = 100
+# Freshservice's ticket listing only returns the last 30 days unless `updated_since` is set, so
+# the time-entry fan-out asks for everything from the epoch — a sweep of every ticket's time
+# entries has to visit every ticket, not just the recent ones.
+_ALL_TICKETS_SINCE = "1970-01-01T00:00:00Z"
-@dataclass
+# A ticket or application can be deleted between the parent listing and the child fetch; treat
+# that 404 as an empty child rather than failing the whole sweep.
+_IGNORE_MISSING_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+_SOFTWARE_FANOUT = DependentEndpointConfig(
+ parent_name="software",
+ resolve_param="application_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "application_id"},
+ child_response_actions=_IGNORE_MISSING_PARENT,
+)
+
+_TICKET_FANOUT = DependentEndpointConfig(
+ parent_name="tickets",
+ resolve_param="ticket_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "ticket_id"},
+ parent_params={"updated_since": _ALL_TICKETS_SINCE, "order_by": "updated_at", "order_type": "asc"},
+ child_response_actions=_IGNORE_MISSING_PARENT,
+)
+
+
+# Mutable by choice: instances flow into `build_dependent_resource`'s
+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's
+# fields as read-only, which is incompatible with that Protocol's plain attributes.
+@dataclass(frozen=False)
class FreshserviceEndpointConfig:
name: str
path: str
@@ -26,6 +61,10 @@ class FreshserviceEndpointConfig:
partition_key: Optional[str] = None
# Extra static query params (e.g. ordering on incremental endpoints).
extra_params: dict[str, str] = field(default_factory=dict)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ page_size: int = PER_PAGE
+ # Set when the endpoint is a sub-resource reached by iterating a parent listing.
+ fanout: Optional[DependentEndpointConfig] = None
def _datetime_incremental_field(name: str) -> IncrementalField:
@@ -37,9 +76,8 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-# 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 v2 endpoints. Most are top-level listings; the ones carrying a `fanout` config
+# are sub-resources reached by iterating their parent listing.
FRESHSERVICE_ENDPOINTS: dict[str, FreshserviceEndpointConfig] = {
"tickets": FreshserviceEndpointConfig(
name="tickets",
@@ -146,6 +184,58 @@ FRESHSERVICE_ENDPOINTS: dict[str, FreshserviceEndpointConfig] = {
path="/api/v2/departments",
data_key="departments",
),
+ "contracts": FreshserviceEndpointConfig(
+ name="contracts",
+ path="/api/v2/contracts",
+ data_key="contracts",
+ partition_key="created_at",
+ ),
+ "contract_types": FreshserviceEndpointConfig(
+ name="contract_types",
+ path="/api/v2/contract_types",
+ data_key="contract_types",
+ ),
+ # The account-wide listing, rather than the per-asset one: it returns the same edges plus
+ # those anchored on agents, requesters, departments and software, without fanning out.
+ "relationships": FreshserviceEndpointConfig(
+ name="relationships",
+ path="/api/v2/relationships",
+ data_key="relationships",
+ partition_key="created_at",
+ ),
+ "relationship_types": FreshserviceEndpointConfig(
+ name="relationship_types",
+ path="/api/v2/relationship_types",
+ data_key="relationship_types",
+ ),
+ # `id` is documented as unique per application user, not across applications, so the parent
+ # id stays in the key.
+ "software_users": FreshserviceEndpointConfig(
+ name="software_users",
+ path="/api/v2/applications/{application_id}/users",
+ data_key="application_users",
+ partition_key="created_at",
+ primary_keys=["application_id", "id"],
+ fanout=_SOFTWARE_FANOUT,
+ ),
+ "software_installations": FreshserviceEndpointConfig(
+ name="software_installations",
+ path="/api/v2/applications/{application_id}/installations",
+ data_key="installations",
+ partition_key="created_at",
+ primary_keys=["application_id", "id"],
+ fanout=_SOFTWARE_FANOUT,
+ ),
+ # Time entries have no server-side timestamp filter of their own, so this table is full
+ # refresh only; the row carries no ticket reference either, hence the injected `ticket_id`.
+ "ticket_time_entries": FreshserviceEndpointConfig(
+ name="ticket_time_entries",
+ path="/api/v2/tickets/{ticket_id}/time_entries",
+ data_key="time_entries",
+ partition_key="created_at",
+ primary_keys=["ticket_id", "id"],
+ fanout=_TICKET_FANOUT,
+ ),
}
ENDPOINTS = tuple(FRESHSERVICE_ENDPOINTS.keys())
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 99a0ad9943d1..d0a54c5d00dd 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
@@ -34,11 +34,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
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.
+# 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-]+$")
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
index a0912b6c723f..5e31546f804c 100644
--- 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
@@ -255,6 +255,96 @@ class TestPagination:
_run("tickets")
+class TestFanout:
+ @pytest.mark.parametrize(
+ "endpoint, parent_key, child_key, parent_field, child_path",
+ [
+ ("software_users", "applications", "application_users", "application_id", "applications/{}/users"),
+ (
+ "software_installations",
+ "applications",
+ "installations",
+ "application_id",
+ "applications/{}/installations",
+ ),
+ ("ticket_time_entries", "tickets", "time_entries", "ticket_id", "tickets/{}/time_entries"),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_requests_and_parent_id_injection(
+ self, MockSession, endpoint: str, parent_key: str, child_key: str, parent_field: str, child_path: str
+ ) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({parent_key: [{"id": 7}, {"id": 9}]}),
+ _response({child_key: [{"id": 100}]}),
+ _response({child_key: [{"id": 100}]}),
+ ],
+ )
+
+ rows = _run(endpoint)
+
+ assert [s["url"] for s in snapshots[1:]] == [
+ f"https://acme.freshservice.com/api/v2/{child_path.format(7)}",
+ f"https://acme.freshservice.com/api/v2/{child_path.format(9)}",
+ ]
+ # The child `id` repeats across parents, so the injected parent id is what makes the
+ # composite primary key unique table-wide.
+ assert rows == [{"id": 100, parent_field: 7}, {"id": 100, parent_field: 9}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_time_entries_ask_the_parent_for_every_ticket(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"tickets": [{"id": 1}]}),
+ _response({"time_entries": [{"id": 20}]}),
+ ],
+ )
+
+ _run("ticket_time_entries")
+
+ # Without updated_since the ticket listing only returns the last 30 days, which would
+ # silently drop every older ticket's time entries.
+ assert snapshots[0]["params"]["updated_since"] == "1970-01-01T00:00:00Z"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_parent_deleted_mid_sweep_is_skipped(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response({"tickets": [{"id": 1}, {"id": 2}]}),
+ _response({"message": "gone"}, status=404),
+ _response({"time_entries": [{"id": 21}]}),
+ ],
+ )
+
+ assert _run("ticket_time_entries") == [{"id": 21, "ticket_id": 2}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_after_the_parents_already_swept(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"applications": [{"id": 7}, {"id": 9}]}),
+ _response({"application_users": [{"id": 100}]}),
+ ],
+ )
+
+ manager = _make_manager(
+ resume_state=FreshserviceResumeConfig(completed=["/api/v2/applications/7/users"], current=None)
+ )
+ rows = _run("software_users", manager=manager)
+
+ assert [s["url"] for s in snapshots[1:]] == ["https://acme.freshservice.com/api/v2/applications/9/users"]
+ assert rows == [{"id": 100, "application_id": 9}]
+
+
class TestValidateCredentials:
@pytest.mark.parametrize("status_code", [200, 401, 403])
@mock.patch(FRESHSERVICE_SESSION_PATCH)
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
index a080af700a3e..3fed7513466b 100644
--- 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
@@ -59,24 +59,26 @@ class TestFreshserviceSource:
if "!" in domain or " " in domain:
mock_validate.assert_not_called()
- 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")
+ @pytest.mark.parametrize(
+ "schema_name, primary_keys, partition_keys",
+ [
+ ("tickets", ["id"], ["created_at"]),
+ ("agents", ["id"], None),
+ # Fan-out children aggregate rows from every parent, so the parent id has to stay in
+ # the key for it to be unique table-wide.
+ ("software_users", ["application_id", "id"], ["created_at"]),
+ ("ticket_time_entries", ["ticket_id", "id"], ["created_at"]),
+ ],
+ )
+ def test_source_for_pipeline_response_shape(
+ self, schema_name: str, primary_keys: list[str], partition_keys: Optional[list[str]]
+ ) -> None:
+ inputs = _make_inputs(schema_name)
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
+ assert response.name == schema_name
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == partition_keys
+ assert response.partition_mode == ("datetime" if partition_keys else None)