: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 gridly import source (#67802)
Tom Owersc0d58a69351d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 758974fb92f2..08c2e730e170 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -167,6 +167,7 @@ the row lists both.| granola | HTTP | requests | ✅ || gorgias | HTTP | requests | ✅ || greenhouse | HTTP | requests | ✅ |+| gridly | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || hellobaton | HTTP | requests | ✅ |@@ -444,7 +445,6 @@ doesn't conflict with concurrent PRs.- google_workspace_admin_reports- grafana- greythr-- gridly- gusto- harness- heapdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 2b52b2a33d51..cf473c2c1533 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1478,7 +1478,8 @@ class GreytHrSourceConfig(config.Config):@config.configclass GridlySourceConfig(config.Config):- pass+ api_key: str+ view_id: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.pynew file mode 100644index 000000000000..4f794dd8b621--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py@@ -0,0 +1,27 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "records": {+ "description": "Content records of the configured Gridly view — one row per record, in the shape the Gridly API returns them.",+ "docs_url": "https://www.gridly.com/docs/api/",+ "columns": {+ "id": "Unique identifier of the record within the view.",+ "path": "Path to the folder where the record is stored.",+ "cells": "List of the record's cells, each with a `columnId` and `value` holding that column's data.",+ },+ },+ "columns": {+ "description": "Column definitions of the configured Gridly view, read from the view resource.",+ "docs_url": "https://www.gridly.com/docs/api/",+ "columns": {+ "id": "Unique identifier of the column.",+ "name": "Display name of the column.",+ "type": "Data type of the column (e.g. singleLine, number, language, reference).",+ "isSource": "Whether the column is a source (reference) column.",+ "isTarget": "Whether the column is a target (reference) column.",+ "languageCode": "Language code for localization columns.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.pynew file mode 100644index 000000000000..20ed1eed9788--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py@@ -0,0 +1,231 @@+import json+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import GRIDLY_ENDPOINTS++GRIDLY_BASE_URL = "https://api.gridly.com/v1"++# Gridly caps `limit` at 1000 records per page; larger values are rejected.+PAGE_SIZE = 1000++MAX_RETRY_ATTEMPTS = 5+++class GridlyRetryableError(Exception):+ pass+++class GridlyResumeConfig:+ # Offset of the next records page to fetch. Records is the only paginated endpoint; the columns+ # endpoint is a single request and never resumes.+ offset: int = 0+++def _headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"ApiKey {api_key}",+ "Accept": "application/json",+ }+++def _parse_total_count(value: str | None) -> int | None:+ """Parse the `X-Total-Count` response header, tolerating a missing/garbage value."""+ if value is None:+ return None+ try:+ return int(value)+ except ValueError:+ return None+++@retry(+ # ChunkedEncodingError is a mid-stream connection break (the server truncated a chunked+ # response body); it's transient like ConnectionError/ReadTimeout, not a ConnectionError subclass.+ retry=retry_if_exception_type(+ (+ GridlyRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> requests.Response:+ response = session.get(url, params=params, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise GridlyRetryableError(f"Gridly API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Never log response.text or the raw URL: the error body can echo customer record content+ # from the synced view, and the query string carries the paginated `page` blob. Both would+ # leak into operational logs. Log only status plus scheme/host/path.+ safe = urlsplit(response.url)+ safe_url = f"{safe.scheme}://{safe.netloc}{safe.path}"+ logger.error(f"Gridly API error: status={response.status_code}, url={safe_url}")+ # raise_for_status() would embed the full request URL (query string included) in the+ # exception, which is surfaced as the schema's latest_error. Rebuild the error from+ # scheme/host/path only so no request params or response body reach stored error state. The+ # "<status> Client Error: <reason> for url: https://api.gridly.com" prefix stays stable for+ # get_non_retryable_errors() matching.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}",+ response=response,+ )++ return response+++def _iter_records(+ session: requests.Session,+ view_id: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Walk the view's records with offset/limit pagination.++ Gridly's `page` query param is a JSON blob (`{"offset": n, "limit": m}`) and the total row+ count comes from the `X-Total-Count` response header. Rows are yielded in the shape the API+ returns them (`{id, path, cells}`) — `cells` is left as a nested list rather than flattened,+ since a record's columns are user-defined and vary per view.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume is not None else 0+ if offset:+ logger.debug(f"Gridly: resuming records from offset={offset}")++ url = f"{GRIDLY_BASE_URL}/views/{view_id}/records"++ while True:+ page = json.dumps({"offset": offset, "limit": PAGE_SIZE}, separators=(",", ":"))+ response = _fetch(session, url, {"page": page}, headers, logger)+ records = response.json()++ if not records:+ break++ yield records++ total = _parse_total_count(response.headers.get("X-Total-Count"))+ offset += len(records)++ # A short page means we've reached the end regardless of the (possibly stale) total.+ if len(records) < PAGE_SIZE:+ break+ if total is not None and offset >= total:+ break++ # Save AFTER yielding so a crash re-fetches the last page rather than skipping it — merge+ # dedupes the re-pulled rows on the primary key.+ resumable_source_manager.save_state(GridlyResumeConfig(offset=offset))+++def _iter_columns(+ session: requests.Session,+ view_id: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Yield the view's column definitions, read from the view object.++ Gridly has no standalone "list columns" endpoint; the column list is embedded in the view+ resource (`GET /v1/views/{viewId}`).+ """+ response = _fetch(session, f"{GRIDLY_BASE_URL}/views/{view_id}", {}, headers, logger)+ columns = response.json().get("columns", [])+ if columns:+ yield columns+++def get_rows(+ api_key: str,+ view_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request.+ session = make_tracked_session(redact_values=(api_key,))+ headers = _headers(api_key)++ if endpoint == "columns":+ yield from _iter_columns(session, view_id, headers, logger)+ elif endpoint == "records":+ yield from _iter_records(session, view_id, headers, logger, resumable_source_manager)+ else:+ raise ValueError(f"Unknown Gridly endpoint: {endpoint!r}")+++def gridly_source(+ api_key: str,+ view_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],+) -> SourceResponse:+ endpoint_config = GRIDLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ view_id=view_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Records carry no stable datetime (no createdAt/updatedAt), so there's nothing to+ # partition on — this is a full-refresh replace on every sync.+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )+++def validate_credentials(api_key: str, view_id: str) -> tuple[bool, str | None]:+ """Probe the configured view to confirm the key is genuine and can reach the view."""+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{GRIDLY_BASE_URL}/views/{view_id}",+ headers=_headers(api_key),+ timeout=10,+ )+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Gridly API key. Create a new API key in your Gridly company settings, then reconnect."+ if response.status_code == 403:+ return (+ False,+ "Your Gridly API key can't access this view. Grant the key access to the view (or use a "+ "Full Access key), then reconnect.",+ )+ if response.status_code == 404:+ return False, "Gridly view not found. Check the View ID and try again."+ return False, f"Gridly returned an unexpected status code: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.pynew file mode 100644index 000000000000..9129dc8c979c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py@@ -0,0 +1,30 @@+from dataclasses import dataclass, field+++@dataclass+class GridlyEndpointConfig:+ name: str+ # Record and column ids are unique within a view, and a Gridly source targets exactly one+ # view, so `id` is unique table-wide.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ description: str | None = None+++GRIDLY_ENDPOINTS: dict[str, GridlyEndpointConfig] = {+ # The content of the view — one row per Gridly record. Offset/limit paginated. Gridly exposes+ # no server-side timestamp filter on records (there's no createdAt/updatedAt on the record+ # object), so this is full refresh only.+ "records": GridlyEndpointConfig(+ name="records",+ description="Content records of the configured Gridly view. Full refresh only.",+ ),+ # The view's column definitions, read from the view object (`GET /v1/views/{viewId}`). Small,+ # single request, full refresh.+ "columns": GridlyEndpointConfig(+ name="columns",+ description="Column definitions of the configured Gridly view. Full refresh only.",+ ),+}++ENDPOINTS = tuple(GRIDLY_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/source.pyindex 213ab7cae651..2def5dc1008f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/source.py@@ -1,19 +1,39 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GridlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gridly import (+ GridlyResumeConfig,+ gridly_source,+ validate_credentials as validate_gridly_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import ENDPOINTS, GRIDLY_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GridlySource(SimpleSource[GridlySourceConfig]):+class GridlySource(ResumableSource[GridlySourceConfig, GridlyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GRIDLY@@ -24,7 +44,99 @@ class GridlySource(SimpleSource[GridlySourceConfig]):name=SchemaExternalDataSourceType.GRIDLY,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Gridly",- iconPath="/static/services/gridly.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Gridly API key and a View ID to pull that view's records into the PostHog Data warehouse.++Create an API key in your Gridly company settings under **Settings → API keys** (Owner or Admin access is required). Use a **Full Access** or **Read-only** key.++Find the **View ID** in Gridly by opening your grid, selecting a view, and opening the **API** panel — it looks like `v1v9jwwk1lwnkz`. For the default Master branch this is the same as the Grid ID.+""",+ iconPath="/static/services/gridly.png",+ docsUrl="https://posthog.com/docs/cdp/sources/gridly",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="view_id",+ label="View ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="v1v9jwwk1lwnkz",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or insufficiently-scoped API key surfaces as an HTTPError when a page fetch+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the+ # sync. Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.gridly.com": "Your Gridly API key is invalid or has been revoked. Create a new API key in your Gridly company settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.gridly.com": "Your Gridly API key can't access this view. Grant the key access to the view (or use a Full Access key), then reconnect.",+ }++ def get_schemas(+ self,+ config: GridlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Gridly exposes no server-side timestamp filter, so every table is full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=GRIDLY_ENDPOINTS[endpoint].primary_keys,+ should_sync_default=GRIDLY_ENDPOINTS[endpoint].should_sync_default,+ description=GRIDLY_ENDPOINTS[endpoint].description,+ )+ 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: GridlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_gridly_credentials(config.api_key, config.view_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GridlyResumeConfig]:+ return ResumableSourceManager[GridlyResumeConfig](inputs, GridlyResumeConfig)++ def source_for_pipeline(+ self,+ config: GridlySourceConfig,+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gridly_source(+ api_key=config.api_key,+ view_id=config.view_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.pynew file mode 100644index 000000000000..b4ad68481d1b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py@@ -0,0 +1,264 @@+import json+from typing import Any+from urllib.parse import urlparse++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gridly import (+ MAX_RETRY_ATTEMPTS,+ GridlyResumeConfig,+ GridlyRetryableError,+ get_rows,+ gridly_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import ENDPOINTS++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gridly"+++def _records_response(records: list[dict[str, Any]], total: int | None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = records+ resp.headers = {} if total is None else {"X-Total-Count": str(total)}+ resp.status_code = 200+ resp.ok = True+ return resp+++def _view_response(view: dict[str, Any]) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = view+ resp.status_code = 200+ resp.ok = True+ return resp+++def _error_response(status_code: int) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status_code+ resp.ok = False+ resp.reason = "Unauthorized"+ resp.url = "https://api.gridly.com/v1/views/view/records?page=%7B%22offset%22%3A0%7D"+ # _fetch echoes a customer view's record content on error; assert it never reaches logs.+ resp.text = "secret customer record content"+ return resp+++def _manager(resume: GridlyResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestRecordsPagination:+ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_by_offset_and_yields_raw_records(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _records_response([{"id": "1"}, {"id": "2"}], total=3),+ _records_response([{"id": "3"}], total=3),+ ]++ batches = list(get_rows("key", "view", "records", mock.MagicMock(), _manager()))++ # Rows are yielded one page (list) at a time in the shape the API returns them.+ assert batches == [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]++ calls = mock_session.return_value.get.call_args_list+ # The `page` param is a JSON blob with offset advancing by the page length.+ assert json.loads(calls[0].kwargs["params"]["page"]) == {"offset": 0, "limit": 2}+ assert json.loads(calls[1].kwargs["params"]["page"]) == {"offset": 2, "limit": 2}++ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_stops_on_short_page_without_total(self, mock_session):+ # A short page (fewer than the page size) terminates even when X-Total-Count is absent.+ mock_session.return_value.get.return_value = _records_response([{"id": "1"}], total=None)++ batches = list(get_rows("key", "view", "records", mock.MagicMock(), _manager()))++ assert batches == [[{"id": "1"}]]+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_page_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _records_response([], total=0)++ assert list(get_rows("key", "view", "records", mock.MagicMock(), _manager())) == []++ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_saves_state_after_yield_and_not_on_terminal_page(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _records_response([{"id": "1"}, {"id": "2"}], total=3),+ _records_response([{"id": "3"}], total=3),+ ]+ manager = _manager()++ list(get_rows("key", "view", "records", mock.MagicMock(), manager))++ # State is saved once — after the first (full) page, pointing at the next offset — and never+ # after the terminal short page, so a crash re-fetches the last page rather than skipping it.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].offset == 2++ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_offset(self, mock_session):+ mock_session.return_value.get.return_value = _records_response([], total=10)++ list(get_rows("key", "view", "records", mock.MagicMock(), _manager(GridlyResumeConfig(offset=4))))++ first_call = mock_session.return_value.get.call_args_list[0]+ assert json.loads(first_call.kwargs["params"]["page"])["offset"] == 4++ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_sends_apikey_authorization_header(self, mock_session):+ mock_session.return_value.get.return_value = _records_response([], total=0)++ list(get_rows("mykey", "view", "records", mock.MagicMock(), _manager()))++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "ApiKey mykey"+++class TestColumns:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_reads_columns_from_view_object(self, mock_session):+ mock_session.return_value.get.return_value = _view_response(+ {"id": "view", "name": "Food", "columns": [{"id": "c1"}, {"id": "c2"}]}+ )++ batches = list(get_rows("key", "view", "columns", mock.MagicMock(), _manager()))++ assert batches == [[{"id": "c1"}, {"id": "c2"}]]+ url = mock_session.return_value.get.call_args.args[0]+ assert urlparse(url).path == "/v1/views/view"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_view_without_columns_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _view_response({"id": "view", "columns": []})++ assert list(get_rows("key", "view", "columns", mock.MagicMock(), _manager())) == []+++class TestRetries:+ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_retries_retryable_status_then_succeeds(self, mock_session, _sleep):+ mock_session.return_value.get.side_effect = [+ _error_response(500),+ _error_response(429),+ _records_response([{"id": "1"}], total=1),+ ]++ batches = list(get_rows("key", "view", "records", mock.MagicMock(), _manager()))++ assert batches == [[{"id": "1"}]]+ assert mock_session.return_value.get.call_count == 3++ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_retries_exhausted_raises(self, mock_session, _sleep):+ mock_session.return_value.get.return_value = _error_response(500)++ with pytest.raises(GridlyRetryableError):+ list(get_rows("key", "view", "records", mock.MagicMock(), _manager()))++ assert mock_session.return_value.get.call_count == MAX_RETRY_ATTEMPTS++ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_client_error_is_not_retried(self, mock_session, _sleep):+ # A 401/403 can never be fixed by retrying, so it raises immediately (no retry loop).+ mock_session.return_value.get.return_value = _error_response(401)++ with pytest.raises(requests.HTTPError):+ list(get_rows("key", "view", "records", mock.MagicMock(), _manager()))++ assert mock_session.return_value.get.call_count == 1++ @mock.patch("time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_client_error_does_not_leak_response_body_or_query_string(self, mock_session, _sleep):+ # The error body echoes customer record content and the URL carries the `page` blob; neither+ # may reach the raised error (surfaced as latest_error) or the logs.+ response = _error_response(401)+ mock_session.return_value.get.return_value = response+ logger = mock.MagicMock()++ with pytest.raises(requests.HTTPError) as exc_info:+ list(get_rows("key", "view", "records", logger, _manager()))++ raised = str(exc_info.value)+ assert response.text not in raised+ assert "page=" not in raised+ assert raised == "401 Client Error: Unauthorized for url: https://api.gridly.com/v1/views/view/records"++ logged = " ".join(str(call) for call in logger.error.call_args_list)+ assert response.text not in logged+ assert "page=" not in logged+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid",+ [+ (200, True),+ (401, False),+ (403, False),+ (404, False),+ (500, False),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected_valid):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ is_valid, message = validate_credentials("key", "view")++ assert is_valid is expected_valid+ assert (message is None) is expected_valid++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_probes_the_configured_view(self, mock_session):+ response = mock.MagicMock()+ response.status_code = 200+ mock_session.return_value.get.return_value = response++ validate_credentials("key", "myview")++ url = mock_session.return_value.get.call_args.args[0]+ assert urlparse(url).path == "/v1/views/myview"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, message = validate_credentials("key", "view")++ assert is_valid is False+ assert message == "boom"+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = gridly_source("key", "view", endpoint, mock.MagicMock(), mock.MagicMock())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ # No stable datetime on records → nothing to partition on.+ assert response.partition_keys is None+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly_source.pynew file mode 100644index 000000000000..f83007260ad0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly_source.py@@ -0,0 +1,117 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GridlySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gridly import GridlyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.source import GridlySource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gridly.source"+++class TestGridlySource:+ def setup_method(self):+ self.source = GridlySource()+ self.team_id = 123+ self.config = GridlySourceConfig(api_key="key", view_id="view")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GRIDLY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Gridly"+ assert config.label == "Gridly"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/gridly.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "view_id"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static catalog (no I/O), so the source opts into public-docs table listing.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.gridly.com/v1/views/abc",+ "403 Client Error: Forbidden for url: https://api.gridly.com/v1/views/abc/records",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.gridly.com/v1/views/abc/records",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)+ assert all(schema.detected_primary_keys == ["id"] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["records"])+ assert [s.name for s in schemas] == ["records"]++ 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",+ [+ (True, None),+ (False, "Invalid Gridly API key. Create a new API key in your Gridly company settings, then reconnect."),+ ],+ )+ @mock.patch(f"{_SOURCE_MODULE}.validate_gridly_credentials")+ def test_validate_credentials_plumbs_to_transport(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id)++ assert result == mock_return+ mock_validate.assert_called_once_with("key", "view")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is GridlyResumeConfig++ @mock.patch(f"{_SOURCE_MODULE}.gridly_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_gridly_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "records"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_gridly_source.assert_called_once()+ kwargs = mock_gridly_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["view_id"] == "view"+ assert kwargs["endpoint"] == "records"+ assert kwargs["resumable_source_manager"] is manager