:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement adobe_commerce source (#73781)
Tom Owers50e09864d3e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b9affe994b9b..9b56f982bb4b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -50,6 +50,7 @@ the row lists both.| -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || ably | HTTP | requests + `rest_source.RESTClient` | ✅ || adobe_analytics | HTTP | requests | ✅ |+| adobe_commerce | HTTP | requests | ✅ || adroll | HTTP | requests | ✅ || adyen | HTTP | requests | ✅ || agilecrm | HTTP | requests | ✅ |@@ -707,6 +708,7 @@ doesn't conflict with concurrent PRs.- acuity_scheduling- adapty- adjust+- adobe_analytics- adobe_commerce- adp_workforce_now- aftershipdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/adobe_commerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/adobe_commerce.pynew file mode 100644index 000000000000..dba02d31980e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/adobe_commerce.py@@ -0,0 +1,679 @@+import re+import json+import time+import threading+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Literal, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.settings import (+ ADOBE_COMMERCE_ENDPOINTS,+ VALIDATION_PROBE_ENDPOINTS,+ AdobeCommerceEndpointConfig,+)+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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++REQUEST_TIMEOUT_SECONDS = 120+VALIDATE_TIMEOUT_SECONDS = 20++# The store URL is customer-supplied, so a misconfigured or hostile host could stream an+# arbitrarily large body into a shared worker. Every response is read with `stream=True` and+# capped: a 200-row `/V1/orders` page with full line items is a few MiB, so this leaves headroom.+MAX_RESPONSE_BYTES = 200 * 1024 * 1024+_RESPONSE_CHUNK_BYTES = 64 * 1024+_ERROR_BODY_PREVIEW_BYTES = 2 * 1024+# `requests`' timeout only bounds each socket read, so a host dribbling a body under that timeout+# could hold a worker open indefinitely while staying under the size cap. Bound total transfer time.+MAX_DOWNLOAD_SECONDS = 600++# A server that returns a non-empty page forever (or omits/inflates `total_count`) would otherwise+# pin the activity until its timeout. At 100-200 rows a page this is far beyond any real catalog.+MAX_PAGES = 100_000+# Bound the loop's wall clock too, so a store that stays under `MAX_PAGES` by dribbling pages can't+# hold an import worker for the activity's week-long timeout. Magento's searchCriteria collections+# always carry `total_count`, so a real store terminates well before either bound — only a+# pathological one hits them, and resuming would just hand it more worker time, so both are+# non-retryable (see `PAGINATION_LIMIT_ERROR` in `get_non_retryable_errors`).+MAX_PAGINATION_SECONDS = 24 * 60 * 60++# Magento's admin token TTL is configurable (`oauth/access_token_lifetime/admin`) and defaults to+# 4 hours; the response carries no expiry, so assume the default and re-mint well before it.+ADMIN_TOKEN_LIFETIME_SECONDS = 4 * 60 * 60+TOKEN_REFRESH_MARGIN_SECONDS = 5 * 60++# The admin token endpoint returns a bare JSON string (the token itself), so a well-behaved store+# answers in under a kilobyte. Validation mints the token inline on the API request thread, so cap+# the exchange far tighter than a data page and give it a short deadline — a hostile store pointed+# at by `store_url` must not be able to tie up a worker by dribbling a huge body during validation.+TOKEN_RESPONSE_MAX_BYTES = 1 * 1024 * 1024+TOKEN_DOWNLOAD_SECONDS = 30++# Credential validation runs inline on the API request thread, so it opts out of transport retries:+# the shared policy honours a server-supplied `Retry-After` and sleeps between attempts, none of it+# bounded by the request timeout, so a hostile store could otherwise stall a worker with a 429/503+# and a large `Retry-After`. A sync run still uses the default retrying session.+_NO_RETRY = Retry(total=0)++# Magento compares searchCriteria datetime filters against MySQL `DATETIME` columns stored in UTC.+MAGENTO_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"++HOST_NOT_ALLOWED_ERROR = "Adobe Commerce store URL is not allowed"+INCOMPLETE_CREDENTIALS_ERROR = "Adobe Commerce credentials are incomplete"+HTTPS_REQUIRED_ERROR = "Adobe Commerce store URL must use HTTPS"+PAGINATION_LIMIT_ERROR = "Adobe Commerce pagination did not terminate"++# A store code is a Magento code: letters, digits and underscores, starting with a letter.+_STORE_CODE_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*$")+_SCHEME_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]*)://")+# A DNS name or bare IPv4. IPv6 literals aren't accepted: a merchant's storefront is reached by+# name, and rejecting them keeps the host string unambiguous for the SSRF check.+_HOSTNAME_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")+++class AdobeCommerceRetryableError(Exception):+ pass+++class AdobeCommerceHostNotAllowedError(Exception):+ pass+++class AdobeCommerceConfigurationError(Exception):+ pass+++class AdobeCommerceResponseTooLargeError(Exception):+ pass+++class AdobeCommerceResponseTooSlowError(Exception):+ pass+++class AdobeCommercePaginationLimitError(Exception):+ pass+++class AdobeCommerceResumeConfig:+ # Next 1-indexed `searchCriteria[currentPage]` to fetch. The rest of the query string is+ # rebuilt deterministically from the schema inputs, so the page number is all we persist.+ current_page: int+++class AdobeCommerceCredentials:+ method: Literal["access_token", "admin"]+ access_token: str | None = None+ username: str | None = None+ password: str | None = None++ def secret_values(self) -> tuple[str, ...]:+ return tuple(v for v in (self.access_token, self.password) if v)+++def normalize_store_url(store_url: str) -> str:+ """Reduce whatever the merchant typed to a `scheme://host[:port][/subpath]` base.++ Magento is frequently installed in a subdirectory, so the path is preserved — but a pasted+ `/rest/...` suffix is stripped so the base is never doubled up. Anything without a usable+ host is rejected before a URL carrying the credential is built.+ """+ cleaned = store_url.strip().rstrip("/")+ if not cleaned:+ raise ValueError("Enter your Adobe Commerce store URL, e.g. https://store.example.com")++ scheme_match = _SCHEME_RE.match(cleaned)+ if scheme_match:+ scheme = scheme_match.group(1).lower()+ # Every request carries the integration token or admin login, so refuse plaintext+ # transport before a credential-bearing URL is ever built.+ if scheme == "http":+ raise ValueError(HTTPS_REQUIRED_ERROR)+ if scheme != "https":+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")+ else:+ cleaned = f"https://{cleaned}"++ parsed = urlparse(cleaned)+ if parsed.scheme.lower() != "https" or not parsed.hostname:+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")+ if parsed.username or parsed.password or parsed.query or parsed.fragment:+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")+ if not _HOSTNAME_RE.match(parsed.hostname):+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")+ try:+ # `urlparse` only validates the port lazily, so force it here rather than letting a+ # malformed one surface mid-sync.+ _ = parsed.port+ except ValueError as e:+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}") from e++ path = parsed.path.rstrip("/")+ # Tolerate a pasted API base (`.../rest`, `.../rest/default/V1`) — everything from `/rest`+ # onwards is rebuilt by `_base_url`.+ rest_index = path.lower().find("/rest")+ if rest_index != -1:+ path = path[:rest_index]+ if ".." in path:+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")++ return f"{parsed.scheme.lower()}://{parsed.netloc}{path}"+++def store_host(store_url: str) -> str:+ hostname = urlparse(normalize_store_url(store_url)).hostname+ if not hostname:+ raise ValueError(f"Invalid Adobe Commerce store URL: {store_url!r}")+ return hostname+++def normalize_store_code(store_code: str | None) -> str:+ """Validate the optional store code. Blank means the default store view (`/rest/V1/...`)."""+ cleaned = (store_code or "").strip().strip("/")+ if not cleaned:+ return ""+ if not _STORE_CODE_RE.match(cleaned):+ raise ValueError(f"Invalid Adobe Commerce store code: {store_code!r}")+ return cleaned+++def _base_url(store_url: str, store_code: str | None) -> str:+ code = normalize_store_code(store_code)+ prefix = f"/rest/{code}/V1" if code else "/rest/V1"+ return f"{normalize_store_url(store_url)}{prefix}"+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params, doseq=True)}"+++def _format_magento_datetime(value: Any) -> str:+ if isinstance(value, datetime):+ as_utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return as_utc.strftime(MAGENTO_DATETIME_FORMAT)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime(MAGENTO_DATETIME_FORMAT)+ return str(value)+++def build_search_criteria(+ config: AdobeCommerceEndpointConfig,+ page: int,+ cursor_field: str | None = None,+ cursor_value: Any = None,+) -> dict[str, Any]:+ """Build the flat `searchCriteria[...]` query params for one page.++ Magento takes its search criteria as bracketed PHP-array keys rather than nested JSON, so the+ filter group, sort order and paging all flatten into single-level keys here.+ """+ params: dict[str, Any] = {+ "searchCriteria[pageSize]": config.page_size,+ "searchCriteria[currentPage]": page,+ }++ if cursor_field:+ params["searchCriteria[sortOrders][0][field]"] = cursor_field+ params["searchCriteria[sortOrders][0][direction]"] = "ASC"+ if cursor_value is not None:+ # `gteq` re-reads the boundary row rather than risking a skip when several rows share+ # the same second; the merge dedupes it on the primary key.+ params["searchCriteria[filter_groups][0][filters][0][field]"] = cursor_field+ params["searchCriteria[filter_groups][0][filters][0][value]"] = _format_magento_datetime(cursor_value)+ params["searchCriteria[filter_groups][0][filters][0][condition_type]"] = "gteq"+ else:+ params["searchCriteria[sortOrders][0][field]"] = config.sort_field+ params["searchCriteria[sortOrders][0][direction]"] = "ASC"++ return params+++def _read_capped_json(+ response: requests.Response,+ max_bytes: int | None = None,+ max_seconds: int | None = None,+) -> Any:+ """Parse a streamed JSON body, refusing one past the size or wall-clock budget.++ The host is customer-controlled, so a body must never be buffered unbounded, nor be allowed to+ hold the connection open by dribbling under the per-read timeout. Both caps are permanent+ failures — re-fetching the same page returns the same oversized/slow body. The token exchange+ passes tighter caps than a data page since its body is a single short string.+ """+ # Resolved at call time (not as defaults) so the module-level caps stay patchable in tests.+ max_bytes = MAX_RESPONSE_BYTES if max_bytes is None else max_bytes+ max_seconds = MAX_DOWNLOAD_SECONDS if max_seconds is None else max_seconds+ result: dict[str, Any] = {}++ def _drain() -> None:+ chunks: list[bytes] = []+ total = 0+ try:+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if not chunk:+ continue+ total += len(chunk)+ if total > max_bytes:+ result["error"] = AdobeCommerceResponseTooLargeError(+ f"Adobe Commerce response exceeded the {max_bytes}-byte limit; refusing to buffer it"+ )+ return+ chunks.append(chunk)+ result["body"] = b"".join(chunks)+ except Exception as e:+ result["error"] = e++ # `iter_content` blocks until its chunk fills while the socket's per-read timeout resets on every+ # byte, so a host dripping bytes could stall past `max_seconds` without any inline check running.+ # Read on a daemon thread we stop waiting on at the deadline, so the worker is freed even when the+ # underlying socket read never returns; the abandoned thread ends once that read eventually errors.+ worker = threading.Thread(target=_drain, daemon=True)+ worker.start()+ worker.join(max_seconds)+ try:+ if worker.is_alive():+ raise AdobeCommerceResponseTooSlowError(+ f"Adobe Commerce response exceeded the {max_seconds}s download budget; aborting"+ )+ if "error" in result:+ raise result["error"]+ return json.loads(result["body"])+ finally:+ response.close()+++def _read_body_preview(response: requests.Response) -> str:+ result: dict[str, bytes] = {}++ def _drain() -> None:+ chunks: list[bytes] = []+ total = 0+ try:+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if not chunk:+ continue+ chunks.append(chunk)+ total += len(chunk)+ if total >= _ERROR_BODY_PREVIEW_BYTES:+ break+ except Exception:+ # A preview read failing shouldn't mask the real error being logged.+ pass+ result["body"] = b"".join(chunks)[:_ERROR_BODY_PREVIEW_BYTES]++ # Same drip hazard as `_read_capped_json`: bound the error-preview read on a daemon thread and+ # give up at the deadline so a slow host can't stall the worker on the error path.+ worker = threading.Thread(target=_drain, daemon=True)+ worker.start()+ worker.join(MAX_DOWNLOAD_SECONDS)+ return result.get("body", b"").decode("utf-8", errors="replace")+++class AdobeCommerceTokenManager:+ """Resolves the bearer token for a run.++ Integration access tokens are long-lived and used verbatim. Admin tokens are minted from the+ merchant's admin username and password against `POST /V1/integration/admin/token` and expire+ after Magento's configured lifetime (4 hours by default), so they are re-minted in place.+ """++ def __init__(self, session: requests.Session, base_url: str, credentials: AdobeCommerceCredentials) -> None:+ self._session = session+ self._base_url = base_url+ self._credentials = credentials+ self._token: str | None = None+ self._deadline: float = 0.0++ def get_token(self) -> str:+ if self._credentials.method == "access_token":+ if not self._credentials.access_token:+ raise AdobeCommerceConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: access token required")+ return self._credentials.access_token++ if self._token is None or time.monotonic() >= self._deadline - TOKEN_REFRESH_MARGIN_SECONDS:+ self._mint()+ assert self._token is not None+ return self._token++ def _mint(self) -> None:+ if not self._credentials.username or not self._credentials.password:+ raise AdobeCommerceConfigurationError(+ f"{INCOMPLETE_CREDENTIALS_ERROR}: admin username and password required"+ )++ response = self._session.post(+ f"{self._base_url}/integration/admin/token",+ json={"username": self._credentials.username, "password": self._credentials.password},+ headers={"Content-Type": "application/json", "Accept": "application/json"},+ # `requests` applies this per socket op, so it also bounds the connect and+ # response-header wait — a hostile store can't stall the exchange before the body cap+ # kicks in while validation runs inline on the API thread.+ timeout=TOKEN_DOWNLOAD_SECONDS,+ allow_redirects=False,+ stream=True,+ )++ try:+ if response.status_code == 429 or response.status_code >= 500:+ raise AdobeCommerceRetryableError(+ f"Adobe Commerce admin token request failed (retryable): status={response.status_code}"+ )+ # A 3xx is not an error status, so refuse it explicitly rather than following it to a+ # potentially internal Location.+ if response.is_redirect or response.is_permanent_redirect:+ raise AdobeCommerceHostNotAllowedError(+ f"Adobe Commerce returned an unexpected redirect (status={response.status_code}) for the token request"+ )+ response.raise_for_status()+ try:+ payload = _read_capped_json(+ response, max_bytes=TOKEN_RESPONSE_MAX_BYTES, max_seconds=TOKEN_DOWNLOAD_SECONDS+ )+ except (AdobeCommerceResponseTooLargeError, AdobeCommerceResponseTooSlowError) as e:+ # A real token is a short string, so an oversized or dribbled body means the URL+ # isn't a Magento token endpoint — permanent, not worth retrying.+ raise AdobeCommerceConfigurationError(+ "Adobe Commerce returned an oversized admin token response; check the store URL points at a Magento REST API"+ ) from e+ finally:+ response.close()++ # The endpoint returns the token as a bare JSON string.+ if not isinstance(payload, str) or not payload:+ raise AdobeCommerceConfigurationError(+ "Adobe Commerce returned an unexpected admin token response; check the store URL points at a Magento REST API"+ )++ self._token = payload+ self._deadline = time.monotonic() + ADMIN_TOKEN_LIFETIME_SECONDS+++def _make_session(+ credentials: AdobeCommerceCredentials, capture: bool = True, retry: Retry | None = None+) -> requests.Session:+ # `allow_redirects=False` keeps traffic pointed at the host that was validated. Secrets are+ # redacted from logged URLs and captured samples by value, since the admin password rides a+ # JSON body the name-based scrubbers can't recognise on every install. `retry=None` keeps the+ # default retrying policy; validation passes `_NO_RETRY` so its sleeps can't stall a worker.+ return make_tracked_session(+ retry=retry,+ redact_values=credentials.secret_values(),+ allow_redirects=False,+ capture=capture,+ )+++def _request_page(+ session: requests.Session,+ token_manager: AdobeCommerceTokenManager,+ url: str,+ logger: FilteringBoundLogger,+ timeout: int = REQUEST_TIMEOUT_SECONDS,+) -> Any:+ """GET one URL with a fresh bearer token and return the parsed body.++ Transport-level retries for 429/5xx already live in the tracked session, so nothing is retried+ here — an exhausted status surfaces as an `HTTPError` and the activity retries the whole job.+ """+ headers = {"Authorization": f"Bearer {token_manager.get_token()}", "Accept": "application/json"}+ response = session.get(url, headers=headers, timeout=timeout, allow_redirects=False, stream=True)++ try:+ if response.is_redirect or response.is_permanent_redirect:+ raise AdobeCommerceHostNotAllowedError(+ f"Adobe Commerce returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )+ if not response.ok:+ body = _read_body_preview(response)+ logger.error(f"Adobe Commerce API error: status={response.status_code}, body={body}, url={url}")+ response.raise_for_status()+ return _read_capped_json(response)+ finally:+ response.close()+++def _extract_items(payload: Any) -> list[dict[str, Any]]:+ """Pull the row list out of either response shape Magento uses.++ searchCriteria collections answer `{"items": [...], "total_count": N}`; the reference endpoints+ (store views, websites, countries) answer with a bare array.+ """+ if isinstance(payload, list):+ return [row for row in payload if isinstance(row, dict)]+ if isinstance(payload, dict):+ items = payload.get("items")+ if isinstance(items, list):+ return [row for row in items if isinstance(row, dict)]+ raise AdobeCommerceRetryableError(f"Adobe Commerce returned an unexpected payload: {type(payload).__name__}")+++def _total_count(payload: Any) -> int | None:+ if isinstance(payload, dict):+ total = payload.get("total_count")+ if isinstance(total, int):+ return total+ return None+++def get_rows(+ store_url: str,+ store_code: str | None,+ credentials: AdobeCommerceCredentials,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AdobeCommerceResumeConfig],+ should_use_incremental_field: bool = False,+ incremental_field_name: Optional[str] = None,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = ADOBE_COMMERCE_ENDPOINTS[endpoint]++ # Re-check at run time, not just at source-create, in case the URL was edited or now resolves+ # to an internal address. Only enforced on cloud — see `_is_host_safe`.+ host_ok, host_err = _is_host_safe(store_host(store_url), team_id)+ if not host_ok:+ raise AdobeCommerceHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ base_url = _base_url(store_url, store_code)+ session = _make_session(credentials)+ # Token exchanges carry the credential in the request and response body, so keep them out of+ # opt-in HTTP sample capture entirely.+ token_manager = AdobeCommerceTokenManager(_make_session(credentials, capture=False), base_url, credentials)++ if not config.uses_search_criteria:+ payload = _request_page(session, token_manager, f"{base_url}{config.path}", logger)+ rows = _extract_items(payload)+ if rows:+ yield rows+ return++ cursor_field = (incremental_field_name or config.incremental_field_name) if should_use_incremental_field else None+ cursor_value = db_incremental_field_last_value if should_use_incremental_field else None++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.current_page if resume is not None else 1+ if resume is not None:+ logger.debug(f"Adobe Commerce: resuming {endpoint} from page {page}")++ loop_deadline = time.monotonic() + MAX_PAGINATION_SECONDS+ while True:+ if page > MAX_PAGES:+ raise AdobeCommercePaginationLimitError(f"{PAGINATION_LIMIT_ERROR}: {endpoint} exceeded {MAX_PAGES} pages")+ if time.monotonic() > loop_deadline:+ raise AdobeCommercePaginationLimitError(+ f"{PAGINATION_LIMIT_ERROR}: {endpoint} exceeded the {MAX_PAGINATION_SECONDS}s pagination budget"+ )++ params = build_search_criteria(config, page, cursor_field, cursor_value)+ payload = _request_page(session, token_manager, _build_url(base_url, config.path, params), logger)+ rows = _extract_items(payload)+ if not rows:+ break++ yield rows++ total = _total_count(payload)+ if total is not None and page * config.page_size >= total:+ break+ # A short page also means the collection is exhausted, which covers a server that omits+ # `total_count` entirely.+ if len(rows) < config.page_size:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; the+ # merge dedupes on the primary key.+ page += 1+ resumable_source_manager.save_state(AdobeCommerceResumeConfig(current_page=page))+++def adobe_commerce_source(+ store_url: str,+ store_code: str | None,+ credentials: AdobeCommerceCredentials,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AdobeCommerceResumeConfig],+ should_use_incremental_field: bool = False,+ incremental_field_name: Optional[str] = None,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = ADOBE_COMMERCE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ store_url=store_url,+ store_code=store_code,+ credentials=credentials,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field_name=incremental_field_name,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # Incremental runs ask Magento for `sortOrders[0][direction]=ASC` on the cursor column, so+ # the watermark can checkpoint after every batch.+ sort_mode="asc",+ )+++def _probe(+ session: requests.Session,+ token_manager: AdobeCommerceTokenManager,+ base_url: str,+ endpoint: str,+ timeout: float,+) -> tuple[int, str | None]:+ """Request one row from an endpoint. Returns `(status, error_message)`; status 0 on transport failure."""+ config = ADOBE_COMMERCE_ENDPOINTS[endpoint]+ params = build_search_criteria(config, page=1) if config.uses_search_criteria else {}+ if params:+ params["searchCriteria[pageSize]"] = 1+ url = _build_url(base_url, config.path, params)++ try:+ headers = {"Authorization": f"Bearer {token_manager.get_token()}", "Accept": "application/json"}+ response = session.get(url, headers=headers, timeout=timeout, allow_redirects=False, stream=True)+ except requests.exceptions.RequestException as e:+ return 0, str(e)++ try:+ if response.is_redirect or response.is_permanent_redirect:+ return 0, HOST_NOT_ALLOWED_ERROR+ return response.status_code, None+ finally:+ response.close()+++def validate_credentials(+ store_url: str,+ store_code: str | None,+ credentials: AdobeCommerceCredentials,+ schema_name: Optional[str] = None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Confirm the store URL and credentials actually reach a Magento REST API.++ At source-create (`schema_name is None`) the probe walks a short list of common read+ endpoints and passes on the first 200 — Magento answers an unauthorized *resource* with the+ same 401 it uses for a bad token, so one endpoint the integration happens not to cover would+ otherwise look identical to invalid credentials. With `schema_name` set the probe targets that+ endpoint only, so the schema picker reports its real access.+ """+ try:+ base_url = _base_url(store_url, store_code)+ except ValueError as e:+ return False, str(e)++ if team_id is not None:+ host_ok, host_err = _is_host_safe(store_host(store_url), team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ session = _make_session(credentials, capture=False, retry=_NO_RETRY)+ token_manager = AdobeCommerceTokenManager(session, base_url, credentials)++ try:+ token_manager.get_token()+ except AdobeCommerceConfigurationError as e:+ return False, str(e)+ except AdobeCommerceHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status == 401:+ return False, "Adobe Commerce rejected the admin username and password."+ if status == 404:+ return False, "No Adobe Commerce REST API found at that store URL. Check the URL and store code."+ return False, f"Could not sign in to Adobe Commerce (HTTP {status})."+ except (AdobeCommerceRetryableError, requests.exceptions.RequestException) as e:+ return False, str(e)++ probes = (schema_name,) if schema_name is not None else VALIDATION_PROBE_ENDPOINTS+ last_status: int | None = None+ last_error: str | None = None+ # Bound the whole probe sequence to a single wall-clock budget so a host that stalls on every+ # endpoint can't tie up an API worker for `len(probes) * VALIDATE_TIMEOUT_SECONDS`.+ deadline = time.monotonic() + VALIDATE_TIMEOUT_SECONDS+ for endpoint in probes:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ last_status, last_error = 0, "Adobe Commerce did not respond in time."+ break+ status, error = _probe(session, token_manager, base_url, endpoint, min(VALIDATE_TIMEOUT_SECONDS, remaining))+ if status == 200:+ return True, None+ last_status, last_error = status, error+ # A transport failure means the host is unreachable or stalling; the remaining endpoints live+ # on the same host, so stop rather than pay another timeout for each of them.+ if status == 0:+ break++ if last_status in (401, 403):+ return False, (+ "Adobe Commerce rejected the credentials. Check the token is valid and the integration has read "+ "access. On Magento 2.4.4 and later, also enable Stores → Configuration → Services → OAuth → "+ "Access Token Expiration → 'Allow OAuth Access Tokens to be used as standalone Bearer tokens'."+ )+ if last_status == 404:+ return False, "No Adobe Commerce REST API found at that store URL. Check the URL and store code."+ if last_status == 0:+ return False, last_error or "Could not connect to your Adobe Commerce store."+ return False, f"Adobe Commerce returned HTTP {last_status}."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/canonical_descriptions.pynew file mode 100644index 000000000000..bd638b264d4c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/canonical_descriptions.py@@ -0,0 +1,290 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_REST_DOCS = "https://adobe-commerce.redoc.ly/2.4.7-admin/tag"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "orders": {+ "description": "Sales orders placed in the store, with their totals, status, addresses, payment and line items.",+ "docs_url": f"{_REST_DOCS}/orders",+ "columns": {+ "entity_id": "Internal numeric identifier of the order.",+ "increment_id": "Human-readable order number shown to the customer and in the admin.",+ "state": "Order state machine value (new, processing, complete, closed, canceled, holded, payment_review).",+ "status": "Order status label, which stores map onto a state.",+ "store_id": "Store view the order was placed in.",+ "customer_id": "Identifier of the registered customer, null for guest checkouts.",+ "customer_email": "Email address the order was placed with.",+ "customer_is_guest": "1 when the order was placed without a customer account.",+ "base_grand_total": "Order grand total in the store's base currency.",+ "grand_total": "Order grand total in the currency the order was placed in.",+ "subtotal": "Sum of the line item row totals, excluding shipping, tax and discounts.",+ "tax_amount": "Total tax charged on the order.",+ "shipping_amount": "Shipping charge applied to the order.",+ "discount_amount": "Total discount applied to the order, as a negative amount.",+ "total_qty_ordered": "Sum of the quantities ordered across all line items.",+ "order_currency_code": "Currency the order was placed in.",+ "base_currency_code": "Base currency of the store the order belongs to.",+ "created_at": "Timestamp the order was placed (UTC).",+ "updated_at": "Timestamp the order row was last modified (UTC).",+ "items": "Line items on the order, each with sku, name, quantities and per-row totals.",+ "billing_address": "Billing address captured at checkout.",+ "extension_attributes": "Extension data such as shipping assignments, applied taxes and gift message.",+ "payment": "Payment record for the order, including method, amounts authorized and captured.",+ },+ },+ "invoices": {+ "description": "Invoices issued against orders, recording the amounts captured for a set of order line items.",+ "docs_url": f"{_REST_DOCS}/invoices",+ "columns": {+ "entity_id": "Internal numeric identifier of the invoice.",+ "increment_id": "Human-readable invoice number.",+ "order_id": "Identifier of the order the invoice belongs to.",+ "state": "Invoice state (1 = pending, 2 = paid, 3 = canceled).",+ "store_id": "Store view the invoice belongs to.",+ "grand_total": "Invoice grand total in the order currency.",+ "base_grand_total": "Invoice grand total in the store's base currency.",+ "subtotal": "Sum of the invoiced line item row totals.",+ "tax_amount": "Tax invoiced.",+ "shipping_amount": "Shipping invoiced.",+ "total_qty": "Total quantity invoiced across line items.",+ "created_at": "Timestamp the invoice was created (UTC).",+ "updated_at": "Timestamp the invoice row was last modified (UTC).",+ "items": "Invoiced line items with sku, quantity invoiced and row totals.",+ },+ },+ "shipments": {+ "description": "Shipments dispatched against orders, with their packages, tracking numbers and shipped items.",+ "docs_url": f"{_REST_DOCS}/shipments",+ "columns": {+ "entity_id": "Internal numeric identifier of the shipment.",+ "increment_id": "Human-readable shipment number.",+ "order_id": "Identifier of the order the shipment belongs to.",+ "store_id": "Store view the shipment belongs to.",+ "total_qty": "Total quantity shipped across line items.",+ "total_weight": "Total weight of the shipment.",+ "created_at": "Timestamp the shipment was created (UTC).",+ "updated_at": "Timestamp the shipment row was last modified (UTC).",+ "items": "Shipped line items with sku, name and quantity shipped.",+ "tracks": "Tracking records attached to the shipment (carrier code, title, tracking number).",+ "packages": "Packages the shipment was split into.",+ },+ },+ "creditmemos": {+ "description": "Credit memos (refunds) issued against orders, recording refunded amounts and returned items.",+ "docs_url": f"{_REST_DOCS}/creditmemos",+ "columns": {+ "entity_id": "Internal numeric identifier of the credit memo.",+ "increment_id": "Human-readable credit memo number.",+ "order_id": "Identifier of the order the credit memo belongs to.",+ "state": "Credit memo state (1 = open, 2 = refunded, 3 = canceled).",+ "store_id": "Store view the credit memo belongs to.",+ "grand_total": "Total refunded in the order currency.",+ "base_grand_total": "Total refunded in the store's base currency.",+ "subtotal": "Sum of the refunded line item row totals.",+ "tax_amount": "Tax refunded.",+ "shipping_amount": "Shipping refunded.",+ "adjustment": "Net manual adjustment applied to the refund.",+ "created_at": "Timestamp the credit memo was created (UTC).",+ "updated_at": "Timestamp the credit memo row was last modified (UTC).",+ "items": "Refunded line items with sku, quantity refunded and row totals.",+ },+ },+ "transactions": {+ "description": "Payment gateway transactions recorded against order payments (authorization, capture, refund, void).",+ "docs_url": f"{_REST_DOCS}/transactions",+ "columns": {+ "transaction_id": "Internal numeric identifier of the transaction.",+ "parent_id": "Identifier of the parent transaction, when this one was derived from another.",+ "order_id": "Identifier of the order the transaction belongs to.",+ "payment_id": "Identifier of the order payment record the transaction belongs to.",+ "txn_id": "Transaction identifier assigned by the payment gateway.",+ "parent_txn_id": "Gateway identifier of the parent transaction.",+ "txn_type": "Transaction type (order, authorization, capture, void, refund).",+ "is_closed": "1 when no further operations are possible on this transaction.",+ "additional_information": "Raw gateway response data stored with the transaction.",+ "created_at": "Timestamp the transaction was recorded (UTC).",+ },+ },+ "products": {+ "description": "Catalog products with their type, price, status, attribute set, custom attributes and media.",+ "docs_url": f"{_REST_DOCS}/products",+ "columns": {+ "id": "Internal numeric identifier of the product.",+ "sku": "Stock keeping unit, the store-unique product code.",+ "name": "Product name.",+ "attribute_set_id": "Attribute set the product's attributes come from.",+ "price": "Product price in the store's base currency.",+ "status": "Product status (1 = enabled, 2 = disabled).",+ "visibility": "Catalog visibility (1 = not visible, 2 = catalog, 3 = search, 4 = catalog and search).",+ "type_id": "Product type (simple, configurable, bundle, grouped, virtual, downloadable).",+ "weight": "Product weight.",+ "created_at": "Timestamp the product was created (UTC).",+ "updated_at": "Timestamp the product was last modified (UTC).",+ "custom_attributes": "EAV attribute values that are not part of the fixed product interface.",+ "media_gallery_entries": "Images and video attached to the product.",+ "extension_attributes": "Extension data such as stock item, category links, website ids and configurable options.",+ "product_links": "Related, up-sell and cross-sell links to other products.",+ "tier_prices": "Quantity- and group-based tier pricing rows.",+ },+ },+ "categories": {+ "description": "Catalog categories, one row per category in the tree, with its position, level and path.",+ "docs_url": f"{_REST_DOCS}/categories",+ "columns": {+ "id": "Internal numeric identifier of the category.",+ "parent_id": "Identifier of the parent category.",+ "name": "Category name.",+ "is_active": "Whether the category is enabled in the storefront.",+ "position": "Sort position among its siblings.",+ "level": "Depth in the category tree, starting at the root.",+ "path": "Slash-separated list of ancestor ids down to this category.",+ "children": "Comma-separated identifiers of the direct child categories.",+ "include_in_menu": "Whether the category appears in the storefront navigation.",+ "created_at": "Timestamp the category was created (UTC).",+ "updated_at": "Timestamp the category was last modified (UTC).",+ "custom_attributes": "EAV attribute values such as url_key, description and display settings.",+ },+ },+ "customers": {+ "description": "Registered customer accounts with their identity, group, store scope and addresses.",+ "docs_url": f"{_REST_DOCS}/customers",+ "columns": {+ "id": "Internal numeric identifier of the customer.",+ "email": "Customer email address, unique within the website.",+ "firstname": "Customer first name.",+ "lastname": "Customer last name.",+ "group_id": "Customer group the account belongs to.",+ "store_id": "Store view the account was created in.",+ "website_id": "Website the account belongs to.",+ "created_in": "Name of the store view the account was created in.",+ "confirmation": "Account confirmation key, set while confirmation is pending.",+ "disable_auto_group_change": "1 when automatic group assignment (e.g. by VAT) is disabled.",+ "created_at": "Timestamp the account was created (UTC).",+ "updated_at": "Timestamp the account was last modified (UTC).",+ "addresses": "Address book entries belonging to the customer.",+ "default_billing": "Identifier of the customer's default billing address.",+ "default_shipping": "Identifier of the customer's default shipping address.",+ "custom_attributes": "EAV attribute values that are not part of the fixed customer interface.",+ },+ },+ "carts": {+ "description": "Shopping carts (quotes), including active carts and the abandoned ones left behind at checkout.",+ "docs_url": f"{_REST_DOCS}/carts",+ "columns": {+ "id": "Internal numeric identifier of the cart (quote).",+ "store_id": "Store view the cart belongs to.",+ "is_active": "Whether the cart is still active, as opposed to converted or abandoned.",+ "is_virtual": "Whether the cart contains only virtual or downloadable products.",+ "items_count": "Number of distinct line items in the cart.",+ "items_qty": "Total quantity across the cart's line items.",+ "customer": "Customer the cart belongs to, or the guest details captured at checkout.",+ "currency": "Base, store, quote and global currency codes with their conversion rates.",+ "customer_is_guest": "1 when the cart belongs to a guest rather than a registered customer.",+ "orig_order_id": "Identifier of the order this cart was reordered from, if any.",+ "converted_at": "Timestamp the cart was converted into an order (UTC).",+ "created_at": "Timestamp the cart was created (UTC).",+ "updated_at": "Timestamp the cart was last modified (UTC).",+ "items": "Cart line items with sku, name, quantity and prices.",+ },+ },+ "coupons": {+ "description": "Coupon codes attached to cart price rules, including auto-generated codes and their usage limits.",+ "docs_url": f"{_REST_DOCS}/coupons",+ "columns": {+ "coupon_id": "Internal numeric identifier of the coupon.",+ "rule_id": "Identifier of the cart price rule the coupon belongs to.",+ "code": "The coupon code a shopper enters at checkout.",+ "usage_limit": "Maximum number of times the coupon can be used overall.",+ "usage_per_customer": "Maximum number of times a single customer can use the coupon.",+ "times_used": "Number of times the coupon has been redeemed.",+ "expiration_date": "Date the coupon stops working.",+ "is_primary": "1 when this is the rule's primary coupon rather than a generated one.",+ "type": "Coupon type (0 = manually specified, 1 = auto-generated).",+ "created_at": "Timestamp the coupon was created (UTC).",+ },+ },+ "customer_groups": {+ "description": "Customer groups used for pricing, tax classes and cart price rule targeting.",+ "docs_url": f"{_REST_DOCS}/customerGroups",+ "columns": {+ "id": "Internal numeric identifier of the customer group.",+ "code": "Display name of the group (e.g. General, Wholesale, NOT LOGGED IN).",+ "tax_class_id": "Identifier of the tax class applied to members of the group.",+ "tax_class_name": "Name of the tax class applied to members of the group.",+ },+ },+ "product_attributes": {+ "description": "Product EAV attribute definitions, describing every field the catalog can store on a product.",+ "docs_url": f"{_REST_DOCS}/productsattributes",+ "columns": {+ "attribute_id": "Internal numeric identifier of the attribute.",+ "attribute_code": "Machine name of the attribute, used as the key in product custom_attributes.",+ "frontend_input": "Input type rendered for the attribute (text, select, boolean, price, ...).",+ "default_frontend_label": "Default admin label of the attribute.",+ "frontend_labels": "Per-store-view labels of the attribute.",+ "is_required": "Whether the attribute must be filled in.",+ "is_unique": "Whether the attribute value must be unique across products.",+ "scope": "Scope the value is stored at (global, website or store).",+ "backend_type": "Storage type of the value (varchar, int, decimal, datetime, text, static).",+ "options": "Selectable option values, for select and multiselect attributes.",+ "is_user_defined": "Whether the attribute was created by an admin rather than shipped with Magento.",+ },+ },+ "tax_classes": {+ "description": "Tax classes that products and customer groups are assigned to when calculating tax rules.",+ "docs_url": f"{_REST_DOCS}/taxClasses",+ "columns": {+ "class_id": "Internal numeric identifier of the tax class.",+ "class_name": "Display name of the tax class.",+ "class_type": "Whether the class applies to PRODUCT or CUSTOMER.",+ },+ },+ "store_views": {+ "description": "Store views configured on the instance — the storefront scope that localizes catalog and prices.",+ "docs_url": f"{_REST_DOCS}/store",+ "columns": {+ "id": "Internal numeric identifier of the store view.",+ "code": "Store view code, used as the scope segment in REST paths.",+ "name": "Display name of the store view.",+ "website_id": "Website the store view belongs to.",+ "store_group_id": "Store group the store view belongs to.",+ "is_active": "Whether the store view is enabled.",+ },+ },+ "store_groups": {+ "description": "Store groups, the middle scope that binds a root category to a set of store views.",+ "docs_url": f"{_REST_DOCS}/store",+ "columns": {+ "id": "Internal numeric identifier of the store group.",+ "code": "Store group code.",+ "name": "Display name of the store group.",+ "website_id": "Website the store group belongs to.",+ "root_category_id": "Root catalog category the group's store views browse.",+ "default_store_id": "Store view used by default for this group.",+ },+ },+ "websites": {+ "description": "Websites configured on the instance — the outermost scope, owning customer accounts and base currency.",+ "docs_url": f"{_REST_DOCS}/store",+ "columns": {+ "id": "Internal numeric identifier of the website.",+ "code": "Website code.",+ "name": "Display name of the website.",+ "default_group_id": "Store group used by default for this website.",+ },+ },+ "countries": {+ "description": "Directory of countries the instance knows about, with their ISO codes, locale names and regions.",+ "docs_url": f"{_REST_DOCS}/directory",+ "columns": {+ "id": "ISO 3166-1 alpha-2 country code, used as the identifier.",+ "two_letter_abbreviation": "ISO 3166-1 alpha-2 country code.",+ "three_letter_abbreviation": "ISO 3166-1 alpha-3 country code.",+ "full_name_locale": "Country name in the admin locale.",+ "full_name_english": "Country name in English.",+ "available_regions": "Regions or states defined for the country.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/settings.pynew file mode 100644index 000000000000..8a58de695b6f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/settings.py@@ -0,0 +1,169 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Magento caps nothing server-side, but /V1/products rows are wide (custom attributes, media+# gallery, tier prices) and large catalogs make big pages slow, so keep the page moderate.+DEFAULT_PAGE_SIZE = 200+++@dataclass+class AdobeCommerceEndpointConfig:+ name: str+ # Path below the `/rest/<store_code>/V1` prefix.+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Most Magento collections are `GET <path>?searchCriteria[...]` returning+ # {"items": [...], "search_criteria": {...}, "total_count": N}. A handful of reference+ # endpoints (store views, websites, countries) take no searchCriteria and return a bare array.+ uses_search_criteria: bool = True+ page_size: int = DEFAULT_PAGE_SIZE+ # Server-side timestamp column used for both the `gteq` filter and the ascending sort on+ # incremental runs. `None` means the entity carries no modification timestamp, so the table+ # is full refresh only.+ incremental_field_name: Optional[str] = None+ # Column the pages are sorted by on a full refresh, so page boundaries stay stable while rows+ # are inserted mid-sync. searchCriteria sorts and filters address the underlying table column,+ # which is not always the name the response uses (`/V1/products` returns `id` but sorts on+ # `entity_id`), so set this whenever the two differ. Defaults to the primary key.+ full_refresh_sort_field: Optional[str] = None++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if self.incremental_field_name is None:+ return []+ return [incremental_field(self.incremental_field_name)]++ @property+ def sort_field(self) -> str:+ return self.full_refresh_sort_field or self.primary_keys[0]+++# Magento 2 / Adobe Commerce REST collections. Every entry below is a documented list endpoint on+# a stock install; the sales, catalog, customer and quote entities all carry `created_at` and+# `updated_at` columns that the searchCriteria filter can compare server-side, which is what makes+# them incremental. Transactions and coupons only ever get a `created_at` (their rows are never+# rewritten), and the reference tables carry no timestamps at all.+ADOBE_COMMERCE_ENDPOINTS: dict[str, AdobeCommerceEndpointConfig] = {+ "orders": AdobeCommerceEndpointConfig(+ name="orders",+ path="/orders",+ primary_keys=["entity_id"],+ incremental_field_name="updated_at",+ ),+ "invoices": AdobeCommerceEndpointConfig(+ name="invoices",+ path="/invoices",+ primary_keys=["entity_id"],+ incremental_field_name="updated_at",+ ),+ "shipments": AdobeCommerceEndpointConfig(+ name="shipments",+ path="/shipments",+ primary_keys=["entity_id"],+ incremental_field_name="updated_at",+ ),+ "creditmemos": AdobeCommerceEndpointConfig(+ name="creditmemos",+ path="/creditmemos",+ primary_keys=["entity_id"],+ incremental_field_name="updated_at",+ ),+ # `sales_payment_transaction` rows are written once and never updated, so `created_at` is a+ # stable cursor.+ "transactions": AdobeCommerceEndpointConfig(+ name="transactions",+ path="/transactions",+ primary_keys=["transaction_id"],+ incremental_field_name="created_at",+ ),+ "products": AdobeCommerceEndpointConfig(+ name="products",+ path="/products",+ primary_keys=["id"],+ full_refresh_sort_field="entity_id",+ page_size=100,+ incremental_field_name="updated_at",+ ),+ "categories": AdobeCommerceEndpointConfig(+ name="categories",+ path="/categories/list",+ primary_keys=["id"],+ full_refresh_sort_field="entity_id",+ incremental_field_name="updated_at",+ ),+ "customers": AdobeCommerceEndpointConfig(+ name="customers",+ path="/customers/search",+ primary_keys=["id"],+ full_refresh_sort_field="entity_id",+ incremental_field_name="updated_at",+ ),+ "carts": AdobeCommerceEndpointConfig(+ name="carts",+ path="/carts/search",+ primary_keys=["id"],+ full_refresh_sort_field="entity_id",+ incremental_field_name="updated_at",+ ),+ # `salesrule_coupon` rows are created with the rule and not rewritten afterwards.+ "coupons": AdobeCommerceEndpointConfig(+ name="coupons",+ path="/coupons/search",+ primary_keys=["coupon_id"],+ incremental_field_name="created_at",+ ),+ "customer_groups": AdobeCommerceEndpointConfig(+ name="customer_groups",+ path="/customerGroups/search",+ primary_keys=["id"],+ ),+ "product_attributes": AdobeCommerceEndpointConfig(+ name="product_attributes",+ path="/products/attributes",+ primary_keys=["attribute_id"],+ ),+ "tax_classes": AdobeCommerceEndpointConfig(+ name="tax_classes",+ path="/taxClasses/search",+ primary_keys=["class_id"],+ ),+ "store_views": AdobeCommerceEndpointConfig(+ name="store_views",+ path="/store/storeViews",+ primary_keys=["id"],+ uses_search_criteria=False,+ ),+ "store_groups": AdobeCommerceEndpointConfig(+ name="store_groups",+ path="/store/storeGroups",+ primary_keys=["id"],+ uses_search_criteria=False,+ ),+ "websites": AdobeCommerceEndpointConfig(+ name="websites",+ path="/store/websites",+ primary_keys=["id"],+ uses_search_criteria=False,+ ),+ "countries": AdobeCommerceEndpointConfig(+ name="countries",+ path="/directory/countries",+ primary_keys=["id"],+ uses_search_criteria=False,+ ),+}++ENDPOINTS = tuple(ADOBE_COMMERCE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ADOBE_COMMERCE_ENDPOINTS.items() if config.incremental_fields+}++# Ordered probe list for source-create validation. Magento answers an unauthorized *resource* with+# the same 401 it uses for an invalid token, so a single probe against a resource the integration+# happens not to have would look identical to bad credentials. Trying the common read ACLs in turn+# and accepting the first 200 keeps a narrowly-scoped integration connectable.+VALIDATION_PROBE_ENDPOINTS = ("orders", "products", "customers", "store_views")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/source.pyindex b8b461794bf8..8d83f2f6db3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/source.py@@ -1,33 +1,231 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.adobe_commerce import (+ HOST_NOT_ALLOWED_ERROR,+ HTTPS_REQUIRED_ERROR,+ INCOMPLETE_CREDENTIALS_ERROR,+ PAGINATION_LIMIT_ERROR,+ AdobeCommerceCredentials,+ AdobeCommerceResumeConfig,+ adobe_commerce_source,+ validate_credentials as validate_adobe_commerce_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.settings import (+ ADOBE_COMMERCE_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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.adobecommerce import (AdobeCommerceSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+CAPTION = """Enter your Adobe Commerce (Magento 2) store URL and API credentials to pull your store data into the PostHog Data warehouse.++The recommended way to connect is an integration access token: in the admin go to **System > Extensions > Integrations**, create an integration, grant it read access to Sales, Catalog, Customers and Carts, then activate it and copy the **Access Token**.++On Magento 2.4.4 and later, integration tokens are rejected as bearer tokens until you set **Stores > Configuration > Services > OAuth > Access Token Expiration > Allow OAuth Access Tokens to be used as standalone Bearer tokens** to **Yes**. If you can't change that setting, connect with an admin username and password instead and PostHog will mint a short-lived admin token for each sync."""+++def _credentials_from_config(config: AdobeCommerceSourceConfig) -> AdobeCommerceCredentials:+ auth = config.auth_method+ if auth.selection == "admin":+ return AdobeCommerceCredentials(method="admin", username=auth.username, password=auth.password)+ return AdobeCommerceCredentials(method="access_token", access_token=auth.access_token)+@SourceRegistry.register-class AdobeCommerceSource(SimpleSource[AdobeCommerceSourceConfig]):+class AdobeCommerceSource(ResumableSource[AdobeCommerceSourceConfig, AdobeCommerceResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # Magento's REST namespace has been `/V1` since Magento 2.0 and isn't a version merchants can+ # pick, so there is nothing meaningful to pin.+ api_docs_url = "https://developer.adobe.com/commerce/webapi/rest/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ADOBECOMMERCE+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored token/password is sent to `store_url`; retargeting it must re-require them.+ return ["store_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ADOBE_COMMERCE,category=DataWarehouseSourceCategory.E_COMMERCE,- keywords=["magento"],+ keywords=["magento", "magento 2", "adobe"],label="Adobe Commerce (Magento)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=CAPTION,iconPath="/static/services/adobe_commerce.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/adobe-commerce",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="store_url",+ label="Store URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://store.example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="store_code",+ label="Store code (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="default",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="access_token",+ options=[+ SourceFieldSelectConfigOption(+ label="Integration access token (recommended)",+ value="access_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Admin username and password",+ value="admin",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Admin username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Admin password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The URL carries the merchant's own host, so match on the status prefix only.+ return {+ "401 Client Error": "Adobe Commerce rejected the credentials. Check the access token (or admin login) is valid and the integration has read access to this data. On Magento 2.4.4 and later, also enable 'Allow OAuth Access Tokens to be used as standalone Bearer tokens'.",+ "403 Client Error": "Your Adobe Commerce integration does not have read access to this data. Grant it under System > Extensions > Integrations, then reconnect.",+ HOST_NOT_ALLOWED_ERROR: "The Adobe Commerce store URL is not allowed. Use your store's public URL.",+ HTTPS_REQUIRED_ERROR: "The Adobe Commerce store URL must use HTTPS so your credentials aren't sent in the clear. Update the store URL and reconnect.",+ INCOMPLETE_CREDENTIALS_ERROR: "Adobe Commerce credentials are incomplete. Please re-enter them and reconnect.",+ PAGINATION_LIMIT_ERROR: "Adobe Commerce kept returning pages without signalling the end of the collection. This usually means the store's REST API is misconfigured — check the store URL and store code.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AdobeCommerceSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Sales and catalog rows are rewritten in place (an order's status advances, a product's+ # price changes), so append mode would duplicate them — merge is the only incremental mode.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)++ def validate_credentials(+ self,+ config: AdobeCommerceSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_adobe_commerce_credentials(+ store_url=config.store_url,+ store_code=config.store_code,+ credentials=_credentials_from_config(config),+ schema_name=schema_name,+ team_id=team_id,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AdobeCommerceResumeConfig]:+ return ResumableSourceManager[AdobeCommerceResumeConfig](inputs, AdobeCommerceResumeConfig)++ def source_for_pipeline(+ self,+ config: AdobeCommerceSourceConfig,+ resumable_source_manager: ResumableSourceManager[AdobeCommerceResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ADOBE_COMMERCE_ENDPOINTS:+ raise ValueError(f"Unknown Adobe Commerce schema '{inputs.schema_name}'")++ return adobe_commerce_source(+ store_url=config.store_url,+ store_code=config.store_code,+ credentials=_credentials_from_config(config),+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ incremental_field_name=inputs.incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce.pynew file mode 100644index 000000000000..2de3e1e1617b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce.py@@ -0,0 +1,736 @@+import json+import threading+from collections.abc import Callable, Iterable, Iterator+from datetime import UTC, date, datetime+from typing import Any, cast+from urllib.parse import parse_qsl, urlparse+from zoneinfo import ZoneInfo++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce import adobe_commerce+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.adobe_commerce import (+ HOST_NOT_ALLOWED_ERROR,+ MAX_RESPONSE_BYTES,+ AdobeCommerceConfigurationError,+ AdobeCommerceCredentials,+ AdobeCommerceHostNotAllowedError,+ AdobeCommercePaginationLimitError,+ AdobeCommerceResponseTooLargeError,+ AdobeCommerceResponseTooSlowError,+ AdobeCommerceResumeConfig,+ AdobeCommerceRetryableError,+ AdobeCommerceTokenManager,+ _base_url,+ _format_magento_datetime,+ _read_capped_json,+ _request_page,+ adobe_commerce_source,+ build_search_criteria,+ get_rows,+ normalize_store_code,+ normalize_store_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.settings import (+ ADOBE_COMMERCE_ENDPOINTS,+ ENDPOINTS,+ VALIDATION_PROBE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++TOKEN_CREDENTIALS = AdobeCommerceCredentials(method="access_token", access_token="tok-123")+ADMIN_CREDENTIALS = AdobeCommerceCredentials(method="admin", username="admin", password="hunter2")+++class _FakeResumableManager(ResumableSourceManager[AdobeCommerceResumeConfig]):+ def __init__(self, state: AdobeCommerceResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AdobeCommerceResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> AdobeCommerceResumeConfig | None:+ return self._state++ def save_state(self, data: AdobeCommerceResumeConfig) -> None:+ self.saved.append(data)+++def _make_response(status: int, body: Any = None, *, redirect: bool = False, raw: bytes | None = None) -> MagicMock:+ payload = raw if raw is not None else (b"" if body is None else json.dumps(body).encode())+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ response.is_redirect = redirect+ response.is_permanent_redirect = False+ # A fresh iterator per call so the body can be read more than once (error preview, then parse).+ response.iter_content.side_effect = lambda chunk_size=None: iter([payload] if payload else [])+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status} Client Error", response=response) if status >= 400 else None+ )+ return response+++def _request_key(url: str) -> str:+ """`path?sorted-query` — a stable routing key for the fake session."""+ parsed = urlparse(url)+ query = "&".join(f"{k}={v}" for k, v in sorted(parse_qsl(parsed.query)))+ return f"{parsed.path}?{query}" if query else parsed.path+++class _FakeSession:+ def __init__(self, route: Callable[[str], Any] | dict[str, Any]) -> None:+ self._route = route+ self.gets: list[str] = []+ self.posts: list[tuple[str, Any]] = []+ self.post_timeouts: list[Any] = []++ def _resolve(self, url: str) -> Any:+ key = _request_key(url)+ resolved = self._route(key) if callable(self._route) else self._route[key]+ if isinstance(resolved, Exception):+ raise resolved+ return resolved++ def get(self, url: str, **kwargs: Any) -> Any:+ self.gets.append(_request_key(url))+ return self._resolve(url)++ def post(self, url: str, **kwargs: Any) -> Any:+ self.posts.append((_request_key(url), kwargs.get("json")))+ self.post_timeouts.append(kwargs.get("timeout"))+ return self._resolve(url)+++def _install_session(monkeypatch: pytest.MonkeyPatch, session: _FakeSession) -> None:+ monkeypatch.setattr(adobe_commerce, "_make_session", lambda credentials, capture=True, retry=None: session)+ monkeypatch.setattr(adobe_commerce, "_is_host_safe", lambda host, team_id: (True, None))+++class TestNormalizeStoreUrl:+ @parameterized.expand(+ [+ ("bare_host", "store.example.com", "https://store.example.com"),+ ("https", "https://store.example.com", "https://store.example.com"),+ ("trailing_slash", "https://store.example.com/", "https://store.example.com"),+ ("subdirectory_install", "https://example.com/shop", "https://example.com/shop"),+ ("pasted_rest_base", "https://example.com/shop/rest/default/V1", "https://example.com/shop"),+ ("pasted_rest_root", "https://store.example.com/rest", "https://store.example.com"),+ ("explicit_port", "https://store.example.com:8443", "https://store.example.com:8443"),+ ("whitespace", " https://store.example.com ", "https://store.example.com"),+ ]+ )+ def test_accepts_and_cleans_valid_input(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_store_url(raw) == expected++ @parameterized.expand(+ [+ ("http_scheme", "http://store.example.com"),+ ("http_uppercase", "HTTP://store.example.com"),+ ]+ )+ def test_rejects_plaintext_http(self, _name: str, raw: str) -> None:+ # Credentials ride every request, so plaintext transport must be refused with a message+ # that tells the merchant to switch to HTTPS rather than a generic "invalid URL".+ with pytest.raises(ValueError, match="must use HTTPS"):+ normalize_store_url(raw)++ @parameterized.expand(+ [+ ("empty", ""),+ ("whitespace_only", " "),+ ("credentials_in_url", "https://user:[email protected]"),+ ("query_string", "https://store.example.com/?redirect=http://169.254.169.254"),+ ("fragment", "https://store.example.com/#@evil.com"),+ ("traversal", "https://store.example.com/shop/../../etc"),+ ("non_http_scheme", "file:///etc/passwd"),+ ]+ )+ def test_rejects_unsafe_input(self, _name: str, raw: str) -> None:+ # The store URL is where the stored token is sent, so anything that could retarget or+ # smuggle must be rejected before a URL is built.+ with pytest.raises(ValueError):+ normalize_store_url(raw)+++class TestStoreCodeAndBaseUrl:+ @parameterized.expand(+ [+ ("blank", None, ""),+ ("empty_string", "", ""),+ ("default", "default", "default"),+ ("underscored", "us_store_view", "us_store_view"),+ ("slashes_stripped", "/default/", "default"),+ ]+ )+ def test_normalize_store_code(self, _name: str, raw: str | None, expected: str) -> None:+ assert normalize_store_code(raw) == expected++ @parameterized.expand([("path_segment", "de/../all"), ("leading_digit", "1store"), ("dotted", "de.store")])+ def test_normalize_store_code_rejects_path_injection(self, _name: str, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_store_code(raw)++ @parameterized.expand(+ [+ ("no_code", "https://store.example.com", None, "https://store.example.com/rest/V1"),+ ("with_code", "https://store.example.com", "default", "https://store.example.com/rest/default/V1"),+ ("subdirectory", "https://example.com/shop", "all", "https://example.com/shop/rest/all/V1"),+ ]+ )+ def test_base_url(self, _name: str, store_url: str, store_code: str | None, expected: str) -> None:+ assert _base_url(store_url, store_code) == expected+++class TestSearchCriteria:+ def test_full_refresh_sorts_by_primary_key_without_filter(self) -> None:+ params = build_search_criteria(ADOBE_COMMERCE_ENDPOINTS["orders"], page=3)+ assert params["searchCriteria[currentPage]"] == 3+ assert params["searchCriteria[pageSize]"] == ADOBE_COMMERCE_ENDPOINTS["orders"].page_size+ assert params["searchCriteria[sortOrders][0][field]"] == "entity_id"+ assert params["searchCriteria[sortOrders][0][direction]"] == "ASC"+ assert not any("filter_groups" in key for key in params)++ @parameterized.expand(+ [+ ("products", "products", "entity_id"),+ ("categories", "categories", "entity_id"),+ ("customers", "customers", "entity_id"),+ ("carts", "carts", "entity_id"),+ ("orders", "orders", "entity_id"),+ ("transactions", "transactions", "transaction_id"),+ ]+ )+ def test_full_refresh_sorts_on_the_table_column_not_the_response_field(+ self, _name: str, endpoint: str, expected_field: str+ ) -> None:+ # searchCriteria addresses the underlying table column: `/V1/products` returns `id` but+ # rejects a sort on it, so the catalog must carry the column name separately.+ params = build_search_criteria(ADOBE_COMMERCE_ENDPOINTS[endpoint], page=1)+ assert params["searchCriteria[sortOrders][0][field]"] == expected_field++ def test_incremental_sorts_by_cursor_and_filters_gteq(self) -> None:+ params = build_search_criteria(+ ADOBE_COMMERCE_ENDPOINTS["orders"],+ page=1,+ cursor_field="updated_at",+ cursor_value=datetime(2024, 5, 4, 3, 2, 1, tzinfo=UTC),+ )+ assert params["searchCriteria[sortOrders][0][field]"] == "updated_at"+ assert params["searchCriteria[sortOrders][0][direction]"] == "ASC"+ assert params["searchCriteria[filter_groups][0][filters][0][field]"] == "updated_at"+ assert params["searchCriteria[filter_groups][0][filters][0][value]"] == "2024-05-04 03:02:01"+ # `gteq` re-reads the boundary row instead of risking a skip within the same second.+ assert params["searchCriteria[filter_groups][0][filters][0][condition_type]"] == "gteq"++ def test_first_incremental_sync_sorts_by_cursor_without_a_filter(self) -> None:+ params = build_search_criteria(ADOBE_COMMERCE_ENDPOINTS["orders"], page=1, cursor_field="updated_at")+ assert params["searchCriteria[sortOrders][0][field]"] == "updated_at"+ assert not any("filter_groups" in key for key in params)++ @parameterized.expand(+ [+ ("aware_datetime", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02 03:04:05"),+ ("naive_datetime_is_utc", datetime(2024, 1, 2, 3, 4, 5), "2024-01-02 03:04:05"),+ ("date", date(2024, 1, 2), "2024-01-02 00:00:00"),+ ("passthrough_string", "2024-01-02 03:04:05", "2024-01-02 03:04:05"),+ ]+ )+ def test_format_magento_datetime(self, _name: str, value: Any, expected: str) -> None:+ assert _format_magento_datetime(value) == expected++ def test_non_utc_datetime_is_converted(self) -> None:+ value = datetime(2024, 1, 2, 3, 4, 5, tzinfo=ZoneInfo("Europe/Berlin"))+ assert _format_magento_datetime(value) == "2024-01-02 02:04:05"+++class TestTokenManager:+ def test_access_token_is_used_verbatim_without_a_request(self) -> None:+ session = _FakeSession({})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", TOKEN_CREDENTIALS)+ assert manager.get_token() == "tok-123"+ assert session.posts == []++ def test_missing_access_token_is_a_configuration_error(self) -> None:+ manager = AdobeCommerceTokenManager(+ cast(Any, _FakeSession({})),+ "https://s.example.com/rest/V1",+ AdobeCommerceCredentials(method="access_token", access_token=""),+ )+ with pytest.raises(AdobeCommerceConfigurationError):+ manager.get_token()++ def test_admin_token_is_minted_once_and_cached(self) -> None:+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(200, "minted-token")})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ assert manager.get_token() == "minted-token"+ assert manager.get_token() == "minted-token"+ assert len(session.posts) == 1+ assert session.posts[0][1] == {"username": "admin", "password": "hunter2"}++ def test_admin_token_is_reminted_before_it_expires(self, monkeypatch: pytest.MonkeyPatch) -> None:+ clock = {"now": 0.0}+ monkeypatch.setattr(adobe_commerce.time, "monotonic", lambda: clock["now"])+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(200, "minted-token")})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)++ manager.get_token()+ # Still inside the lifetime minus the refresh margin — no re-mint.+ clock["now"] = adobe_commerce.ADMIN_TOKEN_LIFETIME_SECONDS - adobe_commerce.TOKEN_REFRESH_MARGIN_SECONDS - 1+ manager.get_token()+ assert len(session.posts) == 1++ # Inside the margin — the token would expire mid-flight, so it is re-minted first.+ clock["now"] = adobe_commerce.ADMIN_TOKEN_LIFETIME_SECONDS - adobe_commerce.TOKEN_REFRESH_MARGIN_SECONDS + 1+ manager.get_token()+ assert len(session.posts) == 2++ @parameterized.expand([("no_username", None, "pw"), ("no_password", "admin", None)])+ def test_incomplete_admin_credentials_raise_before_any_request(+ self, _name: str, username: str | None, password: str | None+ ) -> None:+ session = _FakeSession({})+ manager = AdobeCommerceTokenManager(+ cast(Any, session),+ "https://s.example.com/rest/V1",+ AdobeCommerceCredentials(method="admin", username=username, password=password),+ )+ with pytest.raises(AdobeCommerceConfigurationError):+ manager.get_token()+ assert session.posts == []++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_transient_token_failures_are_retryable(self, _name: str, status: int) -> None:+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(status)})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ with pytest.raises(AdobeCommerceRetryableError):+ manager.get_token()++ def test_token_redirect_is_refused(self) -> None:+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(302, redirect=True)})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ with pytest.raises(AdobeCommerceHostNotAllowedError):+ manager.get_token()++ @parameterized.expand([("html_login_page", {"message": "nope"}), ("empty_string", "")])+ def test_non_token_body_is_a_configuration_error(self, _name: str, body: Any) -> None:+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(200, body)})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ with pytest.raises(AdobeCommerceConfigurationError):+ manager.get_token()++ def test_oversized_token_body_is_a_configuration_error(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A real token is a short string, so validation caps the token exchange far below a data+ # page. An oversized body must fail permanently rather than buffer on the API worker.+ monkeypatch.setattr(adobe_commerce, "TOKEN_RESPONSE_MAX_BYTES", 8)+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(200, raw=b'"' + b"x" * 64 + b'"')})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ with pytest.raises(AdobeCommerceConfigurationError):+ manager.get_token()++ def test_token_request_timeout_is_bounded_for_inline_validation(self) -> None:+ # The exchange runs inline during validation, so its request timeout must bound the+ # connect/header wait too — not inherit the 120s data timeout a hostile store could stall on.+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(200, "minted-token")})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ manager.get_token()+ assert session.post_timeouts[0] == adobe_commerce.TOKEN_DOWNLOAD_SECONDS++ def test_bad_admin_password_surfaces_as_http_error(self) -> None:+ session = _FakeSession({"/rest/V1/integration/admin/token": _make_response(401, {"message": "bad"})})+ manager = AdobeCommerceTokenManager(cast(Any, session), "https://s.example.com/rest/V1", ADMIN_CREDENTIALS)+ with pytest.raises(requests.HTTPError):+ manager.get_token()+++class TestRequestPage:+ def _manager(self) -> AdobeCommerceTokenManager:+ return AdobeCommerceTokenManager(+ cast(Any, _FakeSession({})), "https://s.example.com/rest/V1", TOKEN_CREDENTIALS+ )++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404), ("server_error", 500)])+ def test_error_statuses_raise_for_status(self, _name: str, status: int) -> None:+ # The tracked session already retried 429/5xx, so anything non-ok reaching here is terminal+ # for this attempt and must surface rather than be swallowed.+ session = _FakeSession({"/rest/V1/orders": _make_response(status, {"message": "no"})})+ with pytest.raises(requests.HTTPError):+ _request_page(cast(Any, session), self._manager(), "https://s.example.com/rest/V1/orders", MagicMock())++ def test_redirect_is_refused(self) -> None:+ session = _FakeSession({"/rest/V1/orders": _make_response(301, redirect=True)})+ with pytest.raises(AdobeCommerceHostNotAllowedError):+ _request_page(cast(Any, session), self._manager(), "https://s.example.com/rest/V1/orders", MagicMock())++ def test_bearer_token_is_sent(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_response(200, {"items": []})+ _request_page(session, self._manager(), "https://s.example.com/rest/V1/orders", MagicMock())+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer tok-123"+++class TestReadCappedJson:+ def test_oversized_body_is_refused(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(adobe_commerce, "MAX_RESPONSE_BYTES", 16)+ response = _make_response(200, raw=b"x" * 64)+ with pytest.raises(AdobeCommerceResponseTooLargeError):+ _read_capped_json(response)+ # The connection is released even when the read is aborted.+ response.close.assert_called()++ def test_body_within_the_cap_parses(self) -> None:+ assert _read_capped_json(_make_response(200, {"items": [{"id": 1}]})) == {"items": [{"id": 1}]}+ assert MAX_RESPONSE_BYTES > 0++ def test_slow_body_is_abandoned_at_the_deadline(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A host that never completes a chunk (dripping bytes under the socket read timeout) must not+ # hold the worker: the read runs on a thread we stop waiting on once the budget expires.+ release = threading.Event()++ def blocking_iter(chunk_size: Any = None) -> Iterator[bytes]:+ release.wait(5) # the deadline fires first; released in the finally below+ yield b'"tok"'++ monkeypatch.setattr(adobe_commerce, "MAX_DOWNLOAD_SECONDS", 0.05)+ response = MagicMock()+ response.iter_content.side_effect = blocking_iter+ try:+ with pytest.raises(AdobeCommerceResponseTooSlowError):+ _read_capped_json(response)+ finally:+ release.set()+ response.close.assert_called()+++def _collect(+ manager: _FakeResumableManager,+ session: _FakeSession,+ monkeypatch: pytest.MonkeyPatch,+ endpoint: str,+ **kwargs: Any,+) -> list[dict[str, Any]]:+ _install_session(monkeypatch, session)+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ store_url="https://store.example.com",+ store_code=None,+ credentials=TOKEN_CREDENTIALS,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++def _page_key(path: str, page: int, size: int, sort_field: str, cursor: str | None = None) -> str:+ params = {+ "searchCriteria[pageSize]": str(size),+ "searchCriteria[currentPage]": str(page),+ "searchCriteria[sortOrders][0][field]": sort_field,+ "searchCriteria[sortOrders][0][direction]": "ASC",+ }+ if cursor is not None:+ params["searchCriteria[filter_groups][0][filters][0][field]"] = sort_field+ params["searchCriteria[filter_groups][0][filters][0][value]"] = cursor+ params["searchCriteria[filter_groups][0][filters][0][condition_type]"] = "gteq"+ query = "&".join(f"{k}={v}" for k, v in sorted(params.items()))+ return f"/rest/V1{path}?{query}"+++class TestGetRows:+ def test_paginates_until_total_count_is_reached(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 2)+ routes = {+ _page_key("/orders", 1, 2, "entity_id"): _make_response(+ 200, {"items": [{"entity_id": 1}, {"entity_id": 2}], "total_count": 4}+ ),+ _page_key("/orders", 2, 2, "entity_id"): _make_response(+ 200, {"items": [{"entity_id": 3}, {"entity_id": 4}], "total_count": 4}+ ),+ }+ session = _FakeSession(routes)+ manager = _FakeResumableManager()+ rows = _collect(manager, session, monkeypatch, "orders")++ assert [r["entity_id"] for r in rows] == [1, 2, 3, 4]+ # Page 3 is never requested: total_count says the collection is exhausted.+ assert len(session.gets) == 2+ assert [s.current_page for s in manager.saved] == [2]++ def test_short_page_terminates_when_total_count_is_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 2)+ routes = {+ _page_key("/orders", 1, 2, "entity_id"): _make_response(200, {"items": [{"entity_id": 1}]}),+ }+ rows = _collect(_FakeResumableManager(), _FakeSession(routes), monkeypatch, "orders")+ assert [r["entity_id"] for r in rows] == [1]++ def test_empty_first_page_yields_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 2)+ routes = {_page_key("/orders", 1, 2, "entity_id"): _make_response(200, {"items": [], "total_count": 0})}+ manager = _FakeResumableManager()+ assert _collect(manager, _FakeSession(routes), monkeypatch, "orders") == []+ assert manager.saved == []++ def test_state_is_saved_after_each_yielded_page_and_resume_skips_it(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 1)+ routes = {+ _page_key("/orders", 2, 1, "entity_id"): _make_response(+ 200, {"items": [{"entity_id": 2}], "total_count": 3}+ ),+ _page_key("/orders", 3, 1, "entity_id"): _make_response(+ 200, {"items": [{"entity_id": 3}], "total_count": 3}+ ),+ }+ session = _FakeSession(routes)+ manager = _FakeResumableManager(AdobeCommerceResumeConfig(current_page=2))+ rows = _collect(manager, session, monkeypatch, "orders")++ # Page 1 is never re-fetched; the run picks up exactly where the saved state points.+ assert [r["entity_id"] for r in rows] == [2, 3]+ assert [s.current_page for s in manager.saved] == [3]++ def test_incremental_run_sends_the_server_side_filter(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 2)+ key = _page_key("/orders", 1, 2, "updated_at", cursor="2024-05-04 03:02:01")+ session = _FakeSession({key: _make_response(200, {"items": [{"entity_id": 9}], "total_count": 1})})+ rows = _collect(+ _FakeResumableManager(),+ session,+ monkeypatch,+ "orders",+ should_use_incremental_field=True,+ incremental_field_name="updated_at",+ db_incremental_field_last_value=datetime(2024, 5, 4, 3, 2, 1, tzinfo=UTC),+ )+ assert [r["entity_id"] for r in rows] == [9]+ assert session.gets == [key]++ def test_incremental_falls_back_to_the_endpoint_cursor_when_none_is_chosen(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["transactions"], "page_size", 2)+ key = _page_key("/transactions", 1, 2, "created_at", cursor="2024-01-01 00:00:00")+ session = _FakeSession({key: _make_response(200, {"items": [{"transaction_id": 1}], "total_count": 1})})+ _collect(+ _FakeResumableManager(),+ session,+ monkeypatch,+ "transactions",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01 00:00:00",+ )+ assert session.gets == [key]++ def test_reference_endpoint_fetches_a_bare_array_once(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({"/rest/V1/store/storeViews": _make_response(200, [{"id": 1}, {"id": 2}])})+ manager = _FakeResumableManager()+ rows = _collect(manager, session, monkeypatch, "store_views")+ assert rows == [{"id": 1}, {"id": 2}]+ # No searchCriteria, one request, nothing to resume from.+ assert session.gets == ["/rest/V1/store/storeViews"]+ assert manager.saved == []++ def test_unexpected_payload_is_retryable(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({"/rest/V1/store/storeViews": _make_response(200, "surprise")})+ with pytest.raises(AdobeCommerceRetryableError):+ _collect(_FakeResumableManager(), session, monkeypatch, "store_views")++ def test_pagination_is_bounded(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A server that returns a full page forever with an inflated total_count would otherwise+ # loop until the activity times out.+ monkeypatch.setattr(adobe_commerce, "MAX_PAGES", 2)+ monkeypatch.setattr(ADOBE_COMMERCE_ENDPOINTS["orders"], "page_size", 1)+ session = _FakeSession(+ lambda key: _make_response(200, {"items": [{"entity_id": 1}], "total_count": 10_000_000})+ )+ with pytest.raises(AdobeCommercePaginationLimitError):+ _collect(_FakeResumableManager(), session, monkeypatch, "orders")++ def test_pagination_wall_clock_is_bounded(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A store that dribbles full pages without `total_count` stays under MAX_PAGES but would run+ # to the activity timeout, so the loop's wall-clock budget must stop it independently.+ clock = {"now": 0.0}++ def fake_monotonic() -> float:+ clock["now"] += 1.0+ return clock["now"]++ monkeypatch.setattr(adobe_commerce.time, "monotonic", fake_monotonic)+ monkeypatch.setattr(adobe_commerce, "MAX_PAGINATION_SECONDS", 0)+ session = _FakeSession(lambda key: _make_response(200, {"items": [{"entity_id": 1}]}))+ with pytest.raises(AdobeCommercePaginationLimitError):+ _collect(_FakeResumableManager(), session, monkeypatch, "orders")++ def test_internal_host_is_refused_at_sync_time(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({})+ monkeypatch.setattr(adobe_commerce, "_make_session", lambda credentials, capture=True, retry=None: session)+ monkeypatch.setattr(adobe_commerce, "_is_host_safe", lambda host, team_id: (False, "internal address"))+ with pytest.raises(AdobeCommerceHostNotAllowedError):+ list(+ get_rows(+ store_url="https://store.example.com",+ store_code=None,+ credentials=TOKEN_CREDENTIALS,+ endpoint="orders",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(),+ )+ )+ assert session.gets == []+++class TestValidateCredentials:+ def _routes_all(self, response_factory: Callable[[], Any]) -> Callable[[str], Any]:+ return lambda key: response_factory()++ def test_first_reachable_probe_endpoint_passes(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # Magento answers an unauthorized *resource* with a 401, so a narrowly-scoped integration+ # must still connect as long as one of the probe endpoints is readable.+ def route(key: str) -> Any:+ if key.startswith("/rest/V1/customers/search"):+ return _make_response(200, {"items": [], "total_count": 0})+ return _make_response(401, {"message": "denied"})++ session = _FakeSession(route)+ _install_session(monkeypatch, session)+ assert validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1) == (True, None)+ assert len(session.gets) == 3++ def test_all_probes_unauthorized_reports_credentials(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(401, {"message": "denied"})))+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message is not None and "standalone Bearer tokens" in message+ assert len(session.gets) == len(VALIDATION_PROBE_ENDPOINTS)++ def test_not_a_magento_rest_api_reports_the_url(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(404)))+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message == "No Adobe Commerce REST API found at that store URL. Check the URL and store code."++ def test_connection_failure_is_reported(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: requests.ConnectionError("boom")))+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message is not None and "boom" in message+ # A transport failure means the host is unreachable, so the probe loop must stop rather than+ # pay a full timeout on each remaining endpoint and tie up the worker for minutes.+ assert len(session.gets) == 1++ def test_scoped_probe_targets_only_that_schema(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(200, {"items": [], "total_count": 0})))+ _install_session(monkeypatch, session)+ assert validate_credentials(+ "https://store.example.com", None, TOKEN_CREDENTIALS, schema_name="products", team_id=1+ ) == (True, None)+ assert len(session.gets) == 1+ assert session.gets[0].startswith("/rest/V1/products?")++ def test_probe_requests_a_single_row(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(200, {"items": [], "total_count": 0})))+ _install_session(monkeypatch, session)+ validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, schema_name="orders", team_id=1)+ assert "searchCriteria[pageSize]=1" in session.gets[0]++ def test_validation_disables_transport_retries(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # Validation runs inline on the API thread, so its session must opt out of the retrying+ # policy — otherwise a store answering 429/503 with a large Retry-After stalls the worker+ # across retry sleeps that the request timeout doesn't bound.+ captured: dict[str, Any] = {}+ session = _FakeSession(self._routes_all(lambda: _make_response(200, {"items": [], "total_count": 0})))++ def fake_make_session(credentials: Any, capture: bool = True, retry: Any = None) -> Any:+ captured["retry"] = retry+ return session++ monkeypatch.setattr(adobe_commerce, "_make_session", fake_make_session)+ monkeypatch.setattr(adobe_commerce, "_is_host_safe", lambda host, team_id: (True, None))+ validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1)+ assert captured["retry"] is not None and captured["retry"].total == 0++ def test_bad_admin_password_is_reported_before_any_probe(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(401, {"message": "bad"})))+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("https://store.example.com", None, ADMIN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message == "Adobe Commerce rejected the admin username and password."+ assert session.gets == []++ def test_invalid_store_url_fails_without_network(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({})+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message is not None+ assert session.gets == [] and session.posts == []++ def test_internal_host_is_refused(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({})+ monkeypatch.setattr(adobe_commerce, "_make_session", lambda credentials, capture=True, retry=None: session)+ monkeypatch.setattr(adobe_commerce, "_is_host_safe", lambda host, team_id: (False, "internal address"))+ valid, message = validate_credentials("https://internal.local", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message == "internal address"+ assert session.gets == []++ def test_redirect_probe_is_refused(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession(self._routes_all(lambda: _make_response(302, redirect=True)))+ _install_session(monkeypatch, session)+ valid, message = validate_credentials("https://store.example.com", None, TOKEN_CREDENTIALS, team_id=1)+ assert valid is False+ assert message == HOST_NOT_ALLOWED_ERROR+++class TestSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = adobe_commerce_source(+ store_url="https://store.example.com",+ store_code=None,+ credentials=TOKEN_CREDENTIALS,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ADOBE_COMMERCE_ENDPOINTS[endpoint].primary_keys+ # Every request asks Magento for an ascending sort, so the watermark can checkpoint per batch.+ assert response.sort_mode == "asc"++ def test_items_is_lazy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ session = _FakeSession({"/rest/V1/store/storeViews": _make_response(200, [{"id": 1}])})+ _install_session(monkeypatch, session)+ response = adobe_commerce_source(+ store_url="https://store.example.com",+ store_code=None,+ credentials=TOKEN_CREDENTIALS,+ endpoint="store_views",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(),+ )+ # Building the response must not touch the network — the pipeline decides when to iterate.+ assert session.gets == []+ batches = cast("Iterable[Any]", response.items())+ assert list(cast(Iterator[Any], iter(batches))) == [[{"id": 1}]]++ def test_primary_keys_are_unique_per_endpoint(self) -> None:+ for name, config in ADOBE_COMMERCE_ENDPOINTS.items():+ assert config.primary_keys, f"{name} has no primary key"+ assert len(set(config.primary_keys)) == len(config.primary_keys)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce_source.pynew file mode 100644index 000000000000..35e20670332f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/tests/test_adobe_commerce_source.py@@ -0,0 +1,247 @@+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.adobe_commerce import (+ AdobeCommerceResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.settings import (+ ADOBE_COMMERCE_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.source import AdobeCommerceSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adobecommerce import (+ AdobeCommerceAuthMethodConfig,+ AdobeCommerceSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adobe_commerce.source"++INCREMENTAL_ENDPOINTS = (+ "orders",+ "invoices",+ "shipments",+ "creditmemos",+ "transactions",+ "products",+ "categories",+ "customers",+ "carts",+ "coupons",+)+FULL_REFRESH_ENDPOINTS = (+ "customer_groups",+ "product_attributes",+ "tax_classes",+ "store_views",+ "store_groups",+ "websites",+ "countries",+)+++def _token_config(store_code: str | None = None) -> AdobeCommerceSourceConfig:+ return AdobeCommerceSourceConfig(+ store_url="https://store.example.com",+ store_code=store_code,+ auth_method=AdobeCommerceAuthMethodConfig(selection="access_token", access_token="tok-123"),+ )+++def _admin_config() -> AdobeCommerceSourceConfig:+ return AdobeCommerceSourceConfig(+ store_url="https://store.example.com",+ store_code="default",+ auth_method=AdobeCommerceAuthMethodConfig(selection="admin", username="admin", password="hunter2"),+ )+++class TestAdobeCommerceSource:+ def setup_method(self) -> None:+ self.source = AdobeCommerceSource()+ self.team_id = 123+ self.config = _token_config()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ADOBECOMMERCE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "AdobeCommerce"+ assert config.label == "Adobe Commerce (Magento)"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source must be visible in the wizard.+ assert config.unreleasedSource is None or config.unreleasedSource is False+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/adobe-commerce"++ field_names = [f.name for f in config.fields]+ assert field_names == ["store_url", "store_code", "auth_method"]++ def test_secret_fields_are_password_inputs(self) -> None:+ config = self.source.get_source_config+ auth = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ secrets = {+ field.name: field+ for option in auth.options+ for field in (option.fields or [])+ if isinstance(field, SourceFieldInputConfig)+ }+ assert secrets["access_token"].secret is True+ assert secrets["password"].secret is True+ assert secrets["username"].secret is False++ def test_store_url_is_a_connection_host_field(self) -> None:+ # The token/password is sent to `store_url`, so retargeting it must force a re-entry.+ assert self.source.connection_host_fields == ["store_url"]++ def test_lists_tables_without_credentials(self) -> None:+ # `get_schemas` is a static catalog walk with no I/O, so public docs can render the tables.+ assert self.source.lists_tables_without_credentials is True++ def test_api_docs_url_is_https(self) -> None:+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand([(endpoint,) for endpoint in INCREMENTAL_ENDPOINTS])+ def test_endpoints_with_a_server_side_timestamp_filter_are_incremental(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is True+ # Sales and catalog rows are rewritten in place, so append would duplicate them.+ assert schema.supports_append is False+ assert [f["field"] for f in schema.incremental_fields] == [+ ADOBE_COMMERCE_ENDPOINTS[endpoint].incremental_field_name+ ]++ @parameterized.expand([(endpoint,) for endpoint in FULL_REFRESH_ENDPOINTS])+ def test_endpoints_without_timestamps_are_full_refresh(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])+ assert [s.name for s in schemas] == ["orders"]++ 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)+ orders = next(t for t in tables if t["name"] == "orders")+ assert "Incremental" in orders["sync_methods"]+ assert orders["description"]++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ for name, entry in descriptions.items():+ # Every documented table must at least describe its primary key columns.+ assert entry.get("columns"), name+ for key in ADOBE_COMMERCE_ENDPOINTS[name].primary_keys:+ assert key in entry["columns"], f"{name}.{key}"++ def test_incremental_fields_map_matches_the_endpoint_catalog(self) -> None:+ assert set(INCREMENTAL_FIELDS) == set(INCREMENTAL_ENDPOINTS)++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://store.example.com/rest/V1/orders"),+ ("forbidden", "403 Client Error: Forbidden for url: https://other.example.com/rest/V1/products"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://store.example.com/rest/V1/orders",+ ),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://store.example.com/rest/V1/orders"),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ assert not any(key in unrelated_error for key in self.source.get_non_retryable_errors())++ @mock.patch(f"{_MODULE}.validate_adobe_commerce_credentials")+ def test_validate_credentials_passes_the_access_token(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ kwargs = mock_validate.call_args.kwargs+ assert kwargs["store_url"] == "https://store.example.com"+ assert kwargs["store_code"] is None+ assert kwargs["credentials"].method == "access_token"+ assert kwargs["credentials"].access_token == "tok-123"+ assert kwargs["schema_name"] is None+ assert kwargs["team_id"] == self.team_id++ @mock.patch(f"{_MODULE}.validate_adobe_commerce_credentials")+ def test_validate_credentials_passes_the_admin_login(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ self.source.validate_credentials(_admin_config(), self.team_id, schema_name="orders")++ kwargs = mock_validate.call_args.kwargs+ assert kwargs["store_code"] == "default"+ assert kwargs["credentials"].method == "admin"+ assert (kwargs["credentials"].username, kwargs["credentials"].password) == ("admin", "hunter2")+ assert kwargs["schema_name"] == "orders"++ 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 AdobeCommerceResumeConfig++ @mock.patch(f"{_MODULE}.adobe_commerce_source")+ def test_source_for_pipeline_plumbs_incremental_inputs(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "updated_at"+ inputs.db_incremental_field_last_value = "2024-05-04 03:02:01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["endpoint"] == "orders"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ # The user's chosen cursor from schema settings wins over the endpoint default.+ assert kwargs["incremental_field_name"] == "updated_at"+ assert kwargs["db_incremental_field_last_value"] == "2024-05-04 03:02:01"++ @mock.patch(f"{_MODULE}.adobe_commerce_source")+ def test_source_for_pipeline_drops_the_watermark_on_a_full_refresh(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "products"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-05-04 03:02:01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs: Any = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobecommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobecommerce.pyindex e5a3fd85d706..97b32666dbef 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobecommerce.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobecommerce.py@@ -1,9 +1,21 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class AdobeCommerceAuthMethodConfig(config.Config):+ selection: Literal["access_token", "admin"] = "access_token"+ access_token: str | None = None+ username: str | None = None+ password: str | None = None++@config.configclass AdobeCommerceSourceConfig(config.Config):- pass+ store_url: str+ auth_method: AdobeCommerceAuthMethodConfig+ store_code: str | None = None