: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement gladly import source (#62989)
Tom Owers01e04d58a6c9
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 54d22bf607f9..837c1a55c15b 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -98,6 +98,7 @@ the row lists both.| fullstory | HTTP | requests | ✅ || github | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ |+| gladly | HTTP | requests | ✅ || gocardless | HTTP | requests | ✅ || gong | HTTP | requests | ✅ || google_ads | gRPC | google-ads (googleads.client) | ✅ |@@ -264,7 +265,6 @@ doesn't conflict with concurrent PRs.- facebook_pages- firebase- freshbooks-- gladly- google_ad_manager- google_analytics- google_cloud_storagediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex e5a6975d599b..02be9d7d2bf9 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -646,7 +646,9 @@ class GithubSourceConfig(config.Config):@config.configclass GladlySourceConfig(config.Config):- pass+ organization: str+ agent_email: str+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/gladly/gladly.py b/posthog/temporal/data_imports/sources/gladly/gladly.pynew file mode 100644index 000000000000..8236322e68a9--- /dev/null+++ b/posthog/temporal/data_imports/sources/gladly/gladly.py@@ -0,0 +1,196 @@+import re+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode++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.gladly.settings import GLADLY_ENDPOINTS++REQUEST_TIMEOUT_SECONDS = 300+# 10 req/s per org; back off on 429.+MAX_RETRY_ATTEMPTS = 5+# Yield JSONL rows in chunks so big files don't build one giant list.+CHUNK_SIZE = 5000+++class GladlyRetryableError(Exception):+ pass+++class GladlyResumeConfig:+ # Jobs are processed oldest-first; persisting the last fully-processed+ # job's updatedAt lets a retried sync skip straight past it.+ last_job_updated_at: str+++def _get_session(agent_email: str, api_token: str) -> requests.Session:+ session = make_tracked_session(redact_values=(api_token,))+ session.auth = (agent_email, api_token)+ return session+++def _clean_organization(organization: str) -> str:+ """Accept either the bare org subdomain or a pasted full domain/URL."""+ org = organization.strip().removeprefix("https://").removeprefix("http://")+ org = org.split(".")[0].split("/")[0]+ if not re.fullmatch(r"[a-zA-Z0-9-]+", org):+ raise ValueError(f"Invalid Gladly organization: {organization}")+ return org+++def _base_url(organization: str) -> str:+ return f"https://{_clean_organization(organization)}.gladly.com/api/v1"+++def _format_timestamp(value: Any) -> str:+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00.000Z")+ return str(value)+++def validate_credentials(organization: str, agent_email: str, api_token: str) -> bool:+ """Confirm the credentials are valid with a cheap agents probe."""+ # Resolve the org first so a malformed organization surfaces its own ValueError+ # rather than being mislabelled as a credentials problem by the caller.+ base_url = _base_url(organization)+ try:+ response = _get_session(agent_email, api_token).get(+ f"{base_url}/agents",+ timeout=15,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ organization: str,+ agent_email: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GLADLY_ENDPOINTS[endpoint]+ session = _get_session(agent_email, api_token)+ base_url = _base_url(organization)++ @retry(+ retry=retry_if_exception_type((GladlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def fetch(url: str) -> requests.Response:+ # stream=True keeps the large JSONL export files off the heap — iter_lines()+ # then streams them. The small jobs-list call still works with .json().+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ if response.status_code == 429 or response.status_code >= 500:+ raise GladlyRetryableError(f"Gladly API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Gladly API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response++ # The cutoff is the later of the incremental watermark and the resume+ # state, so retried syncs skip already-processed jobs either way.+ cutoff: Optional[str] = None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ cutoff = _format_timestamp(db_incremental_field_last_value)+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and (cutoff is None or resume_config.last_job_updated_at > cutoff):+ cutoff = resume_config.last_job_updated_at+ logger.debug(f"Gladly: resuming {endpoint} after job updatedAt {cutoff}")++ jobs_body = fetch(f"{base_url}/export/jobs?{urlencode({'status': 'COMPLETED'})}").json()+ jobs = jobs_body if isinstance(jobs_body, list) else []+ jobs = [job for job in jobs if job.get("updatedAt")]+ jobs.sort(key=lambda job: job["updatedAt"])++ for job in jobs:+ job_updated_at = job["updatedAt"]+ # Strict less-than: jobs sharing the cutoff timestamp are re-yielded rather+ # than skipped, so a late-arriving job with the same updatedAt as the+ # watermark isn't lost. Merge-on-id dedupes the boundary job's re-yielded rows.+ if cutoff is not None and job_updated_at < cutoff:+ continue++ files = job.get("files") or []+ if config.filename not in files:+ continue++ # id is required per the export contract and is needed for the download+ # URL — a missing one is a broken API response, so fail loud.+ job_id = job["id"]++ response = fetch(f"{base_url}/export/jobs/{quote(job_id)}/files/{quote(config.filename)}")+ chunk: list[dict[str, Any]] = []+ for line in response.iter_lines(decode_unicode=True):+ if not line or not line.strip():+ continue+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ logger.warning(f"Gladly: skipping malformed JSONL line in job {job_id} {config.filename}")+ continue+ chunk.append({**row, "_job_id": job_id, "_job_updated_at": job_updated_at})+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []+ if chunk:+ yield chunk++ # Save state AFTER the job's file is fully yielded so a crash re-yields+ # this job (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(GladlyResumeConfig(last_job_updated_at=job_updated_at))+++def gladly_source(+ organization: str,+ agent_email: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = GLADLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ organization=organization,+ agent_email=agent_email,+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[config.primary_key],+ partition_count=1,+ partition_size=1,+ # Jobs are processed oldest-first, so the injected job watermark only+ # moves forward.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/gladly/settings.py b/posthog/temporal/data_imports/sources/gladly/settings.pynew file mode 100644index 000000000000..4d10ad6e6d7e--- /dev/null+++ b/posthog/temporal/data_imports/sources/gladly/settings.py@@ -0,0 +1,54 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Rows don't carry an export timestamp themselves, so the transport injects the+# producing job's updatedAt — that injected field is the incremental cursor.+_JOB_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "_job_updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "_job_updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class GladlyEndpointConfig:+ name: str+ # Filename inside each export job (e.g. customers.jsonl).+ filename: str+ primary_key: str = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_JOB_INCREMENTAL_FIELDS))+++# Gladly has no list-all REST surface — bulk data ships as JSONL files inside+# vendor-scheduled export jobs (hourly/daily, 14-day retention). Every stream+# maps to one file per job; jobs are processed oldest-first so the watermark+# advances monotonically, and merge-on-id dedupes records that appear in+# multiple exports.+GLADLY_ENDPOINTS: dict[str, GladlyEndpointConfig] = {+ "customers": GladlyEndpointConfig(+ name="customers",+ filename="customers.jsonl",+ ),+ "conversation_items": GladlyEndpointConfig(+ name="conversation_items",+ filename="conversation_items.jsonl",+ ),+ "agents": GladlyEndpointConfig(+ name="agents",+ filename="agents.jsonl",+ ),+ "topics": GladlyEndpointConfig(+ name="topics",+ filename="topics.jsonl",+ ),+}++ENDPOINTS = tuple(GLADLY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GLADLY_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/gladly/source.py b/posthog/temporal/data_imports/sources/gladly/source.pyindex 4c5518b13772..54364aa8f18e 100644--- a/posthog/temporal/data_imports/sources/gladly/source.py+++ b/posthog/temporal/data_imports/sources/gladly/source.py@@ -1,29 +1,144 @@-from typing import cast+from typing import Optional, castfrom 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, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import GladlySourceConfig+from posthog.temporal.data_imports.sources.gladly.gladly import (+ GladlyResumeConfig,+ gladly_source,+ validate_credentials as validate_gladly_credentials,+)+from posthog.temporal.data_imports.sources.gladly.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class GladlySource(SimpleSource[GladlySourceConfig]):+class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GLADLY+ @property+ def connection_host_fields(self) -> list[str]:+ # `organization` determines the host the stored token is sent to;+ # retargeting it must re-require the token.+ return ["organization"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Gladly authentication failed. Please check your agent email and API token.",+ "403 Client Error: Forbidden for url": "Gladly denied access. Please check that the agent has the API User permission.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GLADLY,label="Gladly",+ caption="""Connect your Gladly account to pull your customer service data into the PostHog Data warehouse.++Your organization is the first part of your Gladly URL — for `myorg.gladly.com` enter `myorg`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Data comes from Gladly's scheduled export jobs, which retain files for 14 days — history older than that requires asking Gladly support to regenerate exports.""",iconPath="/static/services/gladly.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/gladly",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="organization",+ label="Organization",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="myorg",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="agent_email",+ label="Agent email",+ type=SourceFieldInputConfigType.EMAIL,+ required=True,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: GladlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ 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: GladlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ if validate_gladly_credentials(config.organization, config.agent_email, config.api_token):+ return True, None+ except ValueError as e:+ # A malformed organization is a distinct, actionable error — surface it+ # instead of the generic credentials message.+ return False, str(e)++ return False, "Invalid Gladly credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GladlyResumeConfig]:+ return ResumableSourceManager[GladlyResumeConfig](inputs, GladlyResumeConfig)++ def source_for_pipeline(+ self,+ config: GladlySourceConfig,+ resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gladly_source(+ organization=config.organization,+ agent_email=config.agent_email,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/gladly/tests/test_gladly.py b/posthog/temporal/data_imports/sources/gladly/tests/test_gladly.pynew file mode 100644index 000000000000..0cef2f784115--- /dev/null+++ b/posthog/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -0,0 +1,253 @@+import json+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.gladly.gladly import (+ CHUNK_SIZE,+ GladlyResumeConfig,+ _base_url,+ _clean_organization,+ get_rows,+ gladly_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.gladly.settings import ENDPOINTS, GLADLY_ENDPOINTS++_MODULE = "posthog.temporal.data_imports.sources.gladly.gladly"+++def _make_manager(resume_state: GladlyResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _jobs_response(jobs: list[dict[str, Any]]) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = jobs+ resp.status_code = 200+ resp.ok = True+ return resp+++def _jsonl_response(rows: list[dict[str, Any]], junk_lines: list[str] | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ lines = [json.dumps(row) for row in rows] + (junk_lines or [])+ resp.iter_lines.return_value = iter(lines)+ resp.status_code = 200+ resp.ok = True+ return resp+++def _job(job_id: str, updated_at: str, files: list[str] | None = None) -> dict[str, Any]:+ return {"id": job_id, "updatedAt": updated_at, "files": files or ["customers.jsonl", "agents.jsonl"]}+++class TestCleanOrganization:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("myorg", "myorg"),+ ("https://myorg.gladly.com", "myorg"),+ ("myorg.gladly.com/api/v1", "myorg"),+ ("my-org", "my-org"),+ ],+ )+ def test_valid_organizations(self, value, expected):+ assert _clean_organization(value) == expected++ @pytest.mark.parametrize("value", ["", "my org", "org?x=1"])+ def test_invalid_organizations_raise(self, value):+ with pytest.raises(ValueError):+ _clean_organization(value)++ def test_base_url(self):+ assert _base_url("myorg") == "https://myorg.gladly.com/api/v1"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("myorg", "[email protected]", "token") is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_session_uses_basic_auth(self, mock_session):+ response = mock.MagicMock()+ response.status_code = 200+ mock_session.return_value.get.return_value = response++ validate_credentials("myorg", "[email protected]", "token")++ assert mock_session.return_value.auth == ("[email protected]", "token")+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_processes_jobs_oldest_first_and_injects_job_fields(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j2", "2024-01-02T00:00:00.000Z"), _job("j1", "2024-01-01T00:00:00.000Z")]),+ _jsonl_response([{"id": "c1"}]), # j1 file (oldest first)+ _jsonl_response([{"id": "c2"}]), # j2 file+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "[email protected]", "token", "customers", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [(r["id"], r["_job_id"], r["_job_updated_at"]) for r in flat] == [+ ("c1", "j1", "2024-01-01T00:00:00.000Z"),+ ("c2", "j2", "2024-01-02T00:00:00.000Z"),+ ]+ # State saved after each fully-processed job.+ assert [call.args[0].last_job_updated_at for call in manager.save_state.call_args_list] == [+ "2024-01-01T00:00:00.000Z",+ "2024-01-02T00:00:00.000Z",+ ]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_skips_jobs_strictly_before_watermark(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j1", "2024-01-01T00:00:00.000Z"), _job("j2", "2024-01-02T00:00:00.000Z")]),+ _jsonl_response([{"id": "c2"}]),+ ]++ manager = _make_manager()+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "customers",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01T12:00:00.000Z",+ )+ )++ flat = [row for batch in batches for row in batch]+ assert [r["id"] for r in flat] == ["c2"]+ # Only one file download happened.+ assert mock_session.return_value.get.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_job_sharing_watermark_timestamp_is_reprocessed(self, mock_session):+ # A late-arriving job with the same updatedAt as the watermark must not be+ # dropped — it is re-yielded and merge-on-id dedupes any overlapping rows.+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j1", "2024-01-01T00:00:00.000Z"), _job("j2", "2024-01-01T00:00:00.000Z")]),+ _jsonl_response([{"id": "c1"}]),+ _jsonl_response([{"id": "c2"}]),+ ]++ manager = _make_manager()+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "customers",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01T00:00:00.000Z",+ )+ )++ assert [row["id"] for batch in batches for row in batch] == ["c1", "c2"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_state_supersedes_older_watermark(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _jobs_response(+ [+ _job("j1", "2024-01-01T00:00:00.000Z"),+ _job("j2", "2024-01-02T00:00:00.000Z"),+ _job("j3", "2024-01-03T00:00:00.000Z"),+ ]+ ),+ _jsonl_response([{"id": "c3"}]),+ ]++ # Resume cutoff (between j2 and j3) supersedes the older incremental watermark,+ # so j1 and j2 are skipped and only j3 is processed.+ manager = _make_manager(GladlyResumeConfig(last_job_updated_at="2024-01-02T12:00:00.000Z"))+ batches = list(+ get_rows(+ "myorg",+ "[email protected]",+ "token",+ "customers",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01T00:00:00.000Z",+ )+ )++ assert [row["id"] for batch in batches for row in batch] == ["c3"]+ assert mock_session.return_value.get.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_jobs_missing_the_stream_file_are_skipped(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j1", "2024-01-01T00:00:00.000Z", files=["topics.jsonl"])]),+ ]++ manager = _make_manager()+ assert list(get_rows("myorg", "[email protected]", "token", "customers", mock.MagicMock(), manager)) == []++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_malformed_jsonl_lines_are_skipped_with_warning(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j1", "2024-01-01T00:00:00.000Z")]),+ _jsonl_response([{"id": "good"}], junk_lines=["{not json", ""]),+ ]++ manager = _make_manager()+ logger = mock.MagicMock()+ batches = list(get_rows("myorg", "[email protected]", "token", "customers", logger, manager))++ assert [row["id"] for batch in batches for row in batch] == ["good"]+ logger.warning.assert_called_once()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_large_files_are_chunked(self, mock_session):+ rows = [{"id": str(i)} for i in range(CHUNK_SIZE + 1)]+ mock_session.return_value.get.side_effect = [+ _jobs_response([_job("j1", "2024-01-01T00:00:00.000Z")]),+ _jsonl_response(rows),+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "[email protected]", "token", "customers", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]+++class TestGladlySourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = GLADLY_ENDPOINTS[endpoint]+ response = gladly_source("myorg", "[email protected]", "token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == "asc"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/posthog/temporal/data_imports/sources/gladly/tests/test_gladly_source.pynew file mode 100644index 000000000000..f3d765795d9c--- /dev/null+++ b/posthog/temporal/data_imports/sources/gladly/tests/test_gladly_source.py@@ -0,0 +1,148 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import GladlySourceConfig+from posthog.temporal.data_imports.sources.gladly.gladly import GladlyResumeConfig+from posthog.temporal.data_imports.sources.gladly.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.gladly.source import GladlySource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestGladlySource:+ def setup_method(self):+ self.source = GladlySource()+ self.team_id = 123+ self.config = GladlySourceConfig(organization="myorg", agent_email="[email protected]", api_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GLADLY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Gladly"+ assert config.label == "Gladly"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/gladly.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["organization", "agent_email", "api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_connection_host_fields_cover_organization(self):+ # The org subdomain decides where the stored token gets sent.+ assert self.source.connection_host_fields == ["organization"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://myorg.gladly.com/api/v1/export/jobs",+ "403 Client Error: Forbidden for url: https://myorg.gladly.com/api/v1/export/jobs/123/files/customers.jsonl",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://myorg.gladly.com/api/v1/export/jobs"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # Every stream carries the injected job watermark, so all are incremental.+ assert all(schema.supports_incremental for schema in schemas)+ assert all(schema.supports_append for schema in schemas)++ def test_schemas_advertise_the_injected_job_cursor(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ for schema in schemas:+ assert [f["field"] for f in schema.incremental_fields] == ["_job_updated_at"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])+ assert len(schemas) == 1+ assert schemas[0].name == "customers"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.gladly.source.validate_gladly_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if not expected_valid:+ assert error_message == "Invalid Gladly credentials"+ mock_validate.assert_called_once_with("myorg", "[email protected]", "token")++ @mock.patch("posthog.temporal.data_imports.sources.gladly.source.validate_gladly_credentials")+ def test_validate_credentials_surfaces_invalid_organization(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid Gladly organization: bad org")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid Gladly organization: bad org"++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GladlyResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.gladly.source.gladly_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_gladly_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_gladly_source.assert_called_once()+ kwargs = mock_gladly_source.call_args.kwargs+ assert kwargs["organization"] == "myorg"+ assert kwargs["agent_email"] == "[email protected]"+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "customers"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05.000Z"++ @mock.patch("posthog.temporal.data_imports.sources.gladly.source.gladly_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_gladly_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_gladly_source.call_args.kwargs["db_incremental_field_last_value"] is None