: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): add Okendo source (#77096)
Tom Owers559a8124d8a9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 624fa24eb58a..f4fbda8d08e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -425,6 +425,7 @@ the row lists both.| news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ || npm_registry | HTTP | requests | ✅ |+| okendo | HTTP (cursor pagination) | requests + `rest_source.RESTClient` | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ || northflank | HTTP | requests | ✅ |@@ -1163,7 +1164,6 @@ doesn't conflict with concurrent PRs.- octolens- odoo- oecd-- okendo- onedrive- onehundredms- onelogindiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/okendo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/okendo.pyindex 3045f3bebad2..fee5c4795372 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/okendo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/okendo.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass OkendoSourceConfig(config.Config):- pass+ user_id: str+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/canonical_descriptions.pynew file mode 100644index 000000000000..ce2e57782254--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/canonical_descriptions.py@@ -0,0 +1,66 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "reviews": {+ "description": "Product reviews collected by Okendo, across every moderation status.",+ "docs_url": "https://docs.okendo.io/merchant-rest-api/endpoints/reviews",+ "columns": {+ "subscriberId": "Your user id within Okendo.",+ "reviewId": "Unique identifier for the review.",+ "productId": "The product ID prefixed by a platform identifier.",+ "attributesWithRating": "Rated attributes on the review, each with a title, scale type and selected value.",+ "body": "The content of the review.",+ "containsProfanity": "True if the title or body contain words on the profanity list.",+ "dateCreated": "When the review was submitted.",+ "helpfulCount": "The number of upvotes a review has received.",+ "isIncentivized": "Whether the review was submitted in exchange for a reward.",+ "isRecommended": "Whether the reviewer recommends the product.",+ "media": "Images and videos attached to the review, each with its URLs and type.",+ "productAttributes": "Product attributes selected by the reviewer, each with a title, type and value.",+ "productName": "The name of the reviewed product.",+ "order": "The order the review is connected to, with its orderId and orderNumber.",+ "rating": "The number of stars a review has received, from 1 to 5.",+ "reply": "The merchant's reply, with its HTML body, raw body, creation date and privacy flag.",+ "reviewer": "The reviewer's details, including display name, email, location and verified status.",+ "reward": "The reward given for the review, with its type, value and description.",+ "sentiment": "The natural language sentiment of the review title and body: positive, negative, neutral or mixed.",+ "status": "The moderation status of the review: approved, pending or rejected.",+ "tags": "The names of any tags added to the review.",+ "title": "The title of the review.",+ "unhelpfulCount": "The number of downvotes a review has received.",+ "variantId": "The id of the reviewed Shopify product variant.",+ "variantName": "The name of the reviewed Shopify product variant.",+ },+ },+ "loyalty_earning_rules": {+ "description": "The ways customers can earn loyalty points in your Okendo loyalty program.",+ "docs_url": "https://docs.okendo.io/merchant-rest-api/endpoints/loyalty",+ "columns": {+ "type": "The kind of earning rule: fixed-amount, points-per, points-per-spend or submit-review.",+ "amount": "The points awarded by the rule.",+ "waitTimeDays": "For spend-based rules, the number of days before the points are released.",+ "amountForReview": "Points awarded for submitting a review.",+ "amountForSocialLogin": "Points awarded for connecting a social login to the review.",+ "amountForImage": "Points awarded for attaching an image to the review.",+ "amountForVideo": "Points awarded for attaching a video to the review.",+ "capPerOrder": "The maximum points that can be earned from reviews on a single order.",+ "earnEachAmountOncePer": "Whether each award can be earned once per order or once per review.",+ },+ },+ "loyalty_redemption_rules": {+ "description": "The rewards customers can redeem loyalty points for in your Okendo loyalty program.",+ "docs_url": "https://docs.okendo.io/merchant-rest-api/endpoints/loyalty",+ "columns": {+ "redemptionRuleId": "The unique identifier for the redemption rule.",+ "type": "The kind of reward: fixed-value, percentage-coupon, variable-value, free-shipping or free-product.",+ "reward": "The reward itself, including the points required, its value and how it is awarded.",+ "appliesToCollections": "Collections that the redeemed reward is restricted to when applying.",+ "expiresAfterDays": "The number of days until the redeemed reward expires.",+ "minimumPurchase": "The minimum purchase amount the reward is restricted to.",+ "purchaseType": "The purchase type the reward is restricted to: single, subscription or both.",+ "recurringCycleLimit": "The number of subscription payments the reward is restricted to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/okendo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/okendo.pynew file mode 100644index 000000000000..72583cb38717--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/okendo.py@@ -0,0 +1,218 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import parse_qs, urlsplit++from requests import Request, Response+from requests.auth import HTTPBasicAuth++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.settings import (+ OKENDO_BASE_URL,+ OKENDO_ENDPOINTS,+ PAGE_LIMIT,+)+++class OkendoResumeConfig:+ # Which sub-request of the endpoint was in flight: a review moderation status, or "" for the+ # endpoints that issue a single request.+ variant: str+ # Cursor for the next unfetched page, or None when the variant was walked to its end.+ last_evaluated: Optional[str] = None+++def _cursor_from_next_url(next_url: Optional[str]) -> Optional[str]:+ """Pull the `lastEvaluated` cursor out of a `nextUrl` link.++ Okendo documents `nextUrl` as a relative link but not what it is relative to, so the request is+ rebuilt from the cursor rather than following the link verbatim. A link we can't read a cursor+ out of ends pagination instead of being guessed at.+ """+ if not next_url:+ return None+ values = parse_qs(urlsplit(next_url).query).get("lastEvaluated")+ return values[0] if values else None+++class OkendoCursorPaginator(BasePaginator):+ def __init__(self) -> None:+ super().__init__()+ self._last_evaluated: Optional[str] = None++ def _apply(self, request: Request) -> None:+ if self._last_evaluated is None:+ return+ if request.params is None:+ request.params = {}+ request.params["lastEvaluated"] = self._last_evaluated++ def init_request(self, request: Request) -> None:+ # Honour a seeded resume cursor on the first request of a resumed run.+ self._apply(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except ValueError:+ body = None++ cursor = _cursor_from_next_url(body.get("nextUrl") if isinstance(body, dict) else None)+ if cursor is None or cursor == self._last_evaluated:+ # No link, an unreadable link, or a link repeating the cursor we just sent — either way+ # there is no page to advance to, and following a repeated cursor would loop forever.+ self._has_next_page = False+ return++ self._last_evaluated = cursor+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ self._apply(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page and self._last_evaluated is not None:+ return {"last_evaluated": self._last_evaluated}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ last_evaluated = state.get("last_evaluated")+ if last_evaluated is not None:+ self._last_evaluated = str(last_evaluated)+ self._has_next_page = True++ def __str__(self) -> str:+ return "OkendoCursorPaginator()"+++def _headers(api_version: str) -> dict[str, str]:+ # Basic auth goes through the framework auth config so the API key is redacted from logs; only+ # the non-secret headers are set here.+ return {"okendo-api-version": api_version, "Accept": "application/json"}+++def _request_variants(endpoint: str) -> list[tuple[str, dict[str, Any]]]:+ """The (variant key, query params) pairs making up one full read of an endpoint."""+ config = OKENDO_ENDPOINTS[endpoint]++ base: dict[str, Any] = dict(config.params)+ if config.paginated:+ base["limit"] = PAGE_LIMIT++ if not config.statuses:+ return [("", base)]++ return [(status, {**base, "status": status}) for status in config.statuses]+++def okendo_source(+ user_id: str,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[OkendoResumeConfig],+) -> SourceResponse:+ config = OKENDO_ENDPOINTS[endpoint]+ variants = _request_variants(endpoint)++ def build_rest_config(params: dict[str, Any]) -> RESTAPIConfig:+ return {+ "client": {+ "base_url": OKENDO_BASE_URL,+ "headers": _headers(api_version),+ "auth": {"type": "http_basic", "username": user_id, "password": api_key},+ "paginator": OkendoCursorPaginator() if config.paginated else SinglePagePaginator(),+ },+ # Every resource setting is spelled out below, so there are no shared defaults.+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ # A 200 that drops the row key entirely means the response shape changed —+ # fail loud rather than silently syncing 0 rows. An empty body is tolerated+ # because it is unclear whether Okendo omits the key for an empty result.+ "data_selector_required": True,+ "data_selector_empty_ok": True,+ },+ }+ ],+ }++ def items() -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ variant_keys = [key for key, _ in variants]+ start = variant_keys.index(resume.variant) if resume is not None and resume.variant in variant_keys else 0++ for position in range(start, len(variants)):+ variant_key, params = variants[position]++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume is not None and position == start and resume.last_evaluated is not None:+ initial_paginator_state = {"last_evaluated": resume.last_evaluated}++ def save_checkpoint(state: Optional[dict[str, Any]], variant_key: str = variant_key) -> None:+ # Called after each page is yielded, so a crash re-yields the last page (the merge+ # dedupes on primary key) rather than skipping it.+ if state and state.get("last_evaluated"):+ resumable_source_manager.save_state(+ OkendoResumeConfig(variant=variant_key, last_evaluated=str(state["last_evaluated"]))+ )++ yield from rest_api_resource(+ build_rest_config(params),+ team_id,+ job_id,+ None, # every Okendo endpoint is full refresh+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ if position + 1 < len(variants):+ # Point the checkpoint at the next variant so a crash between variants doesn't+ # re-walk the one just finished from its last saved cursor.+ resumable_source_manager.save_state(+ OkendoResumeConfig(variant=variants[position + 1][0], last_evaluated=None)+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Rows arrive oldest-first within a review status but the stream restarts at each status, so+ # it is not globally ascending. Nothing reads this today (no endpoint is incremental), and+ # claiming an order the stream doesn't have would be wrong if one ever is.+ sort_mode=None,+ )+++def validate_credentials(user_id: str, api_key: str, api_version: str) -> tuple[bool, int | None]:+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{OKENDO_BASE_URL}/reviews?limit=1",+ headers=_headers(api_version),+ auth=HTTPBasicAuth(user_id, api_key),+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/settings.pynew file mode 100644index 000000000000..896d1fe659b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/settings.py@@ -0,0 +1,64 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField++OKENDO_BASE_URL = "https://api.okendo.io/enterprise"+# Okendo's Merchant REST API is date-versioned and rejects requests without this header.+OKENDO_API_VERSION = "2025-02-01"+# The API caps `limit` at 100 and defaults to 25.+PAGE_LIMIT = 100++# `/reviews` returns only approved reviews unless `status` is set, so each status is fetched in+# turn and merged into one table with `status` as a column.+REVIEW_STATUSES = ("approved", "pending", "rejected")+++@dataclass+class OkendoEndpointConfig:+ path: str+ # Key holding the row array in the response body.+ data_selector: str+ primary_keys: list[str]+ # Endpoints that accept `limit`/`lastEvaluated` and return a `nextUrl` cursor. The loyalty rule+ # catalogs document neither, so they are read as a single page.+ paginated: bool = True+ # Extra query params sent on every request for this endpoint.+ params: dict[str, str] = field(default_factory=dict)+ # One request per status value, merged into a single table. Empty for endpoints with no fan-out.+ statuses: tuple[str, ...] = ()+ # Stable creation timestamp to partition on, when the rows carry one.+ partition_key: str | None = None+++OKENDO_ENDPOINTS: dict[str, OkendoEndpointConfig] = {+ "reviews": OkendoEndpointConfig(+ path="/reviews",+ data_selector="reviews",+ primary_keys=["reviewId"],+ # Default order is 'date desc', which shifts pages as new reviews land mid-sync. Ascending+ # order appends new rows past the cursor instead, so a page boundary can't skip a row.+ params={"orderBy": "date asc"},+ statuses=REVIEW_STATUSES,+ partition_key="dateCreated",+ ),+ "loyalty_earning_rules": OkendoEndpointConfig(+ path="/loyalty/earning_rules",+ data_selector="rules",+ # Earning rules carry no id; the documented schema is one rule per `type` variant.+ primary_keys=["type"],+ paginated=False,+ ),+ "loyalty_redemption_rules": OkendoEndpointConfig(+ path="/loyalty/redemption_rules",+ data_selector="rules",+ primary_keys=["redemptionRuleId"],+ paginated=False,+ ),+}++ENDPOINTS = tuple(OKENDO_ENDPOINTS.keys())++# Empty: no Okendo list endpoint exposes a created-since / updated-since filter, so there is no+# server-side watermark to sync against and every stream is full refresh. `build_endpoint_schemas`+# reads a missing entry as non-incremental.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/source.pyindex 389f90a5cc5a..59df5aeeef70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/source.py@@ -1,19 +1,46 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.okendo import OkendoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.okendo import (+ OkendoResumeConfig,+ okendo_source,+ validate_credentials as validate_okendo_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ OKENDO_BASE_URL,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OkendoSource(SimpleSource[OkendoSourceConfig]):+class OkendoSource(ResumableSource[OkendoSourceConfig, OkendoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("2025-02-01",)+ default_version = "2025-02-01"+ api_docs_url = "https://docs.okendo.io/merchant-rest-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OKENDO@@ -24,7 +51,99 @@ class OkendoSource(SimpleSource[OkendoSourceConfig]):name=SchemaExternalDataSourceType.OKENDO,category=DataWarehouseSourceCategory.E_COMMERCE,label="Okendo",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Okendo user ID and API key to pull your Okendo reviews and loyalty data into the PostHog Data warehouse.++You can find both in the integration settings section of the Okendo app.+""",iconPath="/static/services/okendo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/okendo",+ keywords=["reviews", "ratings", "ugc", "loyalty"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="user_id",+ label="Okendo user ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ f"401 Client Error: Unauthorized for url: {OKENDO_BASE_URL}": "Your Okendo user ID or API key is invalid. Check both in the integration settings section of the Okendo app, then reconnect.",+ f"403 Client Error: Forbidden for url: {OKENDO_BASE_URL}": "Your Okendo API key does not have access to this data. The loyalty tables need Okendo Loyalty enabled on your account.",+ }++ def get_schemas(+ self,+ config: OkendoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: OkendoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, status_code = validate_okendo_credentials(+ config.user_id, config.api_key, self.resolve_api_version(api_version)+ )+ if is_valid:+ return True, None++ if status_code == 403 and schema_name is None:+ # A genuine key that can't read reviews still connects: the account may only be+ # entitled to the tables the user goes on to pick.+ return True, None++ if status_code == 403:+ return False, "Your Okendo API key does not have access to this data"++ return False, "Invalid Okendo user ID or API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OkendoResumeConfig]:+ return ResumableSourceManager[OkendoResumeConfig](inputs, OkendoResumeConfig)++ def source_for_pipeline(+ self,+ config: OkendoSourceConfig,+ resumable_source_manager: ResumableSourceManager[OkendoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return okendo_source(+ user_id=config.user_id,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo.pynew file mode 100644index 000000000000..ba39bc41698f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo.py@@ -0,0 +1,247 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.okendo import (+ OkendoResumeConfig,+ okendo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.settings import (+ OKENDO_API_VERSION,+ REVIEW_STATUSES,+)++CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+OKENDO_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.okendo.okendo.make_tracked_session"+)+++def _response(body: dict[str, Any] | None) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body if body is not None else {}).encode()+ return resp+++def _reviews_page(ids: list[str], next_cursor: str | None = None) -> Response:+ body: dict[str, Any] = {"reviews": [{"reviewId": review_id} for review_id in ids]}+ if next_cursor is not None:+ body["nextUrl"] = f"/enterprise/reviews?limit=100&lastEvaluated={next_cursor}"+ return _response(body)+++def _make_manager(resume_state: OkendoResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's params AT SEND TIME.++ ``request.params`` is one dict mutated in place across pages, so reading it after the run shows+ only the final state — snapshot a copy as each request is prepared instead.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _rows(source_response: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]+++def _source(endpoint: str, manager: mock.MagicMock) -> SourceResponse:+ return okendo_source(+ user_id="user-1",+ api_key="key-1",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ api_version=OKENDO_API_VERSION,+ resumable_source_manager=manager,+ )+++class TestReviewsTransport:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_walks_every_moderation_status_and_follows_the_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _reviews_page(["a1"], next_cursor="cursor-1"),+ _reviews_page(["a2"]),+ _reviews_page(["p1"]),+ _reviews_page(["r1"]),+ ],+ )++ rows = _rows(_source("reviews", _make_manager()))++ # Only 'approved' comes back when `status` is unset, so a lost fan-out silently drops the+ # moderation queue; a mis-parsed `nextUrl` silently drops every page after the first.+ assert [row["reviewId"] for row in rows] == ["a1", "a2", "p1", "r1"]+ assert [p["status"] for p in params] == ["approved", "approved", "pending", "rejected"]+ assert params[1]["lastEvaluated"] == "cursor-1"+ assert "lastEvaluated" not in params[2]+ assert params[0]["limit"] == 100+ assert params[0]["orderBy"] == "date asc"++ @parameterized.expand(+ [+ ("no_next_url", None),+ ("next_url_without_cursor", "/enterprise/reviews?limit=100"),+ ("next_url_repeating_the_sent_cursor", "/enterprise/reviews?lastEvaluated=cursor-1"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pagination_terminates(self, _name: str, next_url: str | None, MockSession) -> None:+ session = MockSession.return_value+ first: dict[str, Any] = {"reviews": [{"reviewId": "a1"}]}+ if next_url is not None:+ first["nextUrl"] = next_url+ _wire(session, [_response(first), _reviews_page(["p1"]), _reviews_page(["r1"])])++ # Seeded so the repeated-cursor case sends the cursor the response then echoes back.+ manager = _make_manager(OkendoResumeConfig(variant="approved", last_evaluated="cursor-1"))+ rows = _rows(_source("reviews", manager))++ # One request per status: the run ends rather than looping on an unusable next link. A+ # fourth request would exhaust the wired responses and raise StopIteration.+ assert session.send.call_count == len(REVIEW_STATUSES)+ assert len(rows) == 3++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_skips_completed_statuses_and_seeds_the_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_reviews_page(["p2"]), _reviews_page(["r1"])])++ manager = _make_manager(OkendoResumeConfig(variant="pending", last_evaluated="cursor-9"))+ _rows(_source("reviews", manager))++ assert [p["status"] for p in params] == ["pending", "rejected"]+ assert params[0]["lastEvaluated"] == "cursor-9"+ # The cursor belongs to the status it was saved against; carrying it into the next one+ # would resume that status part-way through and drop its earlier rows.+ assert "lastEvaluated" not in params[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_the_next_page_then_the_next_status(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _reviews_page(["a1"], next_cursor="cursor-1"),+ _reviews_page(["a2"]),+ _reviews_page(["p1"]),+ _reviews_page(["r1"]),+ ],+ )++ manager = _make_manager()+ _rows(_source("reviews", manager))++ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ OkendoResumeConfig(variant="approved", last_evaluated="cursor-1"),+ OkendoResumeConfig(variant="pending", last_evaluated=None),+ OkendoResumeConfig(variant="rejected", last_evaluated=None),+ ]+++class TestEndpointRequests:+ @parameterized.expand(+ [+ ("loyalty_earning_rules", "/loyalty/earning_rules"),+ ("loyalty_redemption_rules", "/loyalty/redemption_rules"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_rule_catalogs_are_read_as_a_single_page(self, endpoint: str, _path: str, MockSession) -> None:+ session = MockSession.return_value+ # A nextUrl here must be ignored: neither rules endpoint documents limit/lastEvaluated, so+ # replaying a cursor against them would loop on the same page.+ params = _wire(+ session, [_response({"rules": [{"type": "points-per-spend"}], "nextUrl": "/enterprise/x?lastEvaluated=c"})]+ )++ rows = _rows(_source(endpoint, _make_manager()))++ assert len(rows) == 1+ assert session.send.call_count == 1+ assert "limit" not in params[0]+ assert "status" not in params[0]++ @parameterized.expand(+ [+ ("reviews", ["reviewId"], ["dateCreated"]),+ ("loyalty_earning_rules", ["type"], None),+ ("loyalty_redemption_rules", ["redemptionRuleId"], None),+ ]+ )+ def test_primary_and_partition_keys(+ self, endpoint: str, primary_keys: list[str], partition_keys: list[str] | None+ ) -> None:+ # Okendo rows carry no `id`, so a key copied from another source would be null for every+ # row and every merge would multi-match.+ response = _source(endpoint, _make_manager())+ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_version_header_is_sent(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_reviews_page(["a1"]), _reviews_page([]), _reviews_page([])])++ _rows(_source("reviews", _make_manager()))++ # The API rejects requests without it.+ assert session.headers.get("okendo-api-version") == OKENDO_API_VERSION++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unexpected_response_shape_fails_loud(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"data": [{"reviewId": "a1"}]})])++ # A renamed row key must not read as "0 rows synced".+ with pytest.raises(ValueError, match="matched nothing"):+ _rows(_source("reviews", _make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_body_is_an_empty_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({}), _response({}), _response({})])++ assert _rows(_source("reviews", _make_manager())) == []+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ @mock.patch(OKENDO_SESSION_PATCH)+ def test_reports_the_probe_status(self, _name: str, status_code: int, expected: bool, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ # The status is returned, not just a bool, so the source can accept 403 at connect time.+ assert validate_credentials("user-1", "key-1", OKENDO_API_VERSION) == (expected, status_code)++ @mock.patch(OKENDO_SESSION_PATCH)+ def test_transport_failure_does_not_raise(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("user-1", "key-1", OKENDO_API_VERSION) == (False, None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo_source.pynew file mode 100644index 000000000000..b306601769b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/okendo/tests/test_okendo_source.py@@ -0,0 +1,133 @@+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.okendo import OkendoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.okendo import OkendoResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.okendo.source import OkendoSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.okendo.source.validate_okendo_credentials"+)+++class TestOkendoSource:+ def setup_method(self):+ self.source = OkendoSource()+ self.team_id = 123+ self.config = OkendoSourceConfig(user_id="user-1", api_key="key-1")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.OKENDO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Okendo"+ assert config.label == "Okendo"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/okendo.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["user_id", "api_key"]++ def test_api_key_field_is_a_secret_password(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++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.okendo.io/enterprise/reviews"),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.okendo.io/enterprise/loyalty/earning_rules",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("other_vendor", "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"),+ ("server_error", "500 Server Error for url: https://api.okendo.io/enterprise/reviews"),+ ]+ )+ def test_non_retryable_errors_do_not_match_unrelated(self, _name, other_error):+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # No Okendo list endpoint filters by a created/updated timestamp, so advertising incremental+ # would ship a sync that re-reads everything while claiming a watermark it can't honor.+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["reviews"])++ assert [schema.name for schema in schemas] == ["reviews"]++ @parameterized.expand(+ [+ ("valid", (True, 200), None, True, None),+ ("bad_key", (False, 401), None, False, "Invalid Okendo user ID or API key"),+ ("unreachable", (False, None), None, False, "Invalid Okendo user ID or API key"),+ # 403 at connect time is a real key without review access — the user may only want the+ # loyalty tables, so blocking source creation on it would lock them out.+ ("forbidden_at_connect", (False, 403), None, True, None),+ ("forbidden_for_schema", (False, 403), "reviews", False, "Your Okendo API key does not have access"),+ ]+ )+ def test_validate_credentials(self, _name, probe_result, schema_name, expected_valid, expected_message):+ with mock.patch(VALIDATE_PATCH, return_value=probe_result) as mock_validate:+ is_valid, error_message = self.source.validate_credentials(+ self.config, self.team_id, schema_name=schema_name+ )++ assert is_valid is expected_valid+ if expected_message is None:+ assert error_message is None+ else:+ assert error_message is not None and expected_message in error_message+ mock_validate.assert_called_once_with("user-1", "key-1", "2025-02-01")++ 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 OkendoResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.okendo.source.okendo_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_okendo_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "reviews"+ inputs.team_id = 7+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_okendo_source.call_args.kwargs+ assert kwargs["user_id"] == "user-1"+ assert kwargs["api_key"] == "key-1"+ assert kwargs["endpoint"] == "reviews"+ assert kwargs["resumable_source_manager"] is manager+ # An unpinned source must still send a version header, or every request is rejected.+ assert kwargs["api_version"] == "2025-02-01"++ def test_canonical_descriptions_cover_declared_endpoints(self):+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)