: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 medusa import source (#107254)
Tom Owers23a03240e192
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b8c2e7222d62..5bb43941b9c2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -454,6 +454,7 @@ the row lists both.| marketstack | HTTP | requests | ✅ || matomo | HTTP | requests | ✅ || maxio | HTTP | requests + `rest_source.RESTClient` | ✅ |+| medusa | HTTP | requests + `rest_source.RESTClient` | ✅ || mention | HTTP | requests | ✅ || mercury | HTTP | requests + `rest_source.RESTClient` | ✅ || meta_ads | HTTP | requests | ✅ |@@ -1180,7 +1181,6 @@ doesn't conflict with concurrent PRs.- mantle- manychat- mastodon-- medusa- meetup- memberful- membraindiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/medusa.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/medusa.pyindex 24a37aa8b589..a811ed0fc7b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/medusa.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/medusa.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MedusaSourceConfig(config.Config):- pass+ base_url: str+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/canonical_descriptions.pynew file mode 100644index 000000000000..6e1fb4d2a383--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/canonical_descriptions.py@@ -0,0 +1,135 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions from the Medusa v2 Admin API reference (https://docs.medusajs.com/api/admin).+# Keyed by the endpoint names in settings.MEDUSA_ENDPOINTS.++_TIMESTAMPS = {+ "created_at": "Date the record was created.",+ "updated_at": "Date the record was last updated.",+ "deleted_at": "Date the record was soft-deleted, if it was.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Orders": {+ "description": "A purchase placed in the store, with its items, totals, and fulfillment and payment status.",+ "docs_url": "https://docs.medusajs.com/api/admin#orders",+ "columns": {+ "id": "Unique identifier of the order.",+ "display_id": "Human-readable incrementing order number shown in the admin.",+ "status": "Status of the order, such as pending, completed, or canceled.",+ "email": "Email address associated with the order.",+ "currency_code": "Three-letter ISO currency code of the order.",+ "total": "Total amount of the order, including taxes and shipping.",+ "subtotal": "Order subtotal before taxes and shipping.",+ "tax_total": "Total tax amount on the order.",+ "customer_id": "ID of the customer who placed the order.",+ "region_id": "ID of the region the order was placed in.",+ "sales_channel_id": "ID of the sales channel the order was placed through.",+ **_TIMESTAMPS,+ },+ },+ "DraftOrders": {+ "description": "An order created manually in the admin that has not been completed by a customer.",+ "docs_url": "https://docs.medusajs.com/api/admin#draft-orders",+ "columns": {+ "id": "Unique identifier of the draft order.",+ "display_id": "Human-readable incrementing number of the draft order.",+ "status": "Status of the draft order.",+ "email": "Email address associated with the draft order.",+ "currency_code": "Three-letter ISO currency code of the draft order.",+ "customer_id": "ID of the customer the draft order is for.",+ **_TIMESTAMPS,+ },+ },+ "Products": {+ "description": "A product in the store's catalog, with its options, images, and organization metadata.",+ "docs_url": "https://docs.medusajs.com/api/admin#products",+ "columns": {+ "id": "Unique identifier of the product.",+ "title": "Title of the product.",+ "handle": "URL slug of the product, unique across the store.",+ "status": "Status of the product: draft, proposed, published, or rejected.",+ "description": "Description of the product.",+ "collection_id": "ID of the collection the product belongs to.",+ "type_id": "ID of the product's type.",+ "is_giftcard": "Whether the product is a gift card.",+ **_TIMESTAMPS,+ },+ },+ "ProductVariants": {+ "description": "A purchasable variant of a product, such as a specific size or color, with its own SKU and inventory settings.",+ "docs_url": "https://docs.medusajs.com/api/admin#product-variants",+ "columns": {+ "id": "Unique identifier of the variant.",+ "title": "Title of the variant.",+ "sku": "Stock keeping unit of the variant.",+ "barcode": "Barcode of the variant.",+ "product_id": "ID of the product the variant belongs to.",+ "allow_backorder": "Whether the variant can be ordered while out of stock.",+ "manage_inventory": "Whether Medusa tracks inventory for the variant.",+ **_TIMESTAMPS,+ },+ },+ "Customers": {+ "description": "A customer of the store, registered or created from a guest checkout.",+ "docs_url": "https://docs.medusajs.com/api/admin#customers",+ "columns": {+ "id": "Unique identifier of the customer.",+ "email": "Email address of the customer.",+ "first_name": "First name of the customer.",+ "last_name": "Last name of the customer.",+ "phone": "Phone number of the customer.",+ "company_name": "Company name of the customer.",+ "has_account": "Whether the customer registered an account, rather than checking out as a guest.",+ **_TIMESTAMPS,+ },+ },+ "CustomerGroups": {+ "description": "A named group of customers, used to target promotions and price lists.",+ "docs_url": "https://docs.medusajs.com/api/admin#customer-groups",+ "columns": {+ "id": "Unique identifier of the customer group.",+ "name": "Name of the customer group.",+ **_TIMESTAMPS,+ },+ },+ "Regions": {+ "description": "A region the store sells in, defining its currency and countries.",+ "docs_url": "https://docs.medusajs.com/api/admin#regions",+ "columns": {+ "id": "Unique identifier of the region.",+ "name": "Name of the region.",+ "currency_code": "Three-letter ISO currency code used in the region.",+ "automatic_taxes": "Whether taxes are calculated automatically in the region.",+ **_TIMESTAMPS,+ },+ },+ "PriceLists": {+ "description": "A set of prices that override default prices, for a sale or an override scoped to customer groups.",+ "docs_url": "https://docs.medusajs.com/api/admin#price-lists",+ "columns": {+ "id": "Unique identifier of the price list.",+ "title": "Title of the price list.",+ "description": "Description of the price list.",+ "status": "Status of the price list: active or draft.",+ "type": "Type of the price list: sale or override.",+ "starts_at": "Date the price list becomes active.",+ "ends_at": "Date the price list stops being active.",+ **_TIMESTAMPS,+ },+ },+ "Returns": {+ "description": "A return of one or more items from an order.",+ "docs_url": "https://docs.medusajs.com/api/admin#returns",+ "columns": {+ "id": "Unique identifier of the return.",+ "order_id": "ID of the order the items are returned from.",+ "status": "Status of the return.",+ "refund_amount": "Amount refunded for the return.",+ "received_at": "Date the returned items were received.",+ **_TIMESTAMPS,+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/medusa.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/medusa.pynew file mode 100644index 000000000000..03eaf71c0ce0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/medusa.py@@ -0,0 +1,339 @@+import threading+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from requests import PreparedRequest, Response+from requests.auth import HTTPBasicAuth++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import _NoRedirectSession+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.settings import (+ CONNECT_TIMEOUT_SECONDS,+ MAX_RESPONSE_BYTES,+ MAX_ROWS_PER_SYNC,+ MEDUSA_ENDPOINTS,+ PAGE_SIZE,+ PARTITION_KEY,+ PRIMARY_KEYS,+ READ_DEADLINE_SECONDS,+ READ_TIMEOUT_SECONDS,+ REQUEST_TIMEOUT_SECONDS,+ RESPONSE_READ_CHUNK_BYTES,+ MedusaEndpointConfig,+)++HTTPS_REQUIRED_ERROR = "Medusa server URL must use HTTPS"+INVALID_URL_ERROR = "Invalid Medusa server URL"+PAGINATION_LIMIT_ERROR = "Medusa pagination did not terminate"+++@frozen+class MedusaResumeConfig:+ # Opaque framework checkpoint: the offset paginator's next position. Round-tripped into+ # `initial_paginator_state` on resume.+ paginator_state: dict[str, Any]+++def normalize_base_url(base_url: Optional[str]) -> str:+ """Normalize the server URL and reject anything that isn't HTTPS.++ The secret API key travels in an Authorization header to a user-supplied host, so+ plaintext http:// is rejected to keep it off the wire in the clear. Bare hosts default+ to https. A subpath is kept because Medusa is sometimes served behind a reverse proxy+ under a path prefix.+ """+ host = (base_url or "").strip()+ if not host:+ raise ValueError(f"{INVALID_URL_ERROR}: enter your server's URL, e.g. https://store.example.com")+ if host.lower().startswith("http://"):+ raise ValueError(HTTPS_REQUIRED_ERROR)+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ # Reject characters that make urlparse (which the SSRF host check trusts) and the HTTP+ # client disagree on the target host; a backslash or an encoded authority delimiter is+ # the wedge, so refuse them outright.+ lowered = host.lower()+ if "\\" in host or "%5c" in lowered or "%40" in lowered:+ raise ValueError(f"{INVALID_URL_ERROR}: {host}")+ try:+ parsed = urlparse(host)+ port = parsed.port+ except ValueError:+ raise ValueError(f"{INVALID_URL_ERROR}: {host}")+ if parsed.scheme != "https" or not parsed.hostname:+ raise ValueError(f"{INVALID_URL_ERROR} (must be https): {host}")+ # Credentials in the authority (user:pass@host) would ship the API key to `host` while+ # the safety check could be aimed elsewhere; require the authority to be exactly+ # host[:port].+ host_part = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname+ expected_netloc = host_part + (f":{port}" if port else "")+ if parsed.netloc.lower() != expected_netloc.lower():+ raise ValueError(f"{INVALID_URL_ERROR}: {host}")+ return host+++def hostname_of(base_url: Optional[str]) -> str:+ return urlparse(normalize_base_url(base_url)).hostname or ""+++class _BoundedSession(_NoRedirectSession):+ """No-redirect session that also bounds each request on time and response size.++ The base URL is user-supplied, so a hostile host could accept the connection and then+ stall the response or return an arbitrarily large / highly compressed body (``requests``+ buffers and decodes it eagerly before returning) to exhaust a worker. Pin a connect/read+ timeout when the caller supplies none, and stream the body under a hard per-response+ byte cap.+ """++ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:+ # `requests.Session.request` and `RESTClient` both pass an explicit `timeout` kwarg+ # (None when the caller set none), so a plain setdefault would never fire.+ if kwargs.get("timeout") is None:+ kwargs["timeout"] = (CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS)+ kwargs["stream"] = True+ response = super().send(request, **kwargs)+ try:+ body = _read_capped(response)+ finally:+ response.close()+ response._content = body+ response._content_consumed = True # type: ignore[attr-defined]+ return response+++def _read_capped(response: Response) -> bytes:+ """Buffer the body under both a size cap and a hard wall-clock deadline.++ READ_TIMEOUT_SECONDS is only a socket-inactivity timeout, so a host that drips a byte+ before each idle window keeps the read blocked indefinitely while staying under the byte+ cap. Read on a daemon thread and abandon it past READ_DEADLINE_SECONDS, closing the+ response to unblock the socket, so a slow-drip host can't monopolize a worker.+ """+ result: dict[str, Any] = {}++ def drain() -> None:+ try:+ result["body"] = _stream_under_cap(response)+ except BaseException as exc: # noqa: BLE001 — surfaced to the caller after the join below+ result["error"] = exc++ thread = threading.Thread(target=drain, daemon=True)+ thread.start()+ thread.join(READ_DEADLINE_SECONDS)+ if thread.is_alive():+ # Closing the response unblocks the raw read so the abandoned daemon thread can exit.+ response.close()+ raise ValueError(f"Medusa response body was not fully delivered within {READ_DEADLINE_SECONDS}s")+ if "error" in result:+ raise result["error"]+ return result.get("body", b"")+++def _stream_under_cap(response: Response) -> bytes:+ # Stream *decoded* chunks and abort the instant the running total crosses the cap. A+ # single read(decode_content=True) would inflate the whole compressed body at once, so a+ # bomb is bounded only by decoding incrementally and stopping early.+ chunks: list[bytes] = []+ decoded = 0+ for chunk in response.raw.stream(RESPONSE_READ_CHUNK_BYTES, decode_content=True):+ decoded += len(chunk)+ if decoded > MAX_RESPONSE_BYTES:+ raise ValueError(f"Medusa response body exceeded the {MAX_RESPONSE_BYTES}-byte limit")+ chunks.append(chunk)+ return b"".join(chunks)+++def _bounded_session(api_key: str) -> requests.Session:+ """A tracked, no-redirect, time- and size-bounded session for Medusa's user-supplied host.++ No-redirect is an SSRF boundary: a user-supplied base URL must not be able to bounce API+ calls (and the Authorization header) to another host via a 3xx. The bounds keep a hostile+ host from stalling a request or returning an unbounded body. The key is registered for+ value-based log redaction.+ """+ session = _BoundedSession()+ adapter = make_tracked_adapter(redact_values=(api_key,))+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ session.headers.update({"Accept": "application/json"})+ return session+++def validate_credentials(base_url: Optional[str], api_key: str) -> tuple[bool, int | None]:+ """Confirm the secret API key is genuine with one cheap list call.++ Medusa v2 authenticates secret API keys with HTTP Basic: the key is the username, the+ password is empty (the `api_token` security scheme in the Admin API spec).+ """+ base = normalize_base_url(base_url)+ return validate_via_probe(+ lambda: _bounded_session(api_key),+ f"{base}/admin/regions?limit=1",+ auth=HTTPBasicAuth(api_key, ""),+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+++def _to_iso8601(value: Any) -> Optional[str]:+ """Medusa's timestamp filters compare against timestamptz columns; send a UTC instant."""+ moment = parse_datetime_value(value)+ if moment is None:+ return None+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")+++class MedusaPaginator(OffsetPaginator):+ """Offset paginator that stops on a short or empty page, with a hard row budget.++ `total_path` stays None: the short-page rule already terminates, and reading `count`+ would re-parse every page body just to stop one request earlier. The host is+ user-supplied, so a server that keeps returning full pages forever must not be able to+ keep a resumable import issuing requests until its activity timeout; past the budget the+ sync fails loudly instead of completing on a sliver. The budget rides `offset`, which is+ part of the framework's persisted resume state.+ """++ def __init__(self) -> None:+ super().__init__(limit=PAGE_SIZE, total_path=None)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if self._has_next_page and self.offset >= MAX_ROWS_PER_SYNC:+ raise ValueError(f"{PAGINATION_LIMIT_ERROR}: exceeded {MAX_ROWS_PER_SYNC} rows in one sync")+++def get_resource(+ config: MedusaEndpointConfig,+ should_use_incremental_field: bool,+ incremental_field_name: Optional[str] = None,+) -> EndpointResource:+ cursor_field: str = "created_at"+ if should_use_incremental_field:+ if config.incremental_field_name is None:+ raise ValueError(f"Medusa endpoint '{config.name}' does not support incremental sync")+ if incremental_field_name is not None and incremental_field_name != config.incremental_field_name:+ raise ValueError(f"Medusa endpoint '{config.name}' has no incremental field '{incremental_field_name}'")+ cursor_field = config.incremental_field_name++ endpoint: Endpoint = {+ "path": f"/admin{config.path}",+ "params": {+ # Explicit ascending sort: it keeps offset page boundaries stable while rows are+ # inserted mid-sync, and on incremental runs it matches sort_mode="asc" so the+ # watermark checkpoints correctly. `created_at` is immutable, so a full refresh+ # sorts on it; incremental runs sort on the cursor field itself.+ "order": cursor_field,+ },+ "paginator": MedusaPaginator(),+ "data_selector": config.data_selector,+ }++ if should_use_incremental_field:+ # Medusa parses nested query operators with `qs`, which accepts the percent-encoded+ # brackets `requests` produces for a literal `updated_at[$gte]=...` param. `$gte` is+ # inclusive, so the boundary row is re-read on each run; the merge dedupes it on `id`.+ incremental: IncrementalConfig = {+ "start_param": f"{cursor_field}[$gte]",+ "cursor_path": cursor_field,+ "convert": _to_iso8601,+ }+ endpoint["incremental"] = incremental++ return {+ "name": config.name,+ "table_name": config.name.lower(),+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def medusa_source(+ base_url: str,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[MedusaResumeConfig],+ should_use_incremental_field: bool = False,+ incremental_field_name: Optional[str] = None,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ base = normalize_base_url(base_url)+ config = MEDUSA_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base,+ # The framework auth builds the Basic header and redacts the key from logs and+ # raised errors.+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ # The key rides in the Authorization header to a user-supplied host: pin every+ # request to that host, reject redirects off it, and bound each response in time+ # and size via the session.+ "session": _bounded_session(api_key),+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": (CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS),+ },+ "resources": [get_resource(config, should_use_incremental_field, incremental_field_name)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup+ # on completion. Saved after a page is yielded, so a crash re-fetches from the next+ # position and never skips a page (a re-fetched page is deduped by the merge).+ if state:+ resumable_source_manager.save_state(MedusaResumeConfig(paginator_state=dict(state)))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(PRIMARY_KEYS),+ column_hints=resource.column_hints,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[PARTITION_KEY],+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/settings.pynew file mode 100644index 000000000000..d75580271312--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/settings.py@@ -0,0 +1,92 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Medusa's list routes default `limit` to 20-50 and document no hard maximum; 100 keeps pages+# moderate for wide rows (orders carry items, addresses and totals inline).+PAGE_SIZE = 100++# Medusa ids are globally unique prefixed identifiers (`order_...`, `prod_...`), so `id` alone+# is unique table-wide on every endpoint below.+PRIMARY_KEYS = ("id",)++# Every Medusa entity carries an immutable `created_at`, which makes it a stable partition key+# (`updated_at` changes on every write and would rewrite partitions each sync).+PARTITION_KEY = "created_at"++REQUEST_TIMEOUT_SECONDS = 30.0++# Split connect/read timeouts for the sync path, threaded through the client's+# `request_timeout` (with a session-level fallback): without them a user-controlled host+# could accept the connection and then leave a response unfinished, occupying an import+# worker until the resumable activity's week-long timeout.+CONNECT_TIMEOUT_SECONDS = 10.0+READ_TIMEOUT_SECONDS = 60.0++# Hard wall-clock ceiling on delivering a single response body. READ_TIMEOUT_SECONDS is only a+# socket-inactivity timeout: a host that drips a byte before each idle window keeps the read+# blocked indefinitely while staying under the byte cap. The body is read on a daemon thread+# that is abandoned past this deadline (closing the response to unblock the socket).+READ_DEADLINE_SECONDS = 180.0++# Hard per-response cap on decoded body bytes. `requests` buffers and decodes the whole body+# before returning, so a hostile host could return an arbitrarily large or highly compressed+# page and exhaust a worker's memory. The body is streamed and decoded incrementally under+# this ceiling. Sized well above a legitimate 100-row page of wide order rows.+MAX_RESPONSE_BYTES = 100 * 1024 * 1024+# Compressed bytes pulled per streamed read while enforcing the cap; small so a decompression+# bomb can inflate at most one chunk's worth past the cap before the read aborts.+RESPONSE_READ_CHUNK_BYTES = 64 * 1024++# Coarse backstop on rows fetched into one table in one sync run, far above any realistic+# store. Stops a host that keeps returning full pages forever from holding a resumable+# import until its activity timeout.+MAX_ROWS_PER_SYNC = 100_000_000+++@frozen+class MedusaEndpointConfig:+ name: str+ # Path below the `/admin` prefix.+ path: str+ # Key the rows live under in Medusa's `{<key>: [...], "count": N, "offset": M, "limit": L}`+ # list envelope. Usually the snake_case resource name, but not always (`/admin/product-variants`+ # returns `variants`).+ data_selector: str+ # Server-side timestamp column used for the `[$gte]` filter and the ascending sort on+ # incremental runs. None means the list route documents no timestamp filters, so the+ # endpoint is full refresh only.+ incremental_field_name: str | None = "updated_at"++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if self.incremental_field_name is None:+ return []+ return [incremental_field(self.incremental_field_name)]+++# Medusa v2 Admin API list routes. Every entry is a documented list route on a stock v2 server;+# all carry `created_at`/`updated_at` operator filters except price lists, whose list route+# documents no timestamp filters. Fulfillments have no list route in v2, so they are absent.+MEDUSA_ENDPOINTS: dict[str, MedusaEndpointConfig] = {+ "Orders": MedusaEndpointConfig(name="Orders", path="/orders", data_selector="orders"),+ "DraftOrders": MedusaEndpointConfig(name="DraftOrders", path="/draft-orders", data_selector="draft_orders"),+ "Products": MedusaEndpointConfig(name="Products", path="/products", data_selector="products"),+ "ProductVariants": MedusaEndpointConfig(name="ProductVariants", path="/product-variants", data_selector="variants"),+ "Customers": MedusaEndpointConfig(name="Customers", path="/customers", data_selector="customers"),+ "CustomerGroups": MedusaEndpointConfig(+ name="CustomerGroups", path="/customer-groups", data_selector="customer_groups"+ ),+ "Regions": MedusaEndpointConfig(name="Regions", path="/regions", data_selector="regions"),+ "PriceLists": MedusaEndpointConfig(+ name="PriceLists", path="/price-lists", data_selector="price_lists", incremental_field_name=None+ ),+ "Returns": MedusaEndpointConfig(name="Returns", path="/returns", data_selector="returns"),+}++ENDPOINTS = tuple(MEDUSA_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in MEDUSA_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/source.pyindex 23c50c67b6c9..b5d802761874 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/source.py@@ -1,26 +1,182 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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.mixins import ValidateDatabaseHostMixinfrom 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.medusa import MedusaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.medusa import (+ HTTPS_REQUIRED_ERROR,+ INVALID_URL_ERROR,+ PAGINATION_LIMIT_ERROR,+ MedusaResumeConfig,+ hostname_of,+ medusa_source,+ validate_credentials as validate_medusa_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MEDUSA_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+CAPTION = """Sync orders, products, customers and more from your self-hosted Medusa server into the PostHog Data warehouse.++Requires Medusa v2. Create a secret API key in your Medusa Admin dashboard under **Settings > Secret API Keys**, then enter it here with your server's URL. Publishable API keys only work with the Store API and will not work here."""++REJECTED_KEY_MESSAGE = "Medusa rejected the API key. Check that you're using a secret API key from a Medusa v2 server, not a publishable key."+@SourceRegistry.register-class MedusaSource(SimpleSource[MedusaSourceConfig]):+class MedusaSource(ResumableSource[MedusaSourceConfig, MedusaResumeConfig], ValidateDatabaseHostMixin):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs++ # The v2 Admin API carries no version token on the wire (no version path segment, header,+ # or param); v2 names the Medusa platform generation whose route shapes and `[$gte]` filter+ # syntax this source targets. Medusa v1 servers use different routes and auth, and the+ # credential probe fails against them.+ api_docs_url = "https://docs.medusajs.com/api/admin"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MEDUSA+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored secret API key is sent to `base_url`; retargeting it must re-require the+ # key so an editor can't exfiltrate it to a host they control.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.MEDUSA,category=DataWarehouseSourceCategory.E_COMMERCE,label="Medusa",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=CAPTION,iconPath="/static/services/medusa.png",+ docsUrl="https://posthog.com/docs/cdp/sources/medusa",keywords=["commerce", "ecommerce", "medusajs"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="base_url",+ label="Medusa server URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://store.example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ 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": f"{REJECTED_KEY_MESSAGE} Then reconnect.",+ "403 Client Error": "The API key does not have access to this data. Check the key in your Medusa Admin dashboard, then reconnect.",+ HTTPS_REQUIRED_ERROR: "The Medusa server URL must use HTTPS so your API key is not sent in the clear. Update the server URL and reconnect.",+ INVALID_URL_ERROR: "The Medusa server URL is invalid. Enter your server's public URL, e.g. https://store.example.com, and reconnect.",+ PAGINATION_LIMIT_ERROR: "Medusa kept returning pages without reaching the total it reported. Check that the server URL points at your Medusa server.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MedusaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Commerce 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: MedusaSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ hostname = hostname_of(config.base_url)+ except ValueError as e:+ return False, str(e)++ host_valid, host_error = self.is_database_host_valid(hostname, team_id)+ if not host_valid:+ return False, host_error++ ok, status = validate_medusa_credentials(config.base_url, config.api_key)+ if ok:+ return True, None+ # Secret API keys act as the admin user they belong to, so 403 at create still means+ # the key can't read the store's data; there are no per-endpoint scopes to defer to.+ if status in (401, 403):+ return False, REJECTED_KEY_MESSAGE+ return (+ False,+ "Couldn't connect to the Medusa server. Check the server URL and that the server is reachable, then try again.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MedusaResumeConfig]:+ return ResumableSourceManager[MedusaResumeConfig](inputs, MedusaResumeConfig)++ def source_for_pipeline(+ self,+ config: MedusaSourceConfig,+ resumable_source_manager: ResumableSourceManager[MedusaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in MEDUSA_ENDPOINTS:+ raise ValueError(f"Unknown Medusa schema '{inputs.schema_name}'")++ return medusa_source(+ base_url=config.base_url,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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/medusa/tests/test_medusa.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/tests/test_medusa.pynew file mode 100644index 000000000000..fc544e7b4400--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/tests/test_medusa.py@@ -0,0 +1,245 @@+import json+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response+from requests.auth import HTTPBasicAuth++from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.medusa import (+ MedusaPaginator,+ MedusaResumeConfig,+ _read_capped,+ _to_iso8601,+ get_resource,+ medusa_source,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.settings import (+ MAX_ROWS_PER_SYNC,+ MEDUSA_ENDPOINTS,+ PAGE_SIZE,+)++MEDUSA_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.medusa.medusa"++BASE_URL = "https://store.example.com"+++def _json_response(body: dict[str, Any], status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ return response+++def _streamed_response(chunks: list[bytes]) -> Response:+ response = Response()+ response.status_code = 200+ raw = MagicMock()+ raw.stream.return_value = iter(chunks)+ response.raw = raw+ return response+++def _make_manager(resume_state: MedusaResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++class TestMedusaTransport:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("store.example.com", "https://store.example.com"),+ ("https://store.example.com/", "https://store.example.com"),+ ("https://store.example.com:9000", "https://store.example.com:9000"),+ ("https://proxy.example.com/medusa", "https://proxy.example.com/medusa"),+ ],+ )+ def test_normalizes_valid_urls(self, raw: str, expected: str) -> None:+ assert normalize_base_url(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ None,+ "",+ " ",+ "http://store.example.com", # plaintext would put the API key on the wire in the clear+ "https://user:[email protected]", # credentials in the authority+ "https://evil.com\\@store.example.com", # urlparse/http-client host disagreement+ "https://evil.com%40store.example.com", # encoded authority delimiter+ "https://",+ ],+ )+ def test_rejects_unsafe_urls(self, raw: str | None) -> None:+ with pytest.raises(ValueError):+ normalize_base_url(raw)++ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (None, None),+ ("2026-01-02T03:04:05+00:00", "2026-01-02T03:04:05Z"),+ ("2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),+ ("2026-01-02 03:04:05", "2026-01-02T03:04:05Z"),+ ("not a date", None),+ ],+ )+ def test_to_iso8601(self, value: Any, expected: str | None) -> None:+ assert _to_iso8601(value) == expected++ def test_incremental_resource_filters_and_sorts_on_the_cursor(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(MEDUSA_ENDPOINTS["Orders"], should_use_incremental_field=True),+ )++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ endpoint = resource["endpoint"]+ assert endpoint["path"] == "/admin/orders"+ assert endpoint["params"]["order"] == "updated_at"+ assert endpoint["incremental"]["start_param"] == "updated_at[$gte]"+ assert endpoint["incremental"]["cursor_path"] == "updated_at"++ def test_full_refresh_resource_omits_the_watermark_filter(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(MEDUSA_ENDPOINTS["Orders"], should_use_incremental_field=False),+ )++ assert resource["write_disposition"] == "replace"+ endpoint = resource["endpoint"]+ assert "incremental" not in endpoint+ assert endpoint["params"]["order"] == "created_at"+ assert not any("$gte" in param for param in endpoint["params"])++ def test_incremental_rejected_for_endpoint_without_timestamp_filters(self) -> None:+ with pytest.raises(ValueError, match="does not support incremental"):+ get_resource(MEDUSA_ENDPOINTS["PriceLists"], should_use_incremental_field=True)++ def test_incremental_rejected_for_unadvertised_cursor_field(self) -> None:+ with pytest.raises(ValueError, match="no incremental field 'created_at'"):+ get_resource(+ MEDUSA_ENDPOINTS["Orders"],+ should_use_incremental_field=True,+ incremental_field_name="created_at",+ )++ def test_paginator_aborts_past_the_row_budget_even_after_a_resume(self) -> None:+ # A user-controlled host that keeps returning full pages forever must fail the sync+ # loudly instead of holding the import until its activity timeout. The budget rides+ # `offset`, so a resumed sync keeps the position it already paid for.+ paginator = MedusaPaginator()+ paginator.set_resume_state({"offset": MAX_ROWS_PER_SYNC})+ rows = [{"id": f"order_{i}"} for i in range(PAGE_SIZE)]++ with pytest.raises(ValueError, match="did not terminate"):+ paginator.update_state(_json_response({"orders": rows}), data=rows)++ def test_read_capped_aborts_over_the_byte_limit(self) -> None:+ # A hostile host can return an arbitrarily large or highly compressed body; the cap+ # aborts mid-stream instead of buffering it all into worker memory.+ with patch(f"{MEDUSA_MODULE}.MAX_RESPONSE_BYTES", 3):+ with pytest.raises(ValueError, match="exceeded"):+ _read_capped(_streamed_response([b"ab", b"cd"]))++ def test_validate_credentials_probes_with_basic_key_auth(self) -> None:+ with patch(f"{MEDUSA_MODULE}._bounded_session") as mock_session:+ mock_session.return_value.get.return_value = MagicMock(status_code=200)++ result = validate_credentials(BASE_URL, "sk_test")++ assert result == (True, 200)+ call = mock_session.return_value.get.call_args+ assert call.args[0] == f"{BASE_URL}/admin/regions?limit=1"+ # The key is the Basic username with an empty password.+ assert call.kwargs["auth"] == HTTPBasicAuth("sk_test", "")+ assert call.kwargs["allow_redirects"] is False++ @patch(f"{MEDUSA_MODULE}.rest_api_resource")+ def test_source_pins_requests_to_the_configured_host(self, mock_rest_api_resource: MagicMock) -> None:+ medusa_source(+ base_url=BASE_URL,+ api_key="sk_test",+ endpoint="Orders",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ config = mock_rest_api_resource.call_args.args[0]+ client = config["client"]+ assert client["base_url"] == BASE_URL+ assert client["auth"] == {"type": "http_basic", "username": "sk_test", "password": ""}+ assert client["allowed_hosts"] == []+ assert client["allow_redirects"] is False++ @patch(f"{MEDUSA_MODULE}.rest_api_resource")+ def test_source_response_partitions_on_a_stable_field(self, mock_rest_api_resource: MagicMock) -> None:+ response = medusa_source(+ base_url=BASE_URL,+ api_key="sk_test",+ endpoint="Orders",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert response.name == "Orders"+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"+ mock_rest_api_resource.assert_called_once()++ @patch(f"{MEDUSA_MODULE}.rest_api_resource")+ def test_fresh_run_starts_without_paginator_state(self, mock_rest_api_resource: MagicMock) -> None:+ medusa_source(+ base_url=BASE_URL,+ api_key="sk_test",+ endpoint="Orders",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] is None++ @patch(f"{MEDUSA_MODULE}.rest_api_resource")+ def test_resume_seeds_the_saved_paginator_state(self, mock_rest_api_resource: MagicMock) -> None:+ medusa_source(+ base_url=BASE_URL,+ api_key="sk_test",+ endpoint="Orders",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(MedusaResumeConfig(paginator_state={"offset": 300})),+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"offset": 300}++ @patch(f"{MEDUSA_MODULE}.rest_api_resource")+ def test_checkpoint_saves_only_resumable_state(self, mock_rest_api_resource: MagicMock) -> None:+ manager = _make_manager()+ medusa_source(+ base_url=BASE_URL,+ api_key="sk_test",+ endpoint="Orders",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )+ save_checkpoint = mock_rest_api_resource.call_args.kwargs["resume_hook"]++ save_checkpoint({"offset": 200})+ manager.save_state.assert_called_once_with(MedusaResumeConfig(paginator_state={"offset": 200}))++ manager.save_state.reset_mock()+ save_checkpoint(None)+ manager.save_state.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/tests/test_medusa_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/tests/test_medusa_source.pynew file mode 100644index 000000000000..0df7b4bd1f8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/medusa/tests/test_medusa_source.py@@ -0,0 +1,101 @@+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.medusa import MedusaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.medusa.source import MedusaSource++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.medusa.source"+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "Orders",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestMedusaSource:+ def setup_method(self) -> None:+ self.source = MedusaSource()+ self.team_id = 123+ self.config = MedusaSourceConfig(base_url="https://store.example.com", api_key="sk_test")++ def test_base_url_is_a_connection_host_field(self) -> None:+ # Changing base_url must force the API key to be re-entered, so the stored key is+ # never sent to a freshly-specified host.+ assert self.source.connection_host_fields == ["base_url"]++ @pytest.mark.parametrize(+ "base_url",+ [+ "",+ "http://store.example.com",+ "https://user:[email protected]",+ ],+ )+ def test_validate_credentials_rejects_unsafe_urls_before_probing(self, base_url: str) -> None:+ config = MedusaSourceConfig(base_url=base_url, api_key="sk_test")+ with mock.patch(f"{SOURCE_MODULE}.validate_medusa_credentials") as mock_probe:+ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert message+ mock_probe.assert_not_called()++ def test_validate_credentials_rejects_disallowed_hosts_before_probing(self) -> None:+ with (+ mock.patch.object(MedusaSource, "is_database_host_valid", return_value=(False, "Host is not allowed")),+ mock.patch(f"{SOURCE_MODULE}.validate_medusa_credentials") as mock_probe,+ ):+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert (is_valid, message) == (False, "Host is not allowed")+ mock_probe.assert_not_called()++ @pytest.mark.parametrize(+ ("probe_result", "expected_valid", "expected_message_part"),+ [+ ((True, 200), True, None),+ ((False, 401), False, "secret API key"),+ ((False, 403), False, "secret API key"),+ ((False, None), False, "Couldn't connect"),+ ((False, 500), False, "Couldn't connect"),+ ],+ )+ def test_validate_credentials_maps_probe_results(+ self,+ probe_result: tuple[bool, int | None],+ expected_valid: bool,+ expected_message_part: str | None,+ ) -> None:+ with (+ mock.patch.object(MedusaSource, "is_database_host_valid", return_value=(True, None)),+ mock.patch(f"{SOURCE_MODULE}.validate_medusa_credentials", return_value=probe_result),+ ):+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if expected_message_part is None:+ assert message is None+ else:+ assert message is not None and expected_message_part in message++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ manager = mock.MagicMock()+ with pytest.raises(ValueError, match="Unknown Medusa schema"):+ self.source.source_for_pipeline(self.config, manager, _make_inputs(schema_name="Fulfillments"))