Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement imagga import source (#70003)

Tom Owers6fdb0d5a2cde
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index c484ef942c62..1ff451eafa92 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -211,6 +211,7 @@ the row lists both.
| hubspot | HTTP | requests | ✅ |
| hugging_face | HTTP | requests | ✅ |
| huntr | HTTP | requests | ✅ |
+| imagga | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
| inflowinventory | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
@@ -610,7 +611,6 @@ doesn't conflict with concurrent PRs.
- hyperspell
- ikas
- illumina_basespace
-- imagga
- impact
- infisical
- infor_nexus
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 5a3588571b0d..b843e4b46faf 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
@@ -1808,7 +1808,8 @@ class IlluminaBasespaceSourceConfig(config.Config):
@config.config
class ImaggaSourceConfig(config.Config):
- pass
+ api_key: str
+ api_secret: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/canonical_descriptions.py
new file mode 100644
index 000000000000..3310912b4918
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/canonical_descriptions.py
@@ -0,0 +1,33 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from Imagga's public API docs (https://docs.imagga.com/#usage). The /usage response is
+# normalized into two tables; column names below reflect that normalization (nested objects are
+# flattened with a `<key>_` prefix, and the daily histogram is exploded into rows).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "usage": {
+ "description": "Current billing-period consumption snapshot for the Imagga account: request and processed counters, the monthly request limit, and concurrency.",
+ "docs_url": "https://docs.imagga.com/#usage",
+ "columns": {
+ "billing_period_start": "Start of the current billing period.",
+ "billing_period_end": "End of the current billing period.",
+ "monthly_limit": "Maximum number of requests allowed in the current billing period under the account's plan.",
+ "daily_requests": "Number of API requests made so far on the reference day.",
+ "daily_processed": "Number of items processed so far on the reference day (a single request can process multiple items).",
+ "daily_for": "The day the daily_* counters refer to.",
+ "last_usage": "Unix timestamp of the account's most recent API usage.",
+ "concurrency_now": "Number of requests currently being processed concurrently.",
+ "concurrency_max": "Maximum number of concurrent requests allowed by the account's plan.",
+ },
+ },
+ "daily_usage": {
+ "description": "Per-day usage history for the Imagga account, one row per day.",
+ "docs_url": "https://docs.imagga.com/#usage",
+ "columns": {
+ "date": "Calendar day (UTC) the usage count refers to.",
+ "timestamp": "Unix-second timestamp of the day, as returned by Imagga.",
+ "count": "Number of API requests recorded for the day.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/imagga.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/imagga.py
new file mode 100644
index 000000000000..1317bb76ccb0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/imagga.py
@@ -0,0 +1,174 @@
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.imagga.settings import IMAGGA_ENDPOINTS
+
+BASE_URL = "https://api.imagga.com/v2"
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# The /usage result carries two histogram objects keyed by period -> count (`daily`, `monthly`).
+# Their key set changes every period, so folding them into the flat snapshot row would drift the
+# column width sync to sync. They're kept out of the `usage` snapshot; the per-day series is exposed
+# through the dedicated `daily_usage` table instead.
+_HISTOGRAM_KEYS = frozenset({"daily", "monthly"})
+
+
+class ImaggaRetryableError(Exception):
+ pass
+
+
+def _headers() -> dict[str, str]:
+ return {"Accept": "application/json"}
+
+
+def _fetch_usage(
+ session: requests.Session, api_key: str, api_secret: str, logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ """Fetch GET /usage and return its ``result`` object.
+
+ ``concurrency=1`` asks Imagga to include the concurrency block (current vs max) alongside the
+ usage counters. Credentials travel in the Basic-auth header, not the URL, so a non-2xx error's
+ URL is safe to surface unredacted.
+ """
+ url = f"{BASE_URL}/usage?concurrency=1"
+ response = session.get(url, auth=(api_key, api_secret), headers=_headers(), timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ImaggaRetryableError(f"Imagga API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Imagga API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ body = response.json()
+ result = body.get("result") if isinstance(body, dict) else None
+ return result if isinstance(result, dict) else {}
+
+
+def validate_credentials(api_key: str, api_secret: str) -> bool:
+ """Confirm the key/secret pair is genuine with a single GET /usage. 200 = valid; 401/403 = not."""
+ try:
+ session = make_tracked_session(redact_values=(api_secret,) if api_secret else ())
+ response = session.get(f"{BASE_URL}/usage", auth=(api_key, api_secret), headers=_headers(), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _usage_snapshot_row(result: dict[str, Any]) -> dict[str, Any]:
+ """Flatten the /usage result into one row of stable, flat-width scalar fields.
+
+ The histogram objects (`daily`, `monthly`) are excluded — their keys change every period. Nested
+ scalar objects such as ``concurrency`` are flattened with a ``<key>_`` prefix (e.g.
+ ``concurrency_max``); anything still nested is dropped so the snapshot stays a flat row.
+ """
+ row: dict[str, Any] = {}
+ for key, value in result.items():
+ if key in _HISTOGRAM_KEYS:
+ continue
+ if isinstance(value, dict):
+ for sub_key, sub_value in value.items():
+ if not isinstance(sub_value, dict | list):
+ row[f"{key}_{sub_key}"] = sub_value
+ elif not isinstance(value, list):
+ row[key] = value
+ return row
+
+
+def _daily_usage_rows(result: dict[str, Any]) -> list[dict[str, Any]]:
+ """Explode the `daily` usage histogram into one row per day.
+
+ Imagga keys the histogram by unix-second timestamp (as a string) mapped to the day's usage count.
+ Rows are sorted ascending by day to match ``sort_mode="asc"``. Unparseable keys are skipped
+ rather than failing the sync.
+ """
+ daily = result.get("daily")
+ if not isinstance(daily, dict):
+ return []
+
+ rows: list[dict[str, Any]] = []
+ for ts_key, count in daily.items():
+ try:
+ timestamp = int(ts_key)
+ except (TypeError, ValueError):
+ continue
+ day = datetime.fromtimestamp(timestamp, tz=UTC).date().isoformat()
+ rows.append({"date": day, "timestamp": timestamp, "count": count})
+
+ rows.sort(key=lambda r: r["date"])
+ return rows
+
+
+def get_rows(
+ api_key: str,
+ api_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ # The tenacity wrapper below is the single retry authority for this session, so disable the
+ # transport-level status retries (`make_tracked_session`'s DEFAULT_RETRY already retries 429/5xx).
+ # Otherwise both layers retry a rate-limit response and one 429 fans out into far more requests.
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_secret,) if api_secret else ())
+
+ @retry(
+ retry=retry_if_exception_type((ImaggaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch() -> dict[str, Any]:
+ return _fetch_usage(session, api_key, api_secret, logger)
+
+ result = fetch()
+
+ if endpoint == "usage":
+ row = _usage_snapshot_row(result)
+ if not row:
+ return
+ # The `usage` table merges on `billing_period_start`. If Imagga returns a result without it,
+ # yielding the row anyway makes the warehouse merge fail permanently on a missing key column;
+ # skip and log instead so a malformed response degrades to an empty sync, not a hard failure.
+ missing_keys = [key for key in IMAGGA_ENDPOINTS["usage"].primary_keys if key not in row]
+ if missing_keys:
+ logger.warning(f"Imagga /usage response missing primary key(s) {missing_keys}; skipping snapshot row")
+ return
+ yield [row]
+ return
+
+ if endpoint == "daily_usage":
+ rows = _daily_usage_rows(result)
+ if rows:
+ yield rows
+ return
+
+ raise ValueError(f"Unknown Imagga endpoint: {endpoint}")
+
+
+def imagga_source(
+ api_key: str,
+ api_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = IMAGGA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, api_secret=api_secret, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_keys=config.partition_keys,
+ partition_mode=config.partition_mode,
+ partition_format=config.partition_format,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/settings.py
new file mode 100644
index 000000000000..1d6e46607e21
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/settings.py
@@ -0,0 +1,47 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ PartitionFormat,
+ PartitionMode,
+)
+
+
+@dataclass
+class ImaggaEndpointConfig:
+ name: str
+ # Fields the rows are merged on. Imagga's /usage endpoint has no record ids, so the keys are
+ # derived from the shape we normalize to (the billing period for the snapshot, the day for the
+ # per-day series). Both endpoints are full-refresh only, so these keys mainly document intent.
+ primary_keys: list[str]
+ partition_keys: list[str] | None = None
+ partition_mode: PartitionMode | None = None
+ partition_format: PartitionFormat | None = None
+ should_sync_default: bool = True
+ description: str | None = None
+
+
+# Imagga is an on-demand image-inference API (tagging, categorization, cropping, faces, OCR, content
+# moderation), not a record-oriented dataset provider — there are no list/export endpoints that emit
+# rows for a warehouse. The only pollable account data is GET /usage, which returns the current
+# billing-period consumption plus a per-day usage histogram. We surface that single response as two
+# tables: a flat snapshot and the exploded daily series. Neither exposes a server-side timestamp
+# filter, so both are full refresh only (no incremental sync, no pagination, no cursors).
+IMAGGA_ENDPOINTS: dict[str, ImaggaEndpointConfig] = {
+ "usage": ImaggaEndpointConfig(
+ name="usage",
+ primary_keys=["billing_period_start"],
+ description="Current billing-period consumption snapshot: request and processed counters, the monthly request limit, and concurrency (current vs max). One row, full refresh.",
+ ),
+ "daily_usage": ImaggaEndpointConfig(
+ name="daily_usage",
+ primary_keys=["date"],
+ # `date` is a calendar day derived from the usage histogram — historical days never move, so
+ # it's a stable partition key.
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="month",
+ description="Per-day request counts from the account's usage history, one row per day ({date, timestamp, count}). Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(IMAGGA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/source.py
index 2a34b389c988..4651e698c634 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/source.py
@@ -1,19 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+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, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ImaggaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga import (
+ imagga_source,
+ validate_credentials as validate_imagga_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.settings import IMAGGA_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class ImaggaSource(SimpleSource[ImaggaSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.IMAGGA
@@ -24,7 +42,100 @@ class ImaggaSource(SimpleSource[ImaggaSourceConfig]):
name=SchemaExternalDataSourceType.IMAGGA,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Imagga",
- iconPath="/static/services/imagga.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Imagga API credentials to pull your account's usage statistics into the PostHog Data warehouse.
+
+Find your API key and secret in the [Imagga dashboard](https://imagga.com/profile/dashboard).
+
+Imagga is an on-demand image-recognition API, so the only account data available to sync is your API consumption (from `GET /usage`): the current billing-period request counters, your monthly limit, and per-day usage.""",
+ iconPath="/static/services/imagga.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/imagga",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acc_...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Invalid or missing credentials surface as a 401 when `_fetch_usage` calls
+ # `raise_for_status()`. Imagga uses 403 when the key is valid but the account can't access
+ # the resource. Neither can be fixed by retrying, 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.imagga.com": "Your Imagga API key or secret is invalid. Copy the correct credentials from your Imagga dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.imagga.com": "Your Imagga account does not have access to this resource. Check your plan and credentials in the Imagga dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ImaggaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Both endpoints are full refresh only: Imagga's /usage response exposes no server-side
+ # timestamp filter, so there is no cursor to sync incrementally.
+ schemas = [
+ SourceSchema(
+ name=endpoint_config.name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+ for endpoint_config in IMAGGA_ENDPOINTS.values()
+ ]
+
+ 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: ImaggaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_imagga_credentials(config.api_key, config.api_secret):
+ return True, None
+
+ # The probe also returns False on transient network/timeout errors, so don't claim the
+ # credentials are definitively wrong — point at both possibilities.
+ return (
+ False,
+ "Unable to verify your Imagga credentials. Check that the API key and secret are correct and that api.imagga.com is reachable.",
+ )
+
+ def source_for_pipeline(self, config: ImaggaSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return imagga_source(
+ api_key=config.api_key,
+ api_secret=config.api_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga.py
new file mode 100644
index 000000000000..24314c506636
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga.py
@@ -0,0 +1,206 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga import (
+ BASE_URL,
+ ImaggaRetryableError,
+ _daily_usage_rows,
+ _fetch_usage,
+ _usage_snapshot_row,
+ get_rows,
+ imagga_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.settings import IMAGGA_ENDPOINTS
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = ""):
+ self.status_code = status_code
+ self._json_data = json_data
+ self.text = text
+ self.url: str = ""
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> Any:
+ return self._json_data
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]
+
+
+class _FakeSession:
+ def __init__(self, responses: list[_FakeResponse]):
+ self._responses = list(responses)
+ self.get_calls: list[dict[str, Any]] = []
+
+ def get(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.get_calls.append({"url": url, **kwargs})
+ response = self._responses.pop(0)
+ response.url = url
+ return response
+
+
+# A representative /usage result, shaped after Imagga's public docs example.
+_USAGE_RESULT = {
+ "billing_period_start": "18 of Oct, 2018",
+ "billing_period_end": "18 of Nov, 2018",
+ "monthly_limit": 2000,
+ "daily_for": "23 of Oct, 2018",
+ "daily_processed": 3,
+ "daily_requests": 3,
+ "last_usage": 1540300613,
+ "concurrency": {"max": 2, "now": 1},
+ "daily": {"1519603200": 1, "1540252800": 3},
+ "monthly": {"2018-10": 30},
+}
+
+
+class TestUsageSnapshotRow:
+ def test_flattens_concurrency_and_excludes_histograms(self) -> None:
+ row = _usage_snapshot_row(_USAGE_RESULT)
+ # Nested concurrency scalars are flattened with a prefix.
+ assert row["concurrency_max"] == 2
+ assert row["concurrency_now"] == 1
+ # Scalars are carried through unchanged.
+ assert row["billing_period_start"] == "18 of Oct, 2018"
+ assert row["monthly_limit"] == 2000
+ # The period-keyed histograms must stay out of the flat row, or the column set drifts each sync.
+ assert "daily" not in row
+ assert "monthly" not in row
+
+ def test_empty_result_yields_empty_row(self) -> None:
+ assert _usage_snapshot_row({}) == {}
+
+
+class TestDailyUsageRows:
+ def test_explodes_histogram_to_sorted_dated_rows(self) -> None:
+ rows = _daily_usage_rows(_USAGE_RESULT)
+ # Unix-second keys become calendar days, ascending to keep sort_mode="asc" honest.
+ assert rows == [
+ {"date": "2018-02-26", "timestamp": 1519603200, "count": 1},
+ {"date": "2018-10-23", "timestamp": 1540252800, "count": 3},
+ ]
+
+ @parameterized.expand([("missing", {}), ("wrong_type", {"daily": []}), ("null", {"daily": None})])
+ def test_returns_empty_when_no_daily_histogram(self, _name: str, result: dict[str, Any]) -> None:
+ assert _daily_usage_rows(result) == []
+
+ def test_skips_unparseable_timestamp_keys(self) -> None:
+ rows = _daily_usage_rows({"daily": {"not-a-timestamp": 5, "1519603200": 1}})
+ assert [r["timestamp"] for r in rows] == [1519603200]
+
+
+class TestFetchUsage:
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status)])
+ with pytest.raises(ImaggaRetryableError):
+ _fetch_usage(session, "key", "secret", mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_client_error_raises_http_error(self) -> None:
+ session = _FakeSession([_FakeResponse(status_code=401, text="unauthorized")])
+ with pytest.raises(requests.HTTPError):
+ _fetch_usage(session, "key", "secret", mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_returns_result_object_and_sends_basic_auth(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"result": _USAGE_RESULT, "status": {"type": "success"}})])
+ result = _fetch_usage(session, "key", "secret", mock.MagicMock()) # type: ignore[arg-type]
+ assert result == _USAGE_RESULT
+ # Credentials must ride in the Basic-auth header, not the URL.
+ assert session.get_calls[0]["auth"] == ("key", "secret")
+ assert session.get_calls[0]["url"] == f"{BASE_URL}/usage?concurrency=1"
+
+ @parameterized.expand([("missing_result", {"status": {}}), ("null_result", {"result": None}), ("not_a_dict", [])])
+ def test_missing_result_returns_empty_dict(self, _name: str, body: Any) -> None:
+ session = _FakeSession([_FakeResponse(json_data=body)])
+ assert _fetch_usage(session, "key", "secret", mock.MagicMock()) == {} # type: ignore[arg-type]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga.make_tracked_session")
+ def test_status_mapping(self, _name: str, status: int, expected: bool, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _FakeResponse(status_code=status)
+ assert validate_credentials("key", "secret") is expected
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga.make_tracked_session")
+ def test_exception_returns_false(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ assert validate_credentials("key", "secret") is False
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga.make_tracked_session")
+ def test_redacts_secret_and_uses_basic_auth(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _FakeResponse(status_code=200)
+ validate_credentials("key", "secret")
+ # The secret is masked by value in logs/samples, and travels via Basic auth.
+ assert mock_session.call_args.kwargs["redact_values"] == ("secret",)
+ assert mock_session.return_value.get.call_args.kwargs["auth"] == ("key", "secret")
+
+
+class TestGetRows:
+ def _run(self, endpoint: str, result: dict[str, Any]) -> list[Any]:
+ session = _FakeSession([_FakeResponse(json_data={"result": result})])
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.imagga.imagga.make_tracked_session",
+ return_value=session,
+ ):
+ return list(get_rows("key", "secret", endpoint, mock.MagicMock()))
+
+ def test_usage_yields_single_snapshot_row(self) -> None:
+ batches = self._run("usage", _USAGE_RESULT)
+ assert len(batches) == 1
+ assert len(batches[0]) == 1
+ assert batches[0][0]["billing_period_start"] == "18 of Oct, 2018"
+
+ def test_daily_usage_yields_exploded_rows(self) -> None:
+ batches = self._run("daily_usage", _USAGE_RESULT)
+ assert [r["date"] for r in batches[0]] == ["2018-02-26", "2018-10-23"]
+
+ @parameterized.expand([("usage", {}), ("daily_usage", {})])
+ def test_empty_result_yields_nothing(self, endpoint: str, result: dict[str, Any]) -> None:
+ assert self._run(endpoint, result) == []
+
+ def test_usage_without_primary_key_yields_nothing(self) -> None:
+ # A non-empty snapshot missing `billing_period_start` must not be yielded — merging on an
+ # absent primary key column fails the sync permanently instead of producing an empty batch.
+ result = {"monthly_limit": 2000, "concurrency": {"max": 2, "now": 1}}
+ assert self._run("usage", result) == []
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError):
+ self._run("nope", _USAGE_RESULT)
+
+
+class TestImaggaSourceResponse:
+ @parameterized.expand([("usage", ["billing_period_start"]), ("daily_usage", ["date"])])
+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = imagga_source("key", "secret", endpoint, mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == "asc"
+
+ def test_daily_usage_partitions_on_stable_date(self) -> None:
+ response = imagga_source("key", "secret", "daily_usage", mock.MagicMock())
+ assert response.partition_keys == ["date"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+
+ def test_usage_snapshot_is_not_partitioned(self) -> None:
+ response = imagga_source("key", "secret", "usage", mock.MagicMock())
+ assert response.partition_keys is None
+
+ def test_every_settings_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in IMAGGA_ENDPOINTS:
+ response = imagga_source("key", "secret", endpoint, mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == IMAGGA_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga_source.py
new file mode 100644
index 000000000000..182962a476fe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/imagga/tests/test_imagga_source.py
@@ -0,0 +1,111 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ImaggaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.imagga.source import ImaggaSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestImaggaSource:
+ def setup_method(self) -> None:
+ self.source = ImaggaSource()
+ self.team_id = 123
+ self.config = ImaggaSourceConfig(api_key="acc_test", api_secret="secret_test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.IMAGGA
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Imagga"
+ assert config.label == "Imagga"
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Kept behind the unreleased flag until the source has been exercised end to end.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/imagga"
+ assert [f.name for f in config.fields] == ["api_key", "api_secret"]
+
+ def test_api_secret_is_a_secret_password_field(self) -> None:
+ # The secret must never render as plain text or be treated as non-sensitive by the serializer.
+ field = next(f for f in self.source.get_source_config.fields if f.name == "api_secret")
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog with no I/O — safe to surface in public docs.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_full_refresh_only(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # /usage exposes no server-side timestamp filter, so nothing may advertise incremental/append —
+ # a client-side cursor over a single snapshot request is not incremental.
+ 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_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["daily_usage"])
+ assert [s.name for s in schemas] == ["daily_usage"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "observed_error,should_match",
+ [
+ ("401 Client Error: Unauthorized for url: https://api.imagga.com/v2/usage?concurrency=1", True),
+ ("403 Client Error: Forbidden for url: https://api.imagga.com/v2/usage", True),
+ ("429 Client Error: Too Many Requests for url: https://api.imagga.com/v2/usage", False),
+ ("500 Server Error for url: https://api.imagga.com/v2/usage", False),
+ ],
+ )
+ def test_non_retryable_errors_match_only_auth_failures(self, observed_error: str, should_match: bool) -> None:
+ matched = any(key in observed_error for key in self.source.get_non_retryable_errors())
+ assert matched is should_match
+
+ @pytest.mark.parametrize(
+ "probe_result,expected_valid",
+ [(True, True), (False, False)],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.imagga.source.validate_imagga_credentials"
+ )
+ def test_validate_credentials(
+ self, mock_validate: mock.MagicMock, probe_result: bool, expected_valid: bool
+ ) -> None:
+ mock_validate.return_value = probe_result
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert (error_message is None) is expected_valid
+ mock_validate.assert_called_once_with("acc_test", "secret_test")
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.imagga.source.imagga_source")
+ def test_source_for_pipeline_plumbs_credentials_and_endpoint(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "daily_usage"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "acc_test"
+ assert kwargs["api_secret"] == "secret_test"
+ assert kwargs["endpoint"] == "daily_usage"
+
+ def test_canonical_descriptions_cover_all_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)