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 gorgias import source (#61144)

Tom Owersbb5b8a67fa2b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 7acd387fdeea..37249f95fd19 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -60,6 +60,7 @@ the row lists both.
| github | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
+| gorgias | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
@@ -167,7 +168,6 @@ doesn't conflict with concurrent PRs.
- gong
- google_analytics
- google_drive
-- gorgias
- granola
- greenhouse
- helpscout
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index bd95cc257872..0cd5839d7943 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -395,7 +395,9 @@ class GoogleSheetsSourceConfig(config.Config):
@config.config
class GorgiasSourceConfig(config.Config):
- pass
+ gorgias_domain: str
+ email: str
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/gorgias/gorgias.py b/posthog/temporal/data_imports/sources/gorgias/gorgias.py
new file mode 100644
index 000000000000..1e0461ddf565
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gorgias/gorgias.py
@@ -0,0 +1,184 @@
+import re
+import base64
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.gorgias.settings import GORGIAS_ENDPOINTS
+
+# Gorgias caps `limit` at 100 on every list endpoint.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+# A Gorgias subdomain is a single DNS label (1-63 chars, no leading/trailing hyphen).
+# Validating against this before building the URL prevents a crafted domain (e.g. one
+# containing `#`, `?`, `@`, or `.`) from breaking out of the `.gorgias.com` host and
+# redirecting the request — and the Basic-auth header — to an attacker-controlled host.
+_VALID_SUBDOMAIN = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
+
+
+class GorgiasRetryableError(Exception):
+ pass
+
+
+class GorgiasResumeConfig:
+ # Opaque, short-lived cursor token returned in `meta.next_cursor`. We only persist
+ # it for the duration of a single sync (Redis TTL is 24h) — never longer-term.
+ cursor: str
+
+
+def normalize_domain(domain: str) -> str:
+ """Reduce whatever the user pasted to the bare Gorgias subdomain.
+
+ Accepts `acme`, `acme.gorgias.com`, or `https://acme.gorgias.com/api/` and
+ returns `acme`. The result is not yet validated — `get_base_url` enforces that
+ it is a single safe DNS label before it is used to build a request URL.
+ """
+ value = domain.strip().lower()
+ value = value.removeprefix("https://").removeprefix("http://")
+ value = value.split("/", 1)[0]
+ value = value.removesuffix(".gorgias.com")
+ return value.strip("/")
+
+
+def get_base_url(domain: str) -> str:
+ subdomain = normalize_domain(domain)
+ if not _VALID_SUBDOMAIN.match(subdomain):
+ raise ValueError(
+ "Invalid Gorgias domain. Use your account subdomain (letters, digits, and hyphens only), e.g. your-company."
+ )
+ return f"https://{subdomain}.gorgias.com/api"
+
+
+def _get_auth_header(email: str, api_key: str) -> str:
+ token = base64.b64encode(f"{email}:{api_key}".encode()).decode()
+ return f"Basic {token}"
+
+
+def get_headers(email: str, api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": _get_auth_header(email, api_key),
+ "Accept": "application/json",
+ }
+
+
+def validate_credentials(domain: str, email: str, api_key: str) -> tuple[bool, str | None]:
+ """Cheap probe to confirm the credentials are genuine.
+
+ `/account` is the canonical "who am I" endpoint and the lightest call available.
+ A 200 means the basic-auth pair is valid; 401/403 means it is not.
+ """
+ try:
+ url = f"{get_base_url(domain)}/account"
+ except ValueError as e:
+ return False, str(e)
+
+ try:
+ session = make_tracked_session(headers=get_headers(email, api_key), redact_values=(api_key,))
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception as e:
+ return False, f"Could not connect to Gorgias: {e}"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Gorgias credentials. Check your domain, email, and API key."
+ return False, f"Gorgias API returned an unexpected status: {response.status_code}"
+
+
+def get_rows(
+ domain: str,
+ email: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GorgiasResumeConfig],
+) -> Iterator[Any]:
+ config = GORGIAS_ENDPOINTS[endpoint]
+ url = f"{get_base_url(domain)}{config.path}"
+ session = make_tracked_session(headers=get_headers(email, api_key), redact_values=(api_key,))
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume_config.cursor if resume_config else None
+ if cursor:
+ logger.debug(f"Gorgias: resuming {endpoint} from saved cursor")
+
+ @retry(
+ retry=retry_if_exception_type(
+ (GorgiasRetryableError, requests.ReadTimeout, requests.ConnectionError),
+ ),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(request_cursor: str | None) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "order_by": config.order_by}
+ if request_cursor:
+ params["cursor"] = request_cursor
+
+ # The tracked adapter already retries 429/5xx while honoring the Retry-After
+ # header; this guard re-raises anything that slips through so tenacity can back off.
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GorgiasRetryableError(
+ f"Gorgias API error (retryable): status={response.status_code}, endpoint={endpoint}"
+ )
+ if not response.ok:
+ logger.error(f"Gorgias API error: status={response.status_code}, body={response.text}, endpoint={endpoint}")
+ response.raise_for_status()
+ return response.json()
+
+ while True:
+ data = fetch_page(cursor)
+
+ items = data.get("data", [])
+ if items:
+ yield items
+
+ next_cursor = (data.get("meta") or {}).get("next_cursor")
+ if not next_cursor:
+ break
+
+ cursor = next_cursor
+ # Save AFTER yielding so a crash re-yields the last batch (merge dedupes on the
+ # primary key) instead of skipping it.
+ resumable_source_manager.save_state(GorgiasResumeConfig(cursor=cursor))
+
+
+def gorgias_source(
+ domain: str,
+ email: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GorgiasResumeConfig],
+) -> SourceResponse:
+ config = GORGIAS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ domain=domain,
+ email=email,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/gorgias/settings.py b/posthog/temporal/data_imports/sources/gorgias/settings.py
new file mode 100644
index 000000000000..0859cf31b756
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gorgias/settings.py
@@ -0,0 +1,85 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class GorgiasEndpointConfig:
+ name: str
+ path: str
+ # Stable creation-time field used for datetime partitioning. Gorgias exposes
+ # `created_datetime` on every list resource and it never changes once set —
+ # never partition on `updated_datetime`, which rewrites partitions on each sync.
+ partition_key: str = "created_datetime"
+ # Explicit ascending sort on the stable creation field keeps page boundaries
+ # stable across a full-refresh sync even if rows are inserted while we paginate.
+ # Every list endpoint accepts `created_datetime:asc` (verified against the docs).
+ order_by: str = "created_datetime:asc"
+ # Candidate cursor fields surfaced for documentation/forward-compat only. Gorgias
+ # list endpoints expose NO server-side timestamp filter (only `order_by`), so true
+ # incremental sync is impossible today — every endpoint runs as a full refresh.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {
+ "tickets": GorgiasEndpointConfig(
+ name="tickets",
+ path="/tickets",
+ incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ ),
+ "messages": GorgiasEndpointConfig(
+ name="messages",
+ path="/messages",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+ "customers": GorgiasEndpointConfig(
+ name="customers",
+ path="/customers",
+ incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ ),
+ "users": GorgiasEndpointConfig(
+ name="users",
+ path="/users",
+ incremental_fields=[_datetime_field("created_datetime"), _datetime_field("updated_datetime")],
+ ),
+ "satisfaction_surveys": GorgiasEndpointConfig(
+ name="satisfaction_surveys",
+ path="/satisfaction-surveys",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+ "tags": GorgiasEndpointConfig(
+ name="tags",
+ path="/tags",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+ "views": GorgiasEndpointConfig(
+ name="views",
+ path="/views",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+ "teams": GorgiasEndpointConfig(
+ name="teams",
+ path="/teams",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+ "macros": GorgiasEndpointConfig(
+ name="macros",
+ path="/macros",
+ incremental_fields=[_datetime_field("created_datetime")],
+ ),
+}
+
+ENDPOINTS = tuple(GORGIAS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GORGIAS_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/gorgias/source.py b/posthog/temporal/data_imports/sources/gorgias/source.py
index 810f6159259b..f28f6ef1bd1d 100644
--- a/posthog/temporal/data_imports/sources/gorgias/source.py
+++ b/posthog/temporal/data_imports/sources/gorgias/source.py
@@ -1,29 +1,131 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import GorgiasSourceConfig
+from posthog.temporal.data_imports.sources.gorgias.gorgias import (
+ GorgiasResumeConfig,
+ gorgias_source,
+ validate_credentials as validate_gorgias_credentials,
+)
+from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GorgiasSource(SimpleSource[GorgiasSourceConfig]):
+class GorgiasSource(ResumableSource[GorgiasSourceConfig, GorgiasResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GORGIAS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Gorgias authentication failed. Check your email and API key.",
+ "403 Client Error: Forbidden for url": "Your Gorgias API key does not have access to this resource. Check the integration's permissions.",
+ }
+
+ def get_schemas(
+ self,
+ config: GorgiasSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Gorgias list endpoints have no server-side timestamp filter (only client-side
+ # ordering), so every endpoint is full-refresh only. Cursor pagination still lets
+ # an interrupted sync resume mid-stream via the ResumableSourceManager.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ 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: GorgiasSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_gorgias_credentials(config.gorgias_domain, config.email, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GorgiasResumeConfig]:
+ return ResumableSourceManager[GorgiasResumeConfig](inputs, GorgiasResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GorgiasSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GorgiasResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return gorgias_source(
+ domain=config.gorgias_domain,
+ email=config.email,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.GORGIAS,
label="Gorgias",
+ caption="""Enter your Gorgias credentials to pull your helpdesk data into the PostHog Data warehouse.
+
+Create an API key in your Gorgias account under **Settings → REST API**. Use the email of the account that owns the key together with the key itself.
+
+This source authenticates with HTTP Basic Auth (email + API key) and requires read access to the endpoints you want to sync (tickets, messages, customers, users, satisfaction surveys, tags, views, teams, macros).""",
iconPath="/static/services/gorgias.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/gorgias",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="gorgias_domain",
+ label="Gorgias domain (subdomain)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-company",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="email",
+ label="Account email",
+ type=SourceFieldInputConfigType.EMAIL,
+ required=True,
+ placeholder="[email protected]",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
new file mode 100644
index 000000000000..55a826651997
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
@@ -0,0 +1,206 @@
+import base64
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.gorgias.gorgias import (
+ GorgiasResumeConfig,
+ get_base_url,
+ get_headers,
+ get_rows,
+ gorgias_source,
+ normalize_domain,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS, GORGIAS_ENDPOINTS
+
+GORGIAS_MODULE = "posthog.temporal.data_imports.sources.gorgias.gorgias"
+
+
+class _FakeManager(ResumableSourceManager[GorgiasResumeConfig]):
+ """Minimal stand-in for ResumableSourceManager that records saved state in memory."""
+
+ def __init__(self, resume_cursor: str | None = None) -> None:
+ self._resume_cursor = resume_cursor
+ self.saved: list[GorgiasResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_cursor is not None
+
+ def load_state(self) -> GorgiasResumeConfig | None:
+ return GorgiasResumeConfig(cursor=self._resume_cursor) if self._resume_cursor else None
+
+ def save_state(self, data: GorgiasResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response(status_code: int = 200, json_body: dict | None = None, ok: bool = True) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = ok
+ response.json.return_value = json_body or {}
+ response.text = ""
+ return response
+
+
+class TestNormalizeDomain:
+ @parameterized.expand(
+ [
+ ("bare_subdomain", "acme", "acme"),
+ ("full_host", "acme.gorgias.com", "acme"),
+ ("https_url", "https://acme.gorgias.com", "acme"),
+ ("https_url_with_path", "https://acme.gorgias.com/api/", "acme"),
+ ("uppercase_and_spaces", " ACME ", "acme"),
+ ("trailing_slash", "acme/", "acme"),
+ ]
+ )
+ def test_normalize_domain(self, _name: str, value: str, expected: str) -> None:
+ assert normalize_domain(value) == expected
+
+ def test_get_base_url(self) -> None:
+ assert get_base_url("acme.gorgias.com") == "https://acme.gorgias.com/api"
+
+ @parameterized.expand(
+ [
+ # Crafted inputs that would otherwise break out of the .gorgias.com host
+ # and redirect the request (and the Basic-auth header) elsewhere.
+ ("fragment", "attacker.example.com#"),
+ ("query", "169.254.169.254?x="),
+ ("userinfo", "[email protected]"),
+ ("port", "attacker.example.com:8080"),
+ ("dotted", "evil.com"),
+ ("empty", " "),
+ ("leading_hyphen", "-acme"),
+ ]
+ )
+ def test_get_base_url_rejects_unsafe_domains(self, _name: str, domain: str) -> None:
+ with pytest.raises(ValueError):
+ get_base_url(domain)
+
+
+class TestHeaders:
+ def test_basic_auth_header_is_email_and_api_key(self) -> None:
+ headers = get_headers("[email protected]", "secret-key")
+ scheme, _, token = headers["Authorization"].partition(" ")
+ assert scheme == "Basic"
+ assert base64.b64decode(token).decode() == "[email protected]:secret-key"
+ assert headers["Accept"] == "application/json"
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_valid: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status_code=status_code)
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ valid, error = validate_credentials("acme", "[email protected]", "key")
+ assert valid is expected_valid
+ assert (error is None) is expected_valid
+
+ def test_empty_domain_fails_without_request(self) -> None:
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session") as mocked:
+ valid, error = validate_credentials(" ", "[email protected]", "key")
+ assert valid is False
+ assert error is not None
+ mocked.assert_not_called()
+
+ def test_unsafe_domain_fails_without_request(self) -> None:
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session") as mocked:
+ valid, error = validate_credentials("attacker.example.com#", "[email protected]", "key")
+ assert valid is False
+ assert error is not None
+ mocked.assert_not_called()
+
+ def test_connection_error_is_handled(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ valid, error = validate_credentials("acme", "[email protected]", "key")
+ assert valid is False
+ assert error is not None
+
+
+class TestGetRows:
+ def test_paginates_until_next_cursor_is_null(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": "c2"}}),
+ _response(json_body={"data": [{"id": 2}], "meta": {"next_cursor": None}}),
+ ]
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ batches = list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
+
+ assert batches == [[{"id": 1}], [{"id": 2}]]
+ assert session.get.call_count == 2
+
+ def test_saves_cursor_after_yielding_each_batch(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": "c2"}}),
+ _response(json_body={"data": [{"id": 2}], "meta": {"next_cursor": None}}),
+ ]
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
+
+ # Only the page that has a following cursor triggers a save.
+ assert [c.cursor for c in manager.saved] == ["c2"]
+
+ def test_resumes_from_saved_cursor(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager(resume_cursor="resume-token")
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
+
+ _, kwargs = session.get.call_args
+ assert kwargs["params"]["cursor"] == "resume-token"
+
+ def test_passes_explicit_order_by_and_limit(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
+
+ _, kwargs = session.get.call_args
+ assert kwargs["params"]["order_by"] == "created_datetime:asc"
+ assert kwargs["params"]["limit"] == 100
+ assert "cursor" not in kwargs["params"]
+
+ def test_empty_first_page_terminates(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ batches = list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
+
+ assert batches == []
+ assert manager.saved == []
+
+
+class TestGorgiasSource:
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = gorgias_source("acme", "[email protected]", "key", endpoint, MagicMock(), _FakeManager())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [GORGIAS_ENDPOINTS[endpoint].partition_key]
+ assert response.sort_mode == "asc"
+
+ def test_every_endpoint_partitions_on_created_datetime(self) -> None:
+ for config in GORGIAS_ENDPOINTS.values():
+ assert config.partition_key == "created_datetime"
+ assert "updated" not in config.partition_key
diff --git a/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py
new file mode 100644
index 000000000000..601ed5b81d62
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gorgias/tests/test_gorgias_source.py
@@ -0,0 +1,93 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import GorgiasSourceConfig
+from posthog.temporal.data_imports.sources.gorgias.gorgias import GorgiasResumeConfig
+from posthog.temporal.data_imports.sources.gorgias.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.gorgias.source import GorgiasSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "posthog.temporal.data_imports.sources.gorgias.source"
+
+
+def _config() -> GorgiasSourceConfig:
+ return GorgiasSourceConfig(gorgias_domain="acme", email="[email protected]", api_key="key")
+
+
+def _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=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestGorgiasSource:
+ def test_source_type(self) -> None:
+ assert GorgiasSource().source_type == ExternalDataSourceType.GORGIAS
+
+ def test_source_config_fields(self) -> None:
+ config = GorgiasSource().get_source_config
+ assert config.label == "Gorgias"
+ assert config.releaseStatus == "alpha"
+
+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"gorgias_domain", "email", "api_key"}
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].secret is True
+ assert fields["email"].type == SourceFieldInputConfigType.EMAIL
+ assert all(fields[name].required for name in fields)
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = GorgiasSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Gorgias has no server-side timestamp filter, so nothing supports incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = GorgiasSource().get_schemas(_config(), team_id=1, names=["tickets", "customers"])
+ assert {s.name for s in schemas} == {"tickets", "customers"}
+
+ @parameterized.expand(
+ [
+ ("valid", (True, None), True),
+ ("invalid", (False, "Invalid Gorgias credentials. Check your domain, email, and API key."), False),
+ ]
+ )
+ def test_validate_credentials_delegates(self, _name: str, transport_result: tuple, expected_valid: bool) -> None:
+ with patch(f"{SOURCE_MODULE}.validate_gorgias_credentials", return_value=transport_result) as mocked:
+ valid, _error = GorgiasSource().validate_credentials(_config(), team_id=1)
+ assert valid is expected_valid
+ mocked.assert_called_once_with("acme", "[email protected]", "key")
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = GorgiasSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is GorgiasResumeConfig
+
+ def test_source_for_pipeline_plumbs_schema_name(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ response = GorgiasSource().source_for_pipeline(_config(), manager, _inputs(schema_name="customers"))
+ assert response.name == "customers"
+ assert response.primary_keys == ["id"]
+
+ def test_non_retryable_errors_cover_auth_failures(self) -> None:
+ errors = GorgiasSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
diff --git a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
index 56dcc1f9a7af..ec019529010d 100644
--- a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
+++ b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
@@ -4,6 +4,7 @@ from posthog.temporal.data_imports.sources.generated_configs import (
DoItSourceConfig,
GoogleAdsSourceConfig,
GoogleSheetsSourceConfig,
+ GorgiasSourceConfig,
HubspotSourceConfig,
MetaAdsSourceConfig,
MongoDBSourceConfig,
@@ -73,6 +74,13 @@ def test_google_sheets_config():
assert config.spreadsheet_url == "google.com"
+def test_gorgias_config():
+ config = GorgiasSourceConfig.from_dict({"gorgias_domain": "acme", "email": "[email protected]", "api_key": "api_key"})
+ assert config.gorgias_domain == "acme"
+ assert config.email == "[email protected]"
+ assert config.api_key == "api_key"
+
+
def test_hubspot_config():
config = HubspotSourceConfig.from_dict({"hubspot_integration_id": 1})
assert config.hubspot_integration_id == 1