:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Conekta source (#77136)
Tom Owers9ee85472ce6e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 07677acb7cb7..624fa24eb58a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -159,6 +159,7 @@ the row lists both.| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ || commercetools | HTTP | requests | ✅ || concord | HTTP | requests | ✅ |+| conekta | HTTP | requests + `rest_source.RESTClient` | ✅ || configcat | HTTP | requests | ✅ || confluence | HTTP | requests | ✅ || confluent_cloud | HTTP | requests | ✅ |@@ -877,7 +878,6 @@ doesn't conflict with concurrent PRs.- codecov- collibra- companycam-- conekta- constant_contact- conta_azul- contentsquarediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/canonical_descriptions.pynew file mode 100644index 000000000000..417741571b56--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/canonical_descriptions.py@@ -0,0 +1,210 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS = "https://developers.conekta.com/reference"++# Descriptions are taken from Conekta's published OpenAPI specification (api.conekta.io, v2.3.0).+# Amounts are integers in the smallest currency unit and timestamps are int64 Unix seconds+# throughout the API, so those two facts are repeated on the relevant columns rather than assumed.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "charges": {+ "description": "A single attempt to collect money for an order through one payment method.",+ "docs_url": f"{_DOCS}/getcharges",+ "columns": {+ "id": "Unique identifier for the charge.",+ "amount": "Amount the charge collects, in cents.",+ "channel": "Where the charge originated, such as the checkout, the panel, or the API.",+ "created_at": "Time the charge was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the charge.",+ "customer_id": "Identifier of the customer the charge belongs to.",+ "description": "Free-text description of the charge.",+ "device_fingerprint": "Fingerprint of the device that submitted the payment.",+ "failure_code": "Code explaining why the charge failed, when it did.",+ "failure_message": "Human-readable reason the charge failed, when it did.",+ "livemode": "True when the charge was made with a production key, false in test mode.",+ "object": "Object type, always 'charge'.",+ "order_id": "Identifier of the order this charge pays for.",+ "paid_at": "Time the charge was paid, in seconds since the Unix epoch.",+ "payment_method": "Payment method used, such as a card, an OXXO cash voucher, or a SPEI transfer.",+ "reference_id": "Reference identifier of the charge.",+ "refunds": "Refunds issued against this charge.",+ "chargeback": "Chargeback raised against this charge, when one exists.",+ "status": "Current status of the charge.",+ },+ },+ "checkouts": {+ "description": "A hosted payment link customers can use to pay without a custom checkout page.",+ "docs_url": f"{_DOCS}/getcheckouts",+ "columns": {+ "id": "Unique identifier for the checkout.",+ "allowed_payment_methods": "Payment methods available on this link.",+ "excluded_payment_methods": "Payment methods excluded from this link.",+ "plan_ids": "Plans that can be subscribed to through this link.",+ "can_not_expire": "True when the link never expires.",+ "emails_sent": "Number of emails sent for this link.",+ "exclude_card_networks": "Card networks that cannot be used on this link.",+ "expires_at": "Time the link expires, in seconds since the Unix epoch.",+ "failure_url": "URL the customer is sent to after a failed payment.",+ "force_3ds_flow": "True when 3D Secure is always required.",+ "livemode": "True when the link was created with a production key, false in test mode.",+ "metadata": "Key-value pairs attached to the link.",+ "monthly_installments_enabled": "True when the link offers monthly installments.",+ "monthly_installments_options": "Installment counts offered on this link.",+ "name": "Reason for the charge shown to the customer.",+ "needs_shipping_contact": "True when the customer must supply a shipping contact.",+ "object": "Object type, always 'checkout'.",+ "paid_payments_count": "Number of payments already made through this link.",+ "payments_limit_count": "Maximum number of payments the link accepts.",+ "recurrent": "True when the link can be paid more than once.",+ "slug": "Short identifier used in the link's public URL.",+ "sms_sent": "Number of SMS messages sent for this link.",+ "starts_at": "Time the link becomes payable, in seconds since the Unix epoch.",+ "status": "Current status of the link.",+ "success_url": "URL the customer is sent to after a successful payment.",+ "type": "Link type, such as a one-off payment link or an integration checkout.",+ "url": "Public URL the customer opens to pay.",+ },+ },+ "customers": {+ "description": "A person or company you charge, along with their saved payment sources.",+ "docs_url": f"{_DOCS}/getcustomers",+ "columns": {+ "id": "Unique identifier for the customer.",+ "antifraud_info": "Antifraud signals recorded for the customer.",+ "corporate": "True when the customer is a company rather than a person.",+ "created_at": "Time the customer was created, in seconds since the Unix epoch.",+ "custom_reference": "Your own reference for the customer.",+ "date_of_birth": "Customer's date of birth.",+ "default_fiscal_entity_id": "Identifier of the customer's default fiscal entity.",+ "default_shipping_contact_id": "Identifier of the customer's default shipping contact.",+ "default_payment_source_id": "Identifier of the customer's default payment source.",+ "email": "Customer's email address.",+ "fiscal_entities": "Fiscal entities registered for the customer.",+ "livemode": "True when the customer exists in live mode, false in test mode.",+ "name": "Customer's name.",+ "national_id": "Customer's national identification number.",+ "metadata": "Key-value pairs attached to the customer.",+ "object": "Object type, always 'customer'.",+ "payment_sources": "Payment sources saved against the customer.",+ "phone": "Customer's phone number.",+ "shipping_contacts": "Shipping contacts saved against the customer.",+ "subscription": "The customer's active subscription, when they have one.",+ },+ },+ "events": {+ "description": "A record of something that happened in your Conekta account, and what was delivered to your webhooks.",+ "docs_url": f"{_DOCS}/getevents",+ "columns": {+ "id": "Unique identifier for the event.",+ "created_at": "Time the event occurred, in seconds since the Unix epoch.",+ "data": "The object the event describes, as it looked when the event fired.",+ "livemode": "True when the event happened in live mode, false in test mode.",+ "object": "Object type, always 'event'.",+ "type": "Event type, such as 'order.paid' or 'charge.created'.",+ "webhook_logs": "Delivery attempts made for this event.",+ "webhook_status": "Whether the event was delivered to your webhooks.",+ },+ },+ "orders": {+ "description": "A purchase: what the customer bought, what it cost, and the charges collecting it.",+ "docs_url": f"{_DOCS}/getorders",+ "columns": {+ "id": "Unique identifier for the order.",+ "amount": "Total amount to be collected, in cents.",+ "amount_refunded": "Total amount refunded, in cents.",+ "channel": "Where the order originated, such as the checkout, the panel, or the API.",+ "charges": "Charges created to collect this order.",+ "checkout": "Payment link associated with the order, when one was used.",+ "created_at": "Time the order was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the order.",+ "customer_info": "Details of the customer the order belongs to.",+ "discount_lines": "Discounts applied to the order.",+ "tax_lines": "Taxes applied to the order.",+ "shipping_lines": "Shipping costs applied to the order.",+ "fiscal_entity": "Fiscal entity the order is billed to.",+ "is_refundable": "True when the order can still be refunded.",+ "line_items": "Products or services the order is for.",+ "livemode": "True when the order exists in live mode, false in test mode.",+ "metadata": "Key-value pairs attached to the order.",+ "next_action": "What the customer has to do next to complete payment.",+ "object": "Object type, always 'order'.",+ "payment_status": "Payment status of the order, such as 'paid' or 'pending_payment'.",+ "processing_mode": "How the order is processed: ecommerce, recurrent, or validation.",+ "shipping_contact": "Address the order ships to.",+ "updated_at": "Time the order was last updated, in seconds since the Unix epoch.",+ },+ },+ "payout_orders": {+ "description": "Money paid out from your Conekta balance to a recipient.",+ "docs_url": f"{_DOCS}/getpayoutorders",+ "columns": {+ "id": "Unique identifier for the payout order.",+ "allowed_payout_methods": "Payout methods the recipient can use.",+ "amount": "Amount paid out, in cents.",+ "created_at": "Time the payout order was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the payout order.",+ "customer_info": "Details of the recipient.",+ "expires_at": "Time the payout order expires, in seconds since the Unix epoch.",+ "livemode": "True when the payout order exists in live mode, false in test mode.",+ "object": "Object type, always 'payout_order'.",+ "metadata": "Key-value pairs attached to the payout order.",+ "payouts": "Individual payouts made for this payout order.",+ "reason": "Reason the payout was made.",+ "status": "Current status of the payout order.",+ "updated_at": "Time the payout order was last updated, in seconds since the Unix epoch.",+ },+ },+ "plans": {+ "description": "A recurring billing plan customers can subscribe to.",+ "docs_url": f"{_DOCS}/getplans",+ "columns": {+ "id": "Unique identifier for the plan.",+ "amount": "Amount billed each cycle, in cents.",+ "created_at": "Time the plan was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the plan.",+ "expiry_count": "Number of cycles billed before the subscription ends.",+ "frequency": "How many intervals pass between charges.",+ "interval": "Billing interval, such as week, month, or year.",+ "livemode": "True when the plan exists in live mode, false in test mode.",+ "name": "Name of the plan.",+ "object": "Object type, always 'plan'.",+ "trial_period_days": "Length of the free trial, in days.",+ "max_retries": "How many times a failed charge is retried.",+ "retry_delay_hours": "Hours waited between retries of a failed charge.",+ },+ },+ "transactions": {+ "description": "A movement of money on your Conekta balance, with the fee and net amount for a charge.",+ "docs_url": f"{_DOCS}/gettransactions",+ "columns": {+ "id": "Unique identifier for the transaction.",+ "amount": "Gross amount of the transaction, in cents.",+ "charge": "Identifier of the charge the transaction belongs to.",+ "created_at": "Time the transaction was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the transaction.",+ "fee": "Amount deducted for taxes and commissions, in cents.",+ "livemode": "True when the transaction was created in live mode, false in test mode.",+ "net": "Amount left after fees and taxes, in cents.",+ "object": "Object type, always 'transaction'.",+ "status": "Current status of the transaction.",+ "type": "Transaction type, such as a payment, refund, or fee.",+ },+ },+ "transfers": {+ "description": "A payout of your Conekta balance to your bank account.",+ "docs_url": f"{_DOCS}/gettransfers",+ "columns": {+ "id": "Unique identifier for the transfer.",+ "amount": "Amount transferred, in cents.",+ "created_at": "Time the transfer was created, in seconds since the Unix epoch.",+ "currency": "Three-letter ISO 4217 currency code for the transfer.",+ "livemode": "True when the transfer was created in live mode, false in test mode.",+ "destination": "Bank account the money was sent to.",+ "object": "Object type, always 'transfer'.",+ "statement_description": "Description shown on the bank statement.",+ "statement_reference": "Reference number shown on the bank statement.",+ "status": "Current status of the transfer.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/conekta.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/conekta.pynew file mode 100644index 000000000000..06fb6eb28b16--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/conekta.py@@ -0,0 +1,262 @@+import dataclasses+from datetime import date, datetime+from typing import Any, Optional+from urllib.parse import parse_qs, urlsplit++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+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.conekta.settings import (+ API_VERSION,+ BASE_URL,+ CONEKTA_ENDPOINTS,+ PAGE_SIZE,+)+++class ConektaResumeConfig:+ next_cursor: str+++def build_headers(api_version: str = API_VERSION) -> dict[str, str]:+ return {+ # Conekta refuses requests without a versioned Accept header, which is also how the API+ # version is pinned (there is no version path segment).+ "Accept": f"application/vnd.conekta-v{api_version}+json",+ "Content-Type": "application/json",+ # Responses default to Spanish; ask for English so surfaced error messages are readable.+ "Accept-Language": "en",+ }+++def to_epoch_seconds(value: Any) -> Any:+ """Coerce a stored watermark to the int64 Unix seconds Conekta's `<field>.gte` filters take.++ The incremental fields are declared as integers, so the value normally arrives as an int+ already; datetimes and ISO strings are handled defensively. Anything unrecognised is passed+ through so the API, not this function, decides it is invalid.+ """+ if isinstance(value, bool) or value is None:+ return value+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, datetime):+ return int(value.timestamp())+ if isinstance(value, date):+ return int(datetime(value.year, value.month, value.day).timestamp())+ if isinstance(value, str):+ try:+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())+ except ValueError:+ pass+ try:+ return int(value)+ except ValueError:+ return value+ return value+++def extract_next_cursor(body: Any) -> Optional[str]:+ """Pull the `next` cursor out of a Conekta list response, or None on the last page."""+ if not isinstance(body, dict):+ return None+ if body.get("has_more") is False:+ return None+ next_page_url = body.get("next_page_url")+ if not isinstance(next_page_url, str) or not next_page_url:+ return None+ values = parse_qs(urlsplit(next_page_url).query).get("next")+ return values[0] if values and values[0] else None+++class ConektaCursorPaginator(BasePaginator):+ """Pages Conekta list endpoints by re-sending the `next` cursor on the original request.++ Responses look like `{"data": [...], "has_more": true, "next_page_url": ".../orders?limit=250&next=ord_x"}`.+ The next-page URL only echoes `limit` and `next`, so following it verbatim (the usual+ next-URL paginator) would drop the incremental `updated_at.gte` filter from page two onwards+ and walk the merchant's whole history on every run. Taking just the cursor and re-issuing it+ against the request we built keeps every filter attached. Whether Conekta applies a timestamp+ filter alongside `next` is undocumented, but sending it can only narrow the result set.+ """++ def __init__(self) -> None:+ super().__init__()+ self._next_cursor: Optional[str] = None+ self._previous_cursor: Optional[str] = None++ def _apply(self, request: Request) -> None:+ if self._next_cursor is None:+ return+ if request.params is None:+ request.params = {}+ request.params["next"] = self._next_cursor++ def init_request(self, request: Request) -> None:+ # Seeded by set_resume_state so a resumed run starts at the saved cursor.+ self._apply(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except ValueError:+ body = None++ cursor = extract_next_cursor(body)+ # A repeated cursor means the API is not advancing; stop rather than loop for the+ # activity's full (week-long, for resumable sources) timeout.+ if cursor is None or cursor == self._previous_cursor:+ self._next_cursor = None+ self._has_next_page = False+ return++ self._previous_cursor = cursor+ self._next_cursor = cursor+ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ self._apply(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page and self._next_cursor is not None:+ return {"next_cursor": self._next_cursor}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ next_cursor = state.get("next_cursor")+ if next_cursor is not None:+ self._next_cursor = str(next_cursor)+ # Seed the repeat guard so a resumed page whose response echoes the saved cursor+ # stops instead of looping on a poisoned checkpoint.+ self._previous_cursor = self._next_cursor+ self._has_next_page = True++ def __str__(self) -> str:+ return "ConektaCursorPaginator()"+++def _make_session(api_key: str, api_version: str):+ return make_tracked_session(+ headers=build_headers(api_version),+ redact_values=(api_key,),+ # List responses carry cardholder and customer PII (names, emails, phones, national ids),+ # so keep raw bodies out of HTTP sample capture even when an operator enables it.+ capture=False,+ allow_redirects=False,+ )+++def validate_credentials(api_key: str, api_version: str = API_VERSION) -> tuple[bool, Optional[int]]:+ """Probe the private key with the cheapest authenticated list call Conekta offers."""+ return validate_via_probe(+ lambda: _make_session(api_key, api_version),+ f"{BASE_URL}/orders?limit=1",+ headers={"Authorization": f"Bearer {api_key}"},+ allow_redirects=False,+ )+++def conekta_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ConektaResumeConfig],+ incremental_field: Optional[str] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ api_version: str = API_VERSION,+) -> SourceResponse:+ endpoint_config = CONEKTA_ENDPOINTS[endpoint]++ # Only `/orders` accepts server-side timestamp filters, and only for the fields it documents;+ # anything else falls back to a full refresh rather than paging everything and filtering here.+ supported_cursors = {field["field"] for field in endpoint_config.incremental_fields}+ cursor_field = incremental_field if incremental_field in supported_cursors else None+ use_incremental = should_use_incremental_field and cursor_field is not None++ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if use_incremental:+ params[f"{cursor_field}.gte"] = {+ "type": "incremental",+ "cursor_path": cursor_field,+ "initial_value": 0,+ "convert": to_epoch_seconds,+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "headers": build_headers(api_version),+ "auth": {"type": "bearer", "token": api_key},+ "paginator": ConektaCursorPaginator(),+ "session": _make_session(api_key, api_version),+ # Pin every request to the Conekta origin and refuse redirects: the cursor comes out+ # of a response-controlled URL, so a poisoned `next_page_url` must not be able to+ # retarget the bearer token.+ "allowed_hosts": [],+ "allow_redirects": False,+ },+ "resources": [+ {+ "name": endpoint,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "table_format": "delta",+ "endpoint": {+ "path": endpoint_config.path,+ "params": params,+ "data_selector": "data",+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"next_cursor": resume.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Fires after a page is yielded, so a crash re-yields the last page (merge dedupes on+ # `id`) rather than skipping it. Only persist while a next page remains.+ if state and state.get("next_cursor"):+ resumable_source_manager.save_state(ConektaResumeConfig(next_cursor=str(state["next_cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if use_incremental else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ partition_keys = [endpoint_config.partition_key] if endpoint_config.partition_key else None++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ # Conekta documents no ordering for its list endpoints and exposes no sort parameter, so+ # we cannot claim rows arrive oldest-first. "desc" is the conservative branch: it commits+ # the incremental watermark only after a fully successful sync, whereas "asc" would+ # checkpoint after every batch and silently skip rows if the API returns newest-first.+ sort_mode="desc",+ partition_count=1 if partition_keys else None,+ partition_size=1 if partition_keys else None,+ partition_mode="datetime" if partition_keys else None,+ partition_format="month" if partition_keys else None,+ partition_keys=partition_keys,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/settings.pynew file mode 100644index 000000000000..89b6972205f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/settings.py@@ -0,0 +1,62 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://api.conekta.io"++# Conekta versions its API through the Accept header (`application/vnd.conekta-v<version>+json`)+# rather than a URL path segment, so the version label is sent on every request.+API_VERSION = "2.3.0"++# `limit` is capped at 250 across every list endpoint (the default is 20).+PAGE_SIZE = 250+++def _epoch_incremental_field(name: str) -> IncrementalField:+ # Conekta timestamps are int64 seconds since the Unix epoch, so the stored cursor value is an+ # integer even though it means a point in time.+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.Integer,+ }+++@dataclass+class ConektaEndpointConfig:+ path: str+ # Only `/orders` documents server-side timestamp filters (`created_at.gte` / `updated_at.gte`),+ # so it is the only endpoint that can sync incrementally. Everything else is full refresh:+ # paging the whole endpoint and dropping rows in Python would cost the same as a full sync.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation timestamp used for datetime partitioning. `None` for resources that expose+ # no creation timestamp at all (checkouts), which therefore stay unpartitioned.+ partition_key: str | None = "created_at"+++CONEKTA_ENDPOINTS: dict[str, ConektaEndpointConfig] = {+ "charges": ConektaEndpointConfig(path="/charges"),+ # Payment links carry `starts_at` / `expires_at` but no creation timestamp.+ "checkouts": ConektaEndpointConfig(path="/checkouts", partition_key=None),+ "customers": ConektaEndpointConfig(path="/customers"),+ "events": ConektaEndpointConfig(path="/events"),+ "orders": ConektaEndpointConfig(+ path="/orders",+ incremental_fields=[_epoch_incremental_field("updated_at"), _epoch_incremental_field("created_at")],+ ),+ "payout_orders": ConektaEndpointConfig(path="/payout_orders"),+ "plans": ConektaEndpointConfig(path="/plans"),+ "transactions": ConektaEndpointConfig(path="/transactions"),+ "transfers": ConektaEndpointConfig(path="/transfers"),+}++ENDPOINTS = tuple(CONEKTA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CONEKTA_ENDPOINTS.items() if config.incremental_fields+}++# Orders is merge-only: the `<field>.gte` filter is inclusive, so the watermark row comes back on+# every run and only a merge on `id` can dedupe it.+MERGE_ONLY_ENDPOINTS = ("orders",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/source.pyindex c7dbcbe9bdd8..7f0f5189cfb9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/source.py@@ -1,21 +1,49 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta import conekta as api_client+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.conekta import ConektaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MERGE_ONLY_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.conekta import (ConektaSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+CONEKTA_API_KEYS_URL = "https://panel.conekta.com/developers/api-keys"+@SourceRegistry.register-class ConektaSource(SimpleSource[ConektaSourceConfig]):+class ConektaSource(ResumableSource[ConektaSourceConfig, ConektaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Conekta pins the response format with an `Accept: application/vnd.conekta-v<version>+json`+ # header, which `conekta.build_headers` sends on every request. 2.3.0 is the current version.+ supported_versions = ("2.3.0",)+ default_version = "2.3.0"+ api_docs_url = "https://developers.conekta.com/reference/versiones"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CONEKTA@@ -26,7 +54,99 @@ class ConektaSource(SimpleSource[ConektaSourceConfig]):name=SchemaExternalDataSourceType.CONEKTA,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Conekta",+ caption=(+ "Sync orders, charges, customers, and payouts from Conekta into PostHog. Use the "+ f"private key from [Developers > API keys]({CONEKTA_API_KEYS_URL}) in your Conekta "+ "panel. Production and test keys return different data, so pick the environment "+ "you want to sync."+ ),iconPath="/static/services/conekta.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/conekta",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Private key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="key_...",+ caption=(+ "The private key from [Developers > API keys]"+ f"({CONEKTA_API_KEYS_URL}). The public key is only used for frontend "+ "tokenization and will not work here."+ ),+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.conekta.io": (+ "Conekta rejected the private key. Check it under Developers > API keys and reconnect."+ ),+ "403 Client Error: Forbidden for url: https://api.conekta.io": (+ "This Conekta private key does not have access to the requested resource. "+ "Check the key's permissions and reconnect."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ConektaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Orders is merge-only: `<field>.gte` is inclusive, so the watermark row returns on every+ # run and only a merge on `id` dedupes it.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=MERGE_ONLY_ENDPOINTS)++ def validate_credentials(+ self,+ config: ConektaSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, status = api_client.validate_credentials(config.api_key, self.resolve_api_version(api_version))+ if is_valid:+ return True, None+ if status == 401:+ return False, "Invalid Conekta private key. Make sure you used the private key, not the public one."+ return False, "Could not reach the Conekta API with these credentials. Please try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ConektaResumeConfig]:+ return ResumableSourceManager[ConektaResumeConfig](inputs, ConektaResumeConfig)++ def source_for_pipeline(+ self,+ config: ConektaSourceConfig,+ resumable_source_manager: ResumableSourceManager[ConektaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return api_client.conekta_source(+ 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,+ incremental_field=inputs.incremental_field,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta.pynew file mode 100644index 000000000000..d5a323960017--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta.py@@ -0,0 +1,319 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.conekta import (+ ConektaCursorPaginator,+ ConektaResumeConfig,+ build_headers,+ conekta_source,+ extract_next_cursor,+ to_epoch_seconds,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.settings import (+ API_VERSION,+ CONEKTA_ENDPOINTS,+ PAGE_SIZE,+)++SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.conekta.conekta.make_tracked_session"+++def _page(rows: list[dict[str, Any]], next_cursor: str | None) -> Response:+ body: dict[str, Any] = {"data": rows, "object": "list", "has_more": next_cursor is not None}+ body["next_page_url"] = (+ f"https://api.conekta.io/orders?limit={PAGE_SIZE}&next={next_cursor}" if next_cursor else None+ )+ body["previous_page_url"] = None+ response = Response()+ response.status_code = 200+ response._content = json.dumps(body).encode()+ return response+++def _make_manager(resume_state: ConektaResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ # Snapshot each request at prepare time: the client mutates one Request object across pages.+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return conekta_source("key_priv", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestToEpochSeconds:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (1676328434, 1676328434),+ (1676328434.9, 1676328434),+ (datetime(2023, 2, 13, 21, 27, 14, tzinfo=UTC), 1676323634),+ ("1676328434", 1676328434),+ ("2023-02-13T21:27:14+00:00", 1676323634),+ ("nonsense", "nonsense"),+ ],+ )+ def test_coerces_watermark_to_epoch_seconds(self, value, expected):+ assert to_epoch_seconds(value) == expected++ def test_date_maps_to_midnight(self):+ assert to_epoch_seconds(date(2023, 2, 13)) == int(datetime(2023, 2, 13).timestamp())+++class TestExtractNextCursor:+ @pytest.mark.parametrize(+ "body, expected",+ [+ ({"has_more": True, "next_page_url": "https://api.conekta.io/orders?limit=250&next=ord_2"}, "ord_2"),+ ({"has_more": False, "next_page_url": "https://api.conekta.io/orders?next=ord_2"}, None),+ ({"has_more": True, "next_page_url": None}, None),+ ({"has_more": True}, None),+ # A next URL without the cursor param is not a page we can request.+ ({"has_more": True, "next_page_url": "https://api.conekta.io/orders?limit=250"}, None),+ ("not-json-object", None),+ ],+ )+ def test_cursor_extraction(self, body, expected):+ assert extract_next_cursor(body) == expected+++class TestPaginator:+ def _advance(self, paginator: ConektaCursorPaginator, response: Response, request: Request) -> None:+ paginator.update_state(response)+ paginator.update_request(request)++ def test_keeps_original_params_and_adds_cursor(self):+ paginator = ConektaCursorPaginator()+ request = Request(method="GET", url="https://api.conekta.io/orders", params={"limit": 250, "updated_at.gte": 5})++ self._advance(paginator, _page([{"id": "ord_1"}], "ord_1"), request)++ assert paginator.has_next_page is True+ assert request.params == {"limit": 250, "updated_at.gte": 5, "next": "ord_1"}++ @pytest.mark.parametrize(+ "body",+ [+ {"data": [], "has_more": False, "next_page_url": None},+ {"data": [], "has_more": True, "next_page_url": None},+ ],+ )+ def test_stops_when_no_next_page(self, body):+ response = Response()+ response.status_code = 200+ response._content = json.dumps(body).encode()++ paginator = ConektaCursorPaginator()+ paginator.update_state(response)++ assert paginator.has_next_page is False+ assert paginator.get_resume_state() is None++ def test_stops_on_non_json_body(self):+ response = Response()+ response.status_code = 200+ response._content = b"<html>maintenance</html>"++ paginator = ConektaCursorPaginator()+ paginator.update_state(response)++ assert paginator.has_next_page is False++ def test_stops_when_cursor_repeats(self):+ paginator = ConektaCursorPaginator()+ request = Request(method="GET", url="https://api.conekta.io/orders", params={})++ self._advance(paginator, _page([{"id": "ord_1"}], "ord_1"), request)+ self._advance(paginator, _page([{"id": "ord_1"}], "ord_1"), request)++ assert paginator.has_next_page is False++ def test_resume_state_round_trip(self):+ paginator = ConektaCursorPaginator()+ paginator.update_state(_page([{"id": "ord_1"}], "ord_9"))+ state = paginator.get_resume_state()++ assert state == {"next_cursor": "ord_9"}++ seeded = ConektaCursorPaginator()+ seeded.set_resume_state(state)+ request = Request(method="GET", url="https://api.conekta.io/orders", params={"limit": 250})+ seeded.init_request(request)++ assert seeded.has_next_page is True+ assert request.params == {"limit": 250, "next": "ord_9"}++ def test_seeded_cursor_echoed_back_stops_instead_of_looping(self):+ paginator = ConektaCursorPaginator()+ paginator.set_resume_state({"next_cursor": "ord_9"})++ paginator.update_state(_page([{"id": "ord_9"}], "ord_9"))++ assert paginator.has_next_page is False+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(SESSION_PATCH)+ def test_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ is_valid, status = validate_credentials("key_priv")++ assert is_valid is expected+ assert status == status_code++ @mock.patch(SESSION_PATCH)+ def test_probes_orders_with_bearer_token_and_versioned_accept(self, mock_session):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)++ validate_credentials("key_priv")++ assert mock_session.call_args.kwargs["headers"]["Accept"] == f"application/vnd.conekta-v{API_VERSION}+json"+ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.conekta.io/orders?limit=1"+ assert call.kwargs["headers"]["Authorization"] == "Bearer key_priv"++ @mock.patch(SESSION_PATCH)+ def test_transport_failure_is_not_valid(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key_priv") == (False, None)+++class TestRequests:+ @mock.patch(SESSION_PATCH)+ def test_incremental_filter_survives_pagination(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "ord_1"}], "ord_1"), _page([{"id": "ord_2"}], None)])++ manager = _make_manager()+ rows = _rows(+ _source(+ "orders",+ manager,+ incremental_field="updated_at",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1676328434,+ )+ )++ assert [row["id"] for row in rows] == ["ord_1", "ord_2"]+ # Conekta's next_page_url only echoes limit+next, so the cursor must be re-applied to the+ # original request; otherwise page two drops the filter and walks the whole history.+ assert requests_seen[0]["params"] == {"limit": PAGE_SIZE, "updated_at.gte": 1676328434}+ assert requests_seen[1]["params"] == {"limit": PAGE_SIZE, "updated_at.gte": 1676328434, "next": "ord_1"}+ assert manager.save_state.call_args.args[0] == ConektaResumeConfig(next_cursor="ord_1")++ @mock.patch(SESSION_PATCH)+ def test_honors_the_users_chosen_incremental_field(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "ord_1"}], None)])++ _rows(+ _source(+ "orders",+ _make_manager(),+ incremental_field="created_at",+ should_use_incremental_field=True,+ db_incremental_field_last_value=99,+ )+ )++ assert requests_seen[0]["params"] == {"limit": PAGE_SIZE, "created_at.gte": 99}++ @pytest.mark.parametrize(+ "endpoint, incremental_field",+ [+ # No server-side timestamp filter exists on these endpoints, so no filter may be sent.+ ("charges", "created_at"),+ ("customers", "created_at"),+ # An unsupported cursor on an otherwise-incremental endpoint must not be sent either.+ ("orders", "paid_at"),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_full_refresh_when_the_endpoint_has_no_matching_filter(self, MockSession, endpoint, incremental_field):+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "x"}], None)])++ _rows(+ _source(+ endpoint,+ _make_manager(),+ incremental_field=incremental_field,+ should_use_incremental_field=True,+ db_incremental_field_last_value=99,+ )+ )++ assert requests_seen[0]["params"] == {"limit": PAGE_SIZE}++ @mock.patch(SESSION_PATCH)+ def test_sends_the_pinned_version_in_the_accept_header(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_page([{"id": "ord_1"}], None)])++ _rows(_source("orders", _make_manager(), api_version="2.3.0"))++ assert session.headers["Accept"] == "application/vnd.conekta-v2.3.0+json"++ @mock.patch(SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "ord_5"}], None)])++ rows = _rows(_source("orders", _make_manager(ConektaResumeConfig(next_cursor="ord_4"))))++ assert [row["id"] for row in rows] == ["ord_5"]+ assert requests_seen[0]["params"] == {"limit": PAGE_SIZE, "next": "ord_4"}+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", sorted(CONEKTA_ENDPOINTS))+ @mock.patch(SESSION_PATCH)+ def test_response_shape_per_endpoint(self, MockSession, endpoint):+ _wire(MockSession.return_value, [_page([], None)])++ response = _source(endpoint, _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Conekta documents no list ordering and offers no sort param, so the watermark may only be+ # committed after a fully successful sync.+ assert response.sort_mode == "desc"+ expected_key = CONEKTA_ENDPOINTS[endpoint].partition_key+ assert response.partition_keys == ([expected_key] if expected_key else None)+ assert response.partition_mode == ("datetime" if expected_key else None)+++class TestHeaders:+ def test_accept_header_pins_the_requested_version(self):+ assert build_headers("2.3.0")["Accept"] == "application/vnd.conekta-v2.3.0+json"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta_source.pynew file mode 100644index 000000000000..eee41d041163--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conekta/tests/test_conekta_source.py@@ -0,0 +1,185 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.conekta import ConektaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.settings import (+ API_VERSION,+ CONEKTA_ENDPOINTS,+ ENDPOINTS,+ MERGE_ONLY_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.conekta.source import ConektaSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.conekta import (+ ConektaSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.conekta.source.api_client"+++class TestConektaSource:+ def setup_method(self):+ self.source = ConektaSource()+ self.team_id = 123+ self.config = ConektaSourceConfig(api_key="key_priv")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CONEKTA++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Conekta"+ assert config.label == "Conekta"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The source must ship visible: unreleasedSource hides it from every user.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/conekta"++ def test_api_key_field_is_a_required_secret(self):+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"+ )++ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_declared_version_is_the_one_the_transport_sends(self):+ # A pin the code doesn't actually send makes every deprecation warning and upgrade path wrong.+ assert self.source.default_version == API_VERSION+ assert self.source.supported_versions == (API_VERSION,)++ @pytest.mark.parametrize(+ "observed_error, matches",+ [+ ("401 Client Error: Unauthorized for url: https://api.conekta.io/orders?limit=250", True),+ ("403 Client Error: Forbidden for url: https://api.conekta.io/payout_orders", True),+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers", False),+ ("500 Server Error for url: https://api.conekta.io/orders", False),+ ],+ )+ def test_non_retryable_errors_match_only_conekta_auth_failures(self, observed_error, matches):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors()) is matches++ def test_get_schemas_lists_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_only_orders_is_incremental(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ # `/orders` is the only endpoint documenting server-side `created_at.gte` / `updated_at.gte`+ # filters; claiming incremental anywhere else would page the whole endpoint every run.+ assert {schema.name for schema in schemas if schema.supports_incremental} == {"orders"}++ def test_incremental_schemas_are_merge_only(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ for name in MERGE_ONLY_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ # `.gte` is inclusive, so the watermark row comes back every run; append would duplicate it.+ assert schemas[name].supports_append is False++ def test_orders_offers_both_documented_cursors(self):+ orders = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == "orders")++ assert [field["field"] for field in orders.incremental_fields] == ["updated_at", "created_at"]++ def test_get_schemas_filters_by_name(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders", "charges"])++ assert {schema.name for schema in schemas} == {"orders", "charges"}++ def test_canonical_descriptions_cover_every_schema(self):+ # A renamed endpoint would silently orphan its curated descriptions and fall back to the LLM.+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)++ def test_canonical_descriptions_document_the_partition_key(self):+ for name, config in CONEKTA_ENDPOINTS.items():+ if config.partition_key:+ assert config.partition_key in CANONICAL_DESCRIPTIONS[name]["columns"]++ @pytest.mark.parametrize(+ "probe_result, expected_valid, expected_message_fragment",+ [+ ((True, 200), True, None),+ ((False, 401), False, "private key"),+ ((False, 500), False, "Could not reach"),+ ((False, None), False, "Could not reach"),+ ],+ )+ def test_validate_credentials_status_mapping(self, probe_result, expected_valid, expected_message_fragment):+ with mock.patch(API_CLIENT_PATCH) as api_client:+ api_client.validate_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_fragment is None:+ assert message is None+ else:+ assert message is not None and expected_message_fragment in message++ def test_validate_credentials_probes_the_resolved_version(self):+ with mock.patch(API_CLIENT_PATCH) as api_client:+ api_client.validate_credentials.return_value = (True, 200)++ self.source.validate_credentials(self.config, self.team_id, api_version=None)++ assert api_client.validate_credentials.call_args.args == ("key_priv", API_VERSION)++ def test_get_resumable_source_manager_is_bound_to_the_resume_dataclass(self):+ inputs = mock.MagicMock()+ inputs.job_id = "job"+ inputs.schema_id = "schema"++ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ # A manager bound to the wrong dataclass fails to deserialize its own Redis state on resume.+ assert manager._data_class is ConektaResumeConfig++ def test_source_for_pipeline_passes_the_users_incremental_selection_through(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.team_id = self.team_id+ inputs.job_id = "job"+ inputs.incremental_field = "created_at"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1676328434+ inputs.api_version = None+ manager = mock.MagicMock()++ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = api_client.conekta_source.call_args.kwargs+ assert kwargs["endpoint"] == "orders"+ assert kwargs["incremental_field"] == "created_at"+ assert kwargs["db_incremental_field_last_value"] == 1676328434+ assert kwargs["api_version"] == API_VERSION++ def test_source_for_pipeline_withholds_the_watermark_on_a_full_refresh(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "charges"+ inputs.team_id = self.team_id+ inputs.job_id = "job"+ inputs.incremental_field = None+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = 1676328434+ inputs.api_version = None++ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert api_client.conekta_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/conekta.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/conekta.pyindex 6cc137322006..cd2c3f14acbd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/conekta.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/conekta.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass ConektaSourceConfig(config.Config):- pass+ api_key: str