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 judgeme_reviews import source (#69342)

Tom Owersc1fccbaf249e
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 8a9c1db5df7f..1ae8eb80bdfd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -204,6 +204,7 @@ the row lists both.
| jira | HTTP | requests | ✅ |
| jobnimbus | HTTP | requests | ✅ |
| jotform | HTTP | requests | ✅ |
+| judgeme_reviews | HTTP | requests | ✅ |
| justcall | HTTP | requests | ✅ |
| justsift | HTTP | requests | ✅ |
| k6_cloud | HTTP | requests | ✅ |
@@ -561,6 +562,7 @@ doesn't conflict with concurrent PRs.
- jamf_pro
- jobber
- judgeme_reviews
+- justsift
- kafka
- keka
- kisi
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 80e216ef484a..2de0a2bf2302 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
@@ -1796,7 +1796,8 @@ class JotformSourceConfig(config.Config):
@config.config
class JudgeMeReviewsSourceConfig(config.Config):
- pass
+ shop_domain: str
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/canonical_descriptions.py
new file mode 100644
index 000000000000..c9cae768bd72
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/canonical_descriptions.py
@@ -0,0 +1,49 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Judge.me API docs (https://judge.me/api/docs).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "reviews": {
+ "description": "A product or store review left by a shopper, including its rating, moderation state, and media.",
+ "docs_url": "https://judge.me/api/docs",
+ "columns": {
+ "id": "Judge.me internal ID of the review.",
+ "title": "Raw review title as submitted by the reviewer (not sanitized).",
+ "body": "Raw review body as submitted by the reviewer (not sanitized).",
+ "rating": "Star rating given by the reviewer, from 1 to 5.",
+ "pinned": "Whether the review is pinned to the top of the review widget.",
+ "product_external_id": "External (e.g. Shopify) ID of the reviewed product. Empty for store reviews.",
+ "product_title": "Title of the reviewed product.",
+ "product_handle": "URL handle of the reviewed product.",
+ "reviewer": "The reviewer who left the review (internal ID, name, email, phone, tags).",
+ "source": "Where the review originates (e.g. email, web). Some sources imply the review is verified.",
+ "curated": "Curated status: ok (published on the storefront), spam (not published), or not-yet (awaiting curation).",
+ "hidden": "Whether the review is archived to the Archived tab in the Reviews dashboard.",
+ "verified": "Verified status of the review (e.g. buyer, confirmed-buyer, verified-purchase, nothing).",
+ "created_at": "When the review was created.",
+ "updated_at": "When the review was last updated.",
+ "ip_address": "IP address the review was submitted from.",
+ "has_published_pictures": "Whether the review contains published pictures.",
+ "has_published_videos": "Whether the review contains published videos.",
+ "pictures": "Pictures attached to the review, with per-size URLs and hidden flags.",
+ },
+ },
+ "products": {
+ "description": "A product known to Judge.me for this shop, mapping Judge.me internal product IDs to the external store catalog.",
+ "docs_url": "https://judge.me/api/docs",
+ "columns": {
+ "id": "Judge.me internal ID of the product.",
+ "external_id": "External (e.g. Shopify) ID of the product.",
+ "title": "Title of the product.",
+ "handle": "URL handle of the product.",
+ "vendor": "Vendor of the product.",
+ "product_type": "Type/category of the product.",
+ "description": "Description of the product.",
+ "in_store": "Whether the product is published on the storefront.",
+ "excluded": "Whether Judge.me excludes this product from review request emails.",
+ "image_url": "URL of the product image.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/judgeme_reviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/judgeme_reviews.py
new file mode 100644
index 000000000000..a11fdd793a7b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/judgeme_reviews.py
@@ -0,0 +1,235 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, 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.judgeme_reviews.settings import (
+ JUDGEME_REVIEWS_ENDPOINTS,
+)
+
+# The base URL already includes the `/v1` API version segment; endpoint paths are appended to it.
+JUDGEME_BASE_URL = "https://judge.me/api/v1"
+# per_page maxes out at 100 per Judge.me's docs.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Judge.me doesn't publish precise rate limits but does send Retry-After on 429; cap how long a
+# single wait can be so a bogus header can't stall the worker.
+MAX_RETRY_AFTER_SECONDS = 60
+# Cheap endpoint used to confirm the token + shop domain pair is genuine. The private token is
+# shop-wide, so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/reviews/count"
+
+
+class JudgeMeReviewsRetryableError(Exception):
+ def __init__(self, message: str, retry_after: int | None = None) -> None:
+ super().__init__(message)
+ # When set (from a 429 Retry-After), the retry wait honors it exactly instead of
+ # adding exponential backoff on top.
+ self.retry_after = retry_after
+
+
+# Backoff for connection errors and 5xx, where the server gives no explicit delay.
+_exponential_wait = wait_exponential_jitter(initial=1, max=30)
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ # A 429 already tells us exactly when to retry via Retry-After, so wait precisely that long
+ # (capped) rather than Retry-After plus jitter, which would compound the API's requested delay.
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, JudgeMeReviewsRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _exponential_wait(retry_state)
+
+
+class JudgeMeReviewsResumeConfig:
+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed
+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.
+ next_page: int = 1
+
+
+def _normalize_shop_domain(shop_domain: str) -> str:
+ # Users paste the domain straight from their browser; strip any scheme/trailing slash so the
+ # value matches the bare `example.myshopify.com` format the API expects.
+ domain = shop_domain.strip()
+ for prefix in ("https://", "http://"):
+ if domain.startswith(prefix):
+ domain = domain[len(prefix) :]
+ return domain.rstrip("/")
+
+
+def _make_session(api_token: str) -> requests.Session:
+ # The private token goes in the X-Api-Token header (per the OpenAPI spec) so it never appears
+ # in request URLs; `redact_values` masks it in logged headers and captured samples too.
+ return make_tracked_session(
+ headers={"X-Api-Token": api_token, "Accept": "application/json"},
+ redact_values=(api_token,),
+ )
+
+
+@retry(
+ retry=retry_if_exception_type((JudgeMeReviewsRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=_retry_wait,
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ shop_domain: str,
+ page: int,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ params: dict[str, str | int] = {"shop_domain": shop_domain, "page": page, "per_page": PAGE_SIZE}
+ response = session.get(
+ f"{JUDGEME_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429:
+ retry_after = _parse_retry_after(response.headers.get("Retry-After"))
+ raise JudgeMeReviewsRetryableError(
+ f"Judge.me API rate limited: status=429, path={path}", retry_after=retry_after
+ )
+
+ if response.status_code >= 500:
+ raise JudgeMeReviewsRetryableError(
+ f"Judge.me API error (retryable): status={response.status_code}, path={path}"
+ )
+
+ if not response.ok:
+ logger.error(f"Judge.me API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Every list endpoint returns an object envelope (`{"<resource>": [...], ...}`); a bare array
+ # or other type means a malformed response.
+ if not isinstance(data, dict):
+ raise JudgeMeReviewsRetryableError(f"Judge.me returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def _parse_retry_after(value: str | None) -> int | None:
+ if value is None:
+ return None
+ try:
+ seconds = int(value)
+ except ValueError:
+ return None
+ return seconds if seconds > 0 else None
+
+
+def get_rows(
+ api_token: str,
+ shop_domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JudgeMeReviewsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = JUDGEME_REVIEWS_ENDPOINTS[endpoint]
+ session = _make_session(api_token)
+ domain = _normalize_shop_domain(shop_domain)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume else 1
+ if resume and resume.next_page > 1:
+ logger.debug(f"Judge.me: resuming {endpoint} from page {page}")
+
+ while True:
+ data = _fetch_page(session, config.path, domain, page, logger)
+
+ # The resource key is always present in a well-formed envelope; missing it means a malformed
+ # response, so fail loudly rather than silently advancing the cursor past lost rows.
+ items = data.get(config.list_key)
+ if not isinstance(items, list):
+ raise JudgeMeReviewsRetryableError(
+ f"Judge.me response for {endpoint} is missing the '{config.list_key}' list"
+ )
+ if items:
+ yield items
+
+ # There is no `has_more` flag in the envelope, and the API may cap per_page below what we
+ # request, so an empty page is the only reliable end-of-collection signal.
+ if not items:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(JudgeMeReviewsResumeConfig(next_page=page))
+
+
+def judgeme_reviews_source(
+ api_token: str,
+ shop_domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JudgeMeReviewsResumeConfig],
+) -> SourceResponse:
+ config = JUDGEME_REVIEWS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ shop_domain=shop_domain,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_token: str, shop_domain: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single cheap endpoint to validate the token + shop domain pair.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = _make_session(api_token)
+ domain = _normalize_shop_domain(shop_domain)
+ try:
+ response = session.get(
+ f"{JUDGEME_BASE_URL}{path}",
+ params={"shop_domain": domain},
+ timeout=15,
+ )
+ except Exception as e:
+ return 0, f"Could not connect to Judge.me: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Judge.me returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_token: str, shop_domain: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_token, shop_domain)
+ if status == 200:
+ return True, None
+ # 401 means the token/shop domain pair is wrong; 403 typically means a valid but public token
+ # that can't read reviews. Keep these messages in sync with `source.py`'s non-retryable errors.
+ if status == 401:
+ return (
+ False,
+ "Your Judge.me shop domain or API token is invalid. Check both under Settings → Integrations → Judge.me API in the Judge.me admin, then reconnect.",
+ )
+ if status == 403:
+ return (
+ False,
+ "Your Judge.me API token does not have access to this data. Make sure you are using the private token, then reconnect.",
+ )
+ return False, message or "Could not validate Judge.me credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/settings.py
new file mode 100644
index 000000000000..7a002fafd451
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/settings.py
@@ -0,0 +1,32 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class JudgeMeReviewsEndpointConfig:
+ name: str
+ path: str
+ # Judge.me wraps each list response in a key named after the resource
+ # (e.g. `{"current_page": 1, "per_page": 10, "reviews": [...]}`), so the row list
+ # key varies per endpoint and is stored here.
+ list_key: str
+ # Judge.me internal IDs are unique within a shop, and one source is bound to one shop,
+ # so `id` is a safe primary key for every endpoint.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Judge.me REST API list endpoints. All are full refresh only: the list endpoints expose no
+# documented server-side timestamp filter (the reviews index only accepts per_page, page,
+# reviewer_id, product_id, and rating), so there is no genuine incremental cursor to advance
+# (a client-side scan of every page would cost the same as a full refresh — see the skill).
+JUDGEME_REVIEWS_ENDPOINTS: dict[str, JudgeMeReviewsEndpointConfig] = {
+ "reviews": JudgeMeReviewsEndpointConfig(name="reviews", path="/reviews", list_key="reviews"),
+ # `/products` is absent from the current OpenAPI spec but is documented in Judge.me's legacy
+ # API docs and exists on the live API (401 with bad credentials, vs 404 for unknown paths).
+ # It maps Judge.me internal product IDs to external (Shopify) products, which is needed to
+ # join reviews to store catalog data.
+ "products": JudgeMeReviewsEndpointConfig(name="products", path="/products", list_key="products"),
+}
+
+ENDPOINTS = tuple(JUDGEME_REVIEWS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/source.py
index d1d88afc6a6a..6e2472829eff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/source.py
@@ -1,21 +1,44 @@
-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.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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
JudgeMeReviewsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.judgeme_reviews import (
+ JudgeMeReviewsResumeConfig,
+ judgeme_reviews_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.settings import (
+ ENDPOINTS,
+ JUDGEME_REVIEWS_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class JudgeMeReviewsSource(SimpleSource[JudgeMeReviewsSourceConfig]):
+class JudgeMeReviewsSource(ResumableSource[JudgeMeReviewsSourceConfig, JudgeMeReviewsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.JUDGEMEREVIEWS
@@ -26,7 +49,100 @@ class JudgeMeReviewsSource(SimpleSource[JudgeMeReviewsSourceConfig]):
name=SchemaExternalDataSourceType.JUDGE_ME_REVIEWS,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Judge.me Reviews",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your shop domain and private API token to pull your Judge.me product reviews into the PostHog Data warehouse.
+
+You can find your private API token under **Settings → Integrations → Judge.me API** in the [Judge.me admin](https://judge.me). Use the **private** token — the public token cannot read reviews. The shop domain is your store's `myshopify.com` domain (e.g. `example.myshopify.com`).
+""",
iconPath="/static/services/judgeme_reviews.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/judgeme-reviews",
+ keywords=["judgeme"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="shop_domain",
+ label="Shop domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="example.myshopify.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Private API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid token/shop domain pair surfaces as a requests HTTPError when `_fetch_page`
+ # 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://judge.me/api/v1": "Your Judge.me shop domain or API token is invalid. Check both under Settings → Integrations → Judge.me API in the Judge.me admin, then reconnect.",
+ "403 Client Error: Forbidden for url: https://judge.me/api/v1": "Your Judge.me API token does not have access to this data. Make sure you are using the private token, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: JudgeMeReviewsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Judge.me's list endpoints expose no documented
+ # server-side timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: JudgeMeReviewsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The private token is shop-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_token, config.shop_domain)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JudgeMeReviewsResumeConfig]:
+ return ResumableSourceManager[JudgeMeReviewsResumeConfig](inputs, JudgeMeReviewsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: JudgeMeReviewsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[JudgeMeReviewsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in JUDGEME_REVIEWS_ENDPOINTS:
+ raise ValueError(f"Unknown Judge.me schema '{inputs.schema_name}'")
+
+ return judgeme_reviews_source(
+ api_token=config.api_token,
+ shop_domain=config.shop_domain,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews.py
new file mode 100644
index 000000000000..37d303f7c992
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews.py
@@ -0,0 +1,308 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews import judgeme_reviews
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.judgeme_reviews import (
+ MAX_RETRY_AFTER_SECONDS,
+ PAGE_SIZE,
+ JudgeMeReviewsResumeConfig,
+ JudgeMeReviewsRetryableError,
+ _normalize_shop_domain,
+ _parse_retry_after,
+ _retry_wait,
+ check_access,
+ get_rows,
+ judgeme_reviews_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.settings import (
+ ENDPOINTS,
+ JUDGEME_REVIEWS_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = judgeme_reviews._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: JudgeMeReviewsResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[JudgeMeReviewsResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> JudgeMeReviewsResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: JudgeMeReviewsResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(items: list[dict], page: int = 1, list_key: str = "reviews") -> dict[str, Any]:
+ return {"current_page": page, "per_page": PAGE_SIZE, list_key: items}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "reviews"
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, shop_domain: str, page: int, logger: Any) -> dict:
+ return pages[page]
+
+ monkeypatch.setattr(judgeme_reviews, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(judgeme_reviews, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="jm-token",
+ shop_domain="example.myshopify.com",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_paginates_until_empty_page(self, monkeypatch: Any) -> None:
+ # There is no has_more flag, so a full page must still be followed by another fetch.
+ manager = _FakeResumableManager()
+ pages = {
+ 1: _page([{"id": 1}], page=1),
+ 2: _page([{"id": 2}], page=2),
+ 3: _page([], page=3),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 1}, {"id": 2}]
+
+ def test_empty_first_page_yields_nothing_and_saves_no_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {1: _page([])})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ 1: _page([{"id": 1}], page=1),
+ 2: _page([], page=2),
+ }
+ self._collect(manager, monkeypatch, pages)
+ # State is saved AFTER page 1 is yielded (pointing at page 2), never before.
+ assert [s.next_page for s in manager.saved] == [2]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(JudgeMeReviewsResumeConfig(next_page=2))
+ pages = {
+ # Page 1 must never be fetched on resume.
+ 2: _page([{"id": 2}], page=2),
+ 3: _page([], page=3),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 2}]
+
+ def test_uses_endpoint_specific_list_key(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ 1: _page([{"id": 7}], page=1, list_key="products"),
+ 2: _page([], page=2, list_key="products"),
+ }
+ rows = self._collect(manager, monkeypatch, pages, endpoint="products")
+ assert rows == [{"id": 7}]
+
+ def test_missing_list_key_raises(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+
+ def fake_fetch(session: Any, path: str, shop_domain: str, page: int, logger: Any) -> dict:
+ return {"current_page": 1, "per_page": PAGE_SIZE}
+
+ monkeypatch.setattr(judgeme_reviews, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(judgeme_reviews, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ with pytest.raises(JudgeMeReviewsRetryableError):
+ list(
+ get_rows(
+ api_token="jm-token",
+ shop_domain="example.myshopify.com",
+ endpoint="reviews",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+
+class TestFetchPage:
+ def _session_returning(
+ self, status_code: int, body: Any = None, headers: dict[str, str] | None = None
+ ) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {}
+ response.text = ""
+ response.headers = headers or {}
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(JudgeMeReviewsRetryableError):
+ _fetch_page_unwrapped(session, "/reviews", "example.myshopify.com", 1, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/reviews", "example.myshopify.com", 1, MagicMock())
+
+ def test_rate_limit_carries_retry_after_on_exception(self) -> None:
+ session = self._session_returning(429, headers={"Retry-After": "7"})
+ with pytest.raises(JudgeMeReviewsRetryableError) as exc_info:
+ _fetch_page_unwrapped(session, "/reviews", "example.myshopify.com", 1, MagicMock())
+ assert exc_info.value.retry_after == 7
+
+ def test_success_returns_json_body(self) -> None:
+ body = _page([{"id": 1}])
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/reviews", "example.myshopify.com", 1, MagicMock())
+ assert result == body
+
+ def test_non_dict_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": 1}])
+ with pytest.raises(JudgeMeReviewsRetryableError):
+ _fetch_page_unwrapped(session, "/reviews", "example.myshopify.com", 1, MagicMock())
+
+ def test_request_params_include_shop_domain_and_pagination(self) -> None:
+ session = self._session_returning(200, _page([]))
+ _fetch_page_unwrapped(session, "/products", "example.myshopify.com", 3, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"shop_domain": "example.myshopify.com", "page": 3, "per_page": PAGE_SIZE}
+
+ @parameterized.expand(
+ [
+ ("missing", None, None),
+ ("integer", "12", 12),
+ ("zero", "0", None),
+ ("http_date", "Wed, 21 Oct 2026 07:28:00 GMT", None),
+ ]
+ )
+ def test_parse_retry_after(self, _name: str, value: str | None, expected: int | None) -> None:
+ assert _parse_retry_after(value) == expected
+
+
+class TestRetryWait:
+ @staticmethod
+ def _state(exc: Exception | None) -> Any:
+ state = MagicMock()
+ state.outcome.exception.return_value = exc
+ return state
+
+ @parameterized.expand([("under_cap", 7, 7), ("capped", 120, MAX_RETRY_AFTER_SECONDS)])
+ def test_429_waits_exactly_retry_after_capped(self, _name: str, retry_after: int, expected: int) -> None:
+ # The whole point of the fix: honor Retry-After precisely, never Retry-After + jitter.
+ exc = JudgeMeReviewsRetryableError("rate limited", retry_after=retry_after)
+ assert _retry_wait(self._state(exc)) == expected
+
+ def test_falls_back_to_exponential_without_retry_after(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(judgeme_reviews, "_exponential_wait", lambda state: 99.0)
+ assert _retry_wait(self._state(requests.ReadTimeout())) == 99.0
+ assert _retry_wait(self._state(JudgeMeReviewsRetryableError("boom"))) == 99.0
+
+
+class TestNormalizeShopDomain:
+ @parameterized.expand(
+ [
+ ("bare", "example.myshopify.com", "example.myshopify.com"),
+ ("https", "https://example.myshopify.com", "example.myshopify.com"),
+ ("http", "http://example.myshopify.com", "example.myshopify.com"),
+ ("trailing_slash", "https://example.myshopify.com/", "example.myshopify.com"),
+ ("whitespace", " example.myshopify.com ", "example.myshopify.com"),
+ ]
+ )
+ def test_normalization(self, _name: str, raw: str, expected: str) -> None:
+ assert _normalize_shop_domain(raw) == expected
+
+
+class TestCheckAccess:
+ def _patch_session(self, response: Any) -> Any:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return patch.object(judgeme_reviews, "make_tracked_session", lambda **kwargs: session)
+
+ @parameterized.expand(
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "Judge.me returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(self, status: int, ok: bool, expected_status: int, expected_message: str | None) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with self._patch_session(response):
+ assert check_access("jm-token", "example.myshopify.com") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ with self._patch_session(requests.ConnectionError("boom")):
+ status, message = check_access("jm-token", "example.myshopify.com")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (
+ 401,
+ False,
+ "Your Judge.me shop domain or API token is invalid. Check both under Settings → Integrations → Judge.me API in the Judge.me admin, then reconnect.",
+ ),
+ (
+ 403,
+ False,
+ "Your Judge.me API token does not have access to this data. Make sure you are using the private token, then reconnect.",
+ ),
+ (500, False, "Judge.me returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(self, status: int, expected_valid: bool, expected_message: str | None) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with self._patch_session(response):
+ assert validate_credentials("jm-token", "example.myshopify.com") == (expected_valid, expected_message)
+
+
+class TestJudgeMeReviewsSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = judgeme_reviews_source(
+ api_token="jm-token",
+ shop_domain="example.myshopify.com",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Response ordering is undocumented and syncs are full refresh, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in JUDGEME_REVIEWS_ENDPOINTS.values())
+ assert set(JUDGEME_REVIEWS_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews_source.py
new file mode 100644
index 000000000000..acab63559c25
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/judgeme_reviews/tests/test_judgeme_reviews_source.py
@@ -0,0 +1,149 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
+ JudgeMeReviewsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.judgeme_reviews import (
+ JudgeMeReviewsResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.source import JudgeMeReviewsSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestJudgeMeReviewsSource:
+ def setup_method(self) -> None:
+ self.source = JudgeMeReviewsSource()
+ self.team_id = 123
+ self.config = JudgeMeReviewsSourceConfig(shop_domain="example.myshopify.com", api_token="jm-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.JUDGEMEREVIEWS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Judge.me Reviews"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/judgeme-reviews"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["shop_domain", "api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_shop_domain_field_is_plain_text(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "shop_domain")
+ assert field.type == SourceFieldInputConfigType.TEXT
+ assert field.secret is False
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # shop_domain selects which shop's data the fixed judge.me host returns; the token is never
+ # sent to a user-controlled host, so retargeting it cannot exfiltrate the credential.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ 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=["products"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "products"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://judge.me/api/v1/reviews?shop_domain=example.myshopify.com&page=1",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://judge.me/api/v1/products?shop_domain=example.myshopify.com&page=1",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://judge.me/api/v1/reviews"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://judge.me/api/v1/products"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("valid", (True, None)),
+ ("invalid_credentials", (False, "Invalid Judge.me shop domain or API token")),
+ ("connect_error", (False, "Could not connect to Judge.me: boom")),
+ ]
+ )
+ def test_validate_credentials_delegates_to_probe(self, _name: str, underlying: tuple[bool, str | None]) -> None:
+ # The status → message mapping is covered by the judgeme_reviews.validate_credentials unit
+ # test; here we only guard that the source passes both credentials and returns the probe
+ # result unchanged.
+ with mock.patch.object(source_module, "validate_credentials", return_value=underlying) as mock_validate:
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == underlying
+ mock_validate.assert_called_once_with("jm-token", "example.myshopify.com")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is JudgeMeReviewsResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.judgeme_reviews.source.judgeme_reviews_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "reviews"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "jm-token"
+ assert kwargs["shop_domain"] == "example.myshopify.com"
+ assert kwargs["endpoint"] == "reviews"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Judge.me schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)