: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 giphy import source (#65620)
Tom Owers765b22a02d19
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5f1237aa6ba4..542d8dc84bf8 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -108,6 +108,7 @@ the row lists both.| front | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ || gladly | HTTP | requests | ✅ || gocardless | HTTP | requests | ✅ |@@ -410,7 +411,6 @@ doesn't conflict with concurrent PRs.- freshservice- fulcrum- gainsight_px-- giphy- gitbook- glassfrog- gmaildiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex ca0571b1f8c4..7e741e3c3aa5 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1243,7 +1243,8 @@ class GainsightPxSourceConfig(config.Config):@config.configclass GiphySourceConfig(config.Config):- pass+ api_key: str+ search_query: str | None = None@config.configdiff --git a/posthog/temporal/data_imports/sources/giphy/canonical_descriptions.py b/posthog/temporal/data_imports/sources/giphy/canonical_descriptions.pynew file mode 100644index 000000000000..d96fc7808769--- /dev/null+++ b/posthog/temporal/data_imports/sources/giphy/canonical_descriptions.py@@ -0,0 +1,64 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the official GIPHY API schema docs (https://developers.giphy.com/docs/api/schema/).+# The GIF Object is shared by every trending/search endpoint, so its column descriptions are+# reused across gifs_*/stickers_* tables.+_GIF_OBJECT_COLUMNS: dict[str, str] = {+ "id": "Unique identifier for this GIF.",+ "type": 'The type of object — usually "gif".',+ "slug": "The unique slug used in this GIF's URL.",+ "url": "The unique URL for this GIF.",+ "bitly_url": "The unique bit.ly URL for this GIF.",+ "embed_url": "A URL used for embedding this GIF.",+ "username": "The username this GIF is attached to, if applicable.",+ "source": "The page on which this GIF was found.",+ "rating": "The MPAA-style content rating (y, g, pg, pg-13, r).",+ "title": "The title that appears on giphy.com for this GIF.",+ "import_datetime": "The creation or upload date from this GIF's source.",+ "trending_datetime": "The date this GIF was marked trending, if applicable.",+ "source_tld": "The top level domain of the source URL.",+ "source_post_url": "The URL of the webpage on which this GIF was found.",+ "images": "Object containing the available renditions (sizes/formats) of this GIF.",+ "user": "Object describing the GIPHY user that uploaded this GIF, if any.",+}++_DOCS_URL = "https://developers.giphy.com/docs/api/schema/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "gifs_trending": {+ "description": "The GIFs currently trending on GIPHY, ordered by GIPHY's relevance algorithm.",+ "docs_url": _DOCS_URL,+ "columns": _GIF_OBJECT_COLUMNS,+ },+ "stickers_trending": {+ "description": "The stickers (transparent-background GIFs) currently trending on GIPHY.",+ "docs_url": _DOCS_URL,+ "columns": _GIF_OBJECT_COLUMNS,+ },+ "gifs_search": {+ "description": "GIFs matching the configured search query, ordered by GIPHY's relevance algorithm.",+ "docs_url": _DOCS_URL,+ "columns": _GIF_OBJECT_COLUMNS,+ },+ "stickers_search": {+ "description": "Stickers matching the configured search query, ordered by GIPHY's relevance algorithm.",+ "docs_url": _DOCS_URL,+ "columns": _GIF_OBJECT_COLUMNS,+ },+ "categories": {+ "description": "The GIPHY GIF category taxonomy.",+ "docs_url": _DOCS_URL,+ "columns": {+ "name": "The display name of the category.",+ "name_encoded": "The URL-encoded category name.",+ "subcategories": "A list of subcategories under this category.",+ },+ },+ "trending_search_terms": {+ "description": "The search terms currently trending across GIPHY.",+ "docs_url": _DOCS_URL,+ "columns": {+ "search_term": "A search term currently trending on GIPHY.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/giphy/giphy.py b/posthog/temporal/data_imports/sources/giphy/giphy.pynew file mode 100644index 000000000000..81566a83d213--- /dev/null+++ b/posthog/temporal/data_imports/sources/giphy/giphy.py@@ -0,0 +1,176 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit++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.giphy.settings import GIPHY_ENDPOINTS, GiphyEndpointConfig++GIPHY_BASE_URL = "https://api.giphy.com/v1"+# Beta keys cap search at limit=50; 50 is within every documented endpoint cap+# (trending/search) and works for both beta and production keys.+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+# GIPHY beta keys are rate limited to 100 calls/hour; back off generously on 429.+MAX_RETRY_ATTEMPTS = 5+++class GiphyRetryableError(Exception):+ pass+++class GiphyResumeConfig:+ # GIPHY paginates with a numeric offset. The endpoint and (for search) query+ # are rebuilt deterministically from job inputs on resume, so only the offset+ # needs persisting.+ offset: int+++def _get_session(api_key: str) -> requests.Session:+ # The API key rides in the query string (GIPHY has no header auth), so register it for+ # value-based redaction — otherwise it leaks into tracked request URLs and captured samples.+ return make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,))+++def _build_url(api_key: str, config: GiphyEndpointConfig, offset: int, search_query: str | None) -> str:+ params: dict[str, Any] = {"api_key": api_key}+ if not config.is_term_list:+ params["limit"] = PAGE_SIZE+ params["offset"] = offset+ if config.requires_query:+ params["q"] = search_query+ return f"{GIPHY_BASE_URL}{config.path}?{urlencode(params)}"+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is genuine with one cheap trending request."""+ url = _build_url(api_key, GIPHY_ENDPOINTS["gifs_trending"], offset=0, search_query=None)+ try:+ response = _get_session(api_key).get(url, timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type((GiphyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise GiphyRetryableError(f"GIPHY API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error("GIPHY API error", status=response.status_code, body=response.text)+ # raise_for_status() would embed the full request URL — including the api_key+ # query param — in the exception, which surfaces in the schema's latest_error.+ # Rebuild the error from the path only so the key never leaks.+ safe = urlsplit(response.url)+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",+ response=response,+ )++ return response.json()+++def _normalize_items(config: GiphyEndpointConfig, data: dict[str, Any]) -> list[dict[str, Any]]:+ items = data.get(config.data_key, []) or []+ if config.is_term_list:+ # `/trending/searches` returns a flat list of strings; wrap each so the+ # row has the `search_term` primary-key column.+ return [{"search_term": term} for term in items]+ return list(items)+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GiphyResumeConfig],+ search_query: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GIPHY_ENDPOINTS[endpoint]++ if config.requires_query and not (search_query or "").strip():+ raise ValueError(+ f"GIPHY endpoint '{endpoint}' requires a search query. Set the search query on the source and reconnect."+ )++ session = _get_session(api_key)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config is not None else 0+ if resume_config is not None:+ logger.debug("GIPHY: resuming from offset", endpoint=endpoint, offset=offset)++ while True:+ url = _build_url(api_key, config, offset, search_query)+ data = _fetch_page(session, url, logger)+ items = _normalize_items(config, data)++ if items:+ yield items++ # Term lists and any empty page terminate immediately.+ if config.is_term_list or not items:+ break++ pagination = data.get("pagination") or {}+ count = pagination.get("count")+ page_len = count if isinstance(count, int) else len(items)+ next_offset = offset + page_len++ total_count = pagination.get("total_count")+ if isinstance(total_count, int) and next_offset >= total_count:+ break++ # A short page means we've reached the end of the result set.+ if page_len < PAGE_SIZE:+ break++ # GIPHY caps the offset it will serve; requesting beyond it 400s, so stop+ # rather than fail the sync.+ if config.max_offset is not None and next_offset > config.max_offset:+ logger.debug("GIPHY: reached offset cap", endpoint=endpoint, max_offset=config.max_offset)+ break++ offset = next_offset+ # Save state AFTER yielding so a crash re-yields the last page (merge+ # dedupes on the primary key) rather than skipping it.+ resumable_source_manager.save_state(GiphyResumeConfig(offset=offset))+++def giphy_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GiphyResumeConfig],+ search_query: Optional[str] = None,+) -> SourceResponse:+ config = GIPHY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ search_query=search_query,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )diff --git a/posthog/temporal/data_imports/sources/giphy/settings.py b/posthog/temporal/data_imports/sources/giphy/settings.pynew file mode 100644index 000000000000..d7c8f24fd786--- /dev/null+++ b/posthog/temporal/data_imports/sources/giphy/settings.py@@ -0,0 +1,77 @@+from dataclasses import dataclass++from products.data_warehouse.backend.types import IncrementalField++# GIPHY's content endpoints return current snapshots and expose no server-side+# created_at/updated_at filter, so every endpoint is full-refresh only. The GIF+# object carries `import_datetime`, but there's no `import_datetime_gte`-style+# query param to filter on, so we can't do incremental sync.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}+++@dataclass+class GiphyEndpointConfig:+ name: str+ # Path under the API base (https://api.giphy.com/v1).+ path: str+ # Column(s) that uniquely identify a row across the whole table.+ primary_keys: list[str]+ # Key in the response body the rows live under.+ data_key: str = "data"+ # Largest offset GIPHY will serve for this endpoint. Trending caps at 499 and+ # search at 4999; requesting a larger offset 400s, so pagination stops here.+ max_offset: int | None = None+ # Search endpoints (`/search`) require a `q` query term supplied by the user.+ requires_query: bool = False+ # `/trending/searches` returns a flat list of strings rather than objects and+ # has no pagination, so it's normalized and fetched as a single page.+ is_term_list: bool = False+ # Whether the table is selected for sync by default in the wizard.+ should_sync_default: bool = True+++# GIPHY's public REST API is a content-discovery API, not per-account business+# data, so streams are built around trending content, user-supplied search+# queries, and the category taxonomy.+GIPHY_ENDPOINTS: dict[str, GiphyEndpointConfig] = {+ "gifs_trending": GiphyEndpointConfig(+ name="gifs_trending",+ path="/gifs/trending",+ primary_keys=["id"],+ max_offset=499,+ ),+ "stickers_trending": GiphyEndpointConfig(+ name="stickers_trending",+ path="/stickers/trending",+ primary_keys=["id"],+ max_offset=499,+ ),+ "gifs_search": GiphyEndpointConfig(+ name="gifs_search",+ path="/gifs/search",+ primary_keys=["id"],+ max_offset=4999,+ requires_query=True,+ ),+ "stickers_search": GiphyEndpointConfig(+ name="stickers_search",+ path="/stickers/search",+ primary_keys=["id"],+ max_offset=4999,+ requires_query=True,+ ),+ "categories": GiphyEndpointConfig(+ name="categories",+ path="/gifs/categories",+ primary_keys=["name_encoded"],+ ),+ "trending_search_terms": GiphyEndpointConfig(+ name="trending_search_terms",+ path="/trending/searches",+ primary_keys=["search_term"],+ is_term_list=True,+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(GIPHY_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/giphy/source.py b/posthog/temporal/data_imports/sources/giphy/source.pyindex c8bf3b9d267f..565aa111e84f 100644--- a/posthog/temporal/data_imports/sources/giphy/source.py+++ b/posthog/temporal/data_imports/sources/giphy/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,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.canonical_descriptions import CanonicalDescriptionsfrom 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 GiphySourceConfig+from posthog.temporal.data_imports.sources.giphy.giphy import (+ GiphyResumeConfig,+ giphy_source,+ validate_credentials as validate_giphy_credentials,+)+from posthog.temporal.data_imports.sources.giphy.settings import ENDPOINTS, GIPHY_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class GiphySource(SimpleSource[GiphySourceConfig]):+class GiphySource(ResumableSource[GiphySourceConfig, GiphyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GIPHY@@ -25,7 +38,109 @@ class GiphySource(SimpleSource[GiphySourceConfig]):name=SchemaExternalDataSourceType.GIPHY,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Giphy",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your GIPHY API key to pull trending content, search results, and the category taxonomy into the PostHog Data warehouse.++Create an API key in the [GIPHY Developer Dashboard](https://developers.giphy.com/dashboard/). All GIPHY content is full-refresh only — the API has no incremental sync filter.++The search tables (`gifs_search`, `stickers_search`) only appear once you set a search query below.""",iconPath="/static/services/giphy.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://developers.giphy.com/docs/api",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="search_query",+ label="Search query",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="e.g. cats",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.giphy.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad/banned key surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem. The+ # per-request query/offset varies, but the status text and base host are stable.+ "401 Client Error: Unauthorized for url: https://api.giphy.com": "Your GIPHY API key is invalid or has been revoked. Create a new key in the GIPHY Developer Dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.giphy.com": "Your GIPHY API key has been banned or lacks access. Check the key in the GIPHY Developer Dashboard, then reconnect.",+ # A search table syncing without a query (e.g. the query was cleared after setup) raises a+ # ValueError before any HTTP call. Retrying can't fix missing config, so fail fast.+ "requires a search query": "The search tables (gifs_search, stickers_search) need a search query. Set one on the source and reconnect.",+ }++ def get_schemas(+ self,+ config: GiphySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ has_query = bool((config.search_query or "").strip())++ schemas = []+ for endpoint in ENDPOINTS:+ endpoint_config = GIPHY_ENDPOINTS[endpoint]+ # Search tables can't be populated without a query, so hide them until one is set.+ if endpoint_config.requires_query and not has_query:+ continue+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ description="Full refresh only — GIPHY exposes no incremental sync filter",+ )+ )++ 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: GiphySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_giphy_credentials(config.api_key):+ return True, None++ return False, "Invalid GIPHY API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GiphyResumeConfig]:+ return ResumableSourceManager[GiphyResumeConfig](inputs, GiphyResumeConfig)++ def source_for_pipeline(+ self,+ config: GiphySourceConfig,+ resumable_source_manager: ResumableSourceManager[GiphyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return giphy_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ search_query=config.search_query,)diff --git a/posthog/temporal/data_imports/sources/giphy/tests/test_giphy.py b/posthog/temporal/data_imports/sources/giphy/tests/test_giphy.pynew file mode 100644index 000000000000..f1bb937712af--- /dev/null+++ b/posthog/temporal/data_imports/sources/giphy/tests/test_giphy.py@@ -0,0 +1,283 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.giphy import giphy+from posthog.temporal.data_imports.sources.giphy.giphy import (+ PAGE_SIZE,+ GiphyResumeConfig,+ _build_url,+ _fetch_page,+ _normalize_items,+ get_rows,+ giphy_source,+)+from posthog.temporal.data_imports.sources.giphy.settings import GIPHY_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: GiphyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[GiphyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GiphyResumeConfig | None:+ return self._state++ def save_state(self, data: GiphyResumeConfig) -> None:+ self.saved.append(data)+++def _gif_page(ids: list[str], offset: int, total_count: int) -> dict[str, Any]:+ return {+ "data": [{"id": i, "type": "gif"} for i in ids],+ "pagination": {"offset": offset, "count": len(ids), "total_count": total_count},+ "meta": {"status": 200, "msg": "OK"},+ }+++class TestBuildUrl:+ def test_trending_has_limit_and_offset_no_query(self) -> None:+ url = _build_url("KEY", GIPHY_ENDPOINTS["gifs_trending"], offset=50, search_query=None)+ parsed = urlparse(url)+ params = parse_qs(parsed.query)+ assert parsed.path == "/v1/gifs/trending"+ assert params["api_key"] == ["KEY"]+ assert params["limit"] == [str(PAGE_SIZE)]+ assert params["offset"] == ["50"]+ assert "q" not in params++ def test_search_includes_query(self) -> None:+ url = _build_url("KEY", GIPHY_ENDPOINTS["gifs_search"], offset=0, search_query="cats")+ params = parse_qs(urlparse(url).query)+ assert params["q"] == ["cats"]+ assert params["limit"] == [str(PAGE_SIZE)]++ def test_term_list_has_no_pagination_params(self) -> None:+ url = _build_url("KEY", GIPHY_ENDPOINTS["trending_search_terms"], offset=0, search_query=None)+ params = parse_qs(urlparse(url).query)+ assert params["api_key"] == ["KEY"]+ assert "limit" not in params+ assert "offset" not in params+++class TestNormalizeItems:+ def test_object_endpoint_passthrough(self) -> None:+ data = {"data": [{"id": "a"}, {"id": "b"}]}+ assert _normalize_items(GIPHY_ENDPOINTS["gifs_trending"], data) == [{"id": "a"}, {"id": "b"}]++ def test_term_list_wraps_strings(self) -> None:+ data = {"data": ["cats", "dogs"]}+ assert _normalize_items(GIPHY_ENDPOINTS["trending_search_terms"], data) == [+ {"search_term": "cats"},+ {"search_term": "dogs"},+ ]++ def test_missing_data_key_is_empty(self) -> None:+ assert _normalize_items(GIPHY_ENDPOINTS["gifs_trending"], {"meta": {}}) == []+++class TestGetRows:+ @staticmethod+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any) -> list[dict]:+ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ # Key the fake pages by the offset query param so tests stay URL-order agnostic.+ offset = parse_qs(urlparse(url).query).get("offset", ["0"])[0]+ return pages[offset]++ monkeypatch.setattr(giphy, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ api_key="KEY",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows++ def test_paginates_until_total_count_reached(self, monkeypatch: Any) -> None:+ pages = {+ "0": _gif_page([str(i) for i in range(PAGE_SIZE)], offset=0, total_count=PAGE_SIZE + 2),+ str(PAGE_SIZE): _gif_page(["x", "y"], offset=PAGE_SIZE, total_count=PAGE_SIZE + 2),+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages, endpoint="gifs_trending")+ assert len(rows) == PAGE_SIZE + 2+ assert rows[-1] == {"id": "y", "type": "gif"}++ def test_stops_on_short_page(self, monkeypatch: Any) -> None:+ # A page shorter than PAGE_SIZE means the result set is exhausted.+ pages = {"0": _gif_page(["a", "b"], offset=0, total_count=999)}+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages, endpoint="gifs_trending")+ assert [r["id"] for r in rows] == ["a", "b"]++ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:+ pages = {"0": _gif_page([], offset=0, total_count=0)}+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages, endpoint="gifs_trending")+ assert rows == []++ def test_stops_at_offset_cap(self, monkeypatch: Any) -> None:+ # gifs_trending caps at offset 499. A full page lands next_offset at 500 > 499, so we stop+ # without ever requesting an offset GIPHY would reject, even though total_count is far larger.+ cap = GIPHY_ENDPOINTS["gifs_trending"].max_offset+ assert cap == 499+ requested_offsets: list[int] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ offset = int(parse_qs(urlparse(url).query)["offset"][0])+ requested_offsets.append(offset)+ return _gif_page([f"{offset}_{i}" for i in range(PAGE_SIZE)], offset=offset, total_count=10_000)++ monkeypatch.setattr(giphy, "_fetch_page", fake_fetch)+ list(+ get_rows(+ api_key="KEY",+ endpoint="gifs_trending",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert max(requested_offsets) <= cap+ assert max(requested_offsets) + PAGE_SIZE > cap++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ pages = {+ str(PAGE_SIZE): _gif_page(["x", "y"], offset=PAGE_SIZE, total_count=PAGE_SIZE + 2),+ }+ manager = _FakeResumableManager(GiphyResumeConfig(offset=PAGE_SIZE))+ rows = self._collect(manager, monkeypatch, pages, endpoint="gifs_trending")+ assert [r["id"] for r in rows] == ["x", "y"]++ def test_saves_state_after_each_batch(self, monkeypatch: Any) -> None:+ pages = {+ "0": _gif_page([str(i) for i in range(PAGE_SIZE)], offset=0, total_count=PAGE_SIZE + 1),+ str(PAGE_SIZE): _gif_page(["last"], offset=PAGE_SIZE, total_count=PAGE_SIZE + 1),+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages, endpoint="gifs_trending")+ # State is saved once, advancing to the second page's offset, before that page is fetched.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_term_list_single_fetch(self, monkeypatch: Any) -> None:+ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ return {"data": ["cats", "dogs", "memes"], "meta": {"status": 200}}++ monkeypatch.setattr(giphy, "_fetch_page", fake_fetch)+ manager = _FakeResumableManager()+ rows = [+ r+ for batch in get_rows(+ api_key="KEY",+ endpoint="trending_search_terms",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ for r in batch+ ]+ assert rows == [{"search_term": "cats"}, {"search_term": "dogs"}, {"search_term": "memes"}]+ assert manager.saved == []++ @parameterized.expand(["gifs_search", "stickers_search"])+ def test_search_without_query_raises(self, endpoint: str) -> None:+ with pytest.raises(ValueError, match="requires a search query"):+ list(+ get_rows(+ api_key="KEY",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ search_query=" ",+ )+ )+++class TestGiphySourceResponse:+ @parameterized.expand(+ [+ ("gifs_trending", ["id"]),+ ("stickers_trending", ["id"]),+ ("gifs_search", ["id"]),+ ("stickers_search", ["id"]),+ ("categories", ["name_encoded"]),+ ("trending_search_terms", ["search_term"]),+ ]+ )+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:+ response = giphy_source(+ api_key="KEY",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ search_query="cats",+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys++ def test_full_refresh_sort_mode_default_ascending(self) -> None:+ response = giphy_source(+ api_key="KEY",+ endpoint="gifs_trending",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.sort_mode == "asc"+++class TestFetchPageErrorHandling:+ def test_client_error_does_not_leak_api_key(self) -> None:+ # The api_key rides in the query string, so raise_for_status() would put it in+ # the exception message, which lands in the schema's latest_error.+ api_key = "super-secret-key"+ response = MagicMock()+ response.status_code = 400+ response.ok = False+ response.reason = "Bad Request"+ response.text = "invalid request"+ response.url = f"https://api.giphy.com/v1/gifs/search?api_key={api_key}&q=cats"++ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page(session, response.url, MagicMock())++ assert api_key not in str(exc_info.value)+ assert "api.giphy.com/v1/gifs/search" in str(exc_info.value)+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ def test_status_maps_to_validity(self, monkeypatch: Any, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ monkeypatch.setattr(giphy, "_get_session", lambda *_: session)+ assert giphy.validate_credentials("KEY") is expected++ def test_network_error_is_invalid(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ monkeypatch.setattr(giphy, "_get_session", lambda *_: session)+ assert giphy.validate_credentials("KEY") is False+++class TestSessionRedaction:+ def test_api_key_registered_for_redaction(self, monkeypatch: Any) -> None:+ # The key travels in the query string, so it must be passed to make_tracked_session as a+ # redacted value — otherwise it leaks into tracked URLs/samples.+ captured: dict[str, Any] = {}++ def fake_make_session(**kwargs: Any) -> Any:+ captured.update(kwargs)+ return MagicMock()++ monkeypatch.setattr(giphy, "make_tracked_session", fake_make_session)+ giphy._get_session("super-secret-key")+ assert captured["redact_values"] == ("super-secret-key",)diff --git a/posthog/temporal/data_imports/sources/giphy/tests/test_giphy_source.py b/posthog/temporal/data_imports/sources/giphy/tests/test_giphy_source.pynew file mode 100644index 000000000000..c25825b37d00--- /dev/null+++ b/posthog/temporal/data_imports/sources/giphy/tests/test_giphy_source.py@@ -0,0 +1,154 @@+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 GiphySourceConfig+from posthog.temporal.data_imports.sources.giphy.giphy import GiphyResumeConfig+from posthog.temporal.data_imports.sources.giphy.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.giphy.source import GiphySource++from products.data_warehouse.backend.types import ExternalDataSourceType++# Endpoints that need a user-supplied search query (hidden until one is set).+SEARCH_ENDPOINTS = {"gifs_search", "stickers_search"}+++class TestGiphySource:+ def setup_method(self):+ self.source = GiphySource()+ self.team_id = 123+ self.config = GiphySourceConfig(api_key="key", search_query=None)+ self.config_with_query = GiphySourceConfig(api_key="key", search_query="cats")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GIPHY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Giphy"+ assert config.label == "Giphy"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/giphy.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "search_query"]++ def test_api_key_field_is_secret_password_required(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_search_query_field_is_optional_text(self):+ config = self.source.get_source_config+ query_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "search_query"+ )+ assert query_field.type == SourceFieldInputConfigType.TEXT+ assert query_field.required is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.giphy.com/v1/gifs/trending?api_key=x&limit=50&offset=0",+ "403 Client Error: Forbidden for url: https://api.giphy.com/v1/gifs/search?api_key=x&q=cats",+ ],+ )+ 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)++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.giphy.com/v1/gifs/trending",+ "HTTPSConnectionPool(host='api.giphy.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_missing_search_query_error_is_non_retryable(self):+ # The ValueError raised when a search table syncs without a query must fail fast, not retry.+ observed_error = (+ "GIPHY endpoint 'gifs_search' requires a search query. Set the search query on the source and reconnect."+ )+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_get_schemas_hides_search_without_query(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ names = {s.name for s in schemas}+ assert names == set(ENDPOINTS) - SEARCH_ENDPOINTS++ def test_get_schemas_shows_search_with_query(self):+ schemas = self.source.get_schemas(self.config_with_query, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_schemas_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config_with_query, self.team_id)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_trending_search_terms_off_by_default(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config_with_query, self.team_id)}+ assert schemas["trending_search_terms"].should_sync_default is False+ assert schemas["gifs_trending"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config_with_query, self.team_id, names=["gifs_search"])+ assert [s.name for s in schemas] == ["gifs_search"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config_with_query, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid GIPHY API key"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.giphy.source.validate_giphy_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ 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+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GiphyResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.giphy.source.giphy_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_giphy_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "gifs_search"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config_with_query, manager, inputs)++ mock_giphy_source.assert_called_once()+ kwargs = mock_giphy_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "gifs_search"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["search_query"] == "cats"++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)+ for endpoint in ENDPOINTS:+ assert descriptions[endpoint]["description"]