: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 marketo source (#73786)
Tom Owers0bee01c60918
diff --git a/frontend/public/services/marketo.png b/frontend/public/services/marketo.pngindex cc3b1b6c22b5..1b04eead22ec 100644Binary files a/frontend/public/services/marketo.png and b/frontend/public/services/marketo.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f75de6070a8b..6e011a943555 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -371,6 +371,7 @@ the row lists both.| loops | HTTP | requests + `rest_source.RESTClient` | ✅ || luma | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |+| marketo | HTTP | requests | ✅ || mem0 | HTTP | requests | ✅ || mailerlite | HTTP | requests | ✅ || mailersend | HTTP | requests | ✅ |@@ -1077,7 +1078,6 @@ doesn't conflict with concurrent PRs.- m3ter- mailtrap- mantle-- marketo- mastodon- meetup- memberfuldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketo.pyindex f934db80f4b9..f70f030242b3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/marketo.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MarketoSourceConfig(config.Config):- pass+ munchkin_id: str+ client_id: str+ client_secret: str+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.pynew file mode 100644index 000000000000..a142b2d661e7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/canonical_descriptions.py@@ -0,0 +1,177 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "leads": {+ "description": "People records in Marketo, exported through the Bulk Extract API. Columns follow your instance's lead field set, so custom fields appear alongside the standard ones.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/bulk-extract/",+ "columns": {+ "id": "Unique identifier of the lead in Marketo.",+ "email": "Email address of the lead.",+ "firstName": "First name of the lead.",+ "lastName": "Last name of the lead.",+ "company": "Company name on the lead record.",+ "title": "Job title of the lead.",+ "phone": "Phone number of the lead.",+ "country": "Country on the lead record.",+ "createdAt": "Datetime the lead was created in Marketo.",+ "updatedAt": "Datetime the lead record was last modified.",+ "leadSource": "Source the lead was acquired from.",+ "leadStatus": "Current lifecycle status of the lead.",+ "leadScore": "Numeric score assigned by your scoring campaigns.",+ "unsubscribed": "Whether the lead has unsubscribed from marketing email.",+ "unsubscribedReason": "Reason recorded when the lead unsubscribed.",+ "marketingSuspended": "Whether marketing communication to this lead is suspended.",+ "emailInvalid": "Whether Marketo has marked the email address as invalid.",+ "sfdcContactId": "Salesforce contact id linked to this lead, when CRM sync is enabled.",+ "sfdcLeadId": "Salesforce lead id linked to this lead, when CRM sync is enabled.",+ "sfdcAccountId": "Salesforce account id linked to this lead, when CRM sync is enabled.",+ },+ },+ "activities": {+ "description": "Lead activity records (email opens, clicks, form fills, page visits, score changes and more) exported through the Bulk Extract API.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/bulk-extract/",+ "columns": {+ "marketoGUID": "Globally unique identifier of the activity record.",+ "leadId": "Identifier of the lead the activity belongs to.",+ "activityDate": "Datetime the activity occurred.",+ "activityTypeId": "Identifier of the activity type, joinable to the activity_types table.",+ "campaignId": "Identifier of the campaign that produced the activity, when applicable.",+ "primaryAttributeValueId": "Identifier of the activity's primary attribute (for example the email or form involved).",+ "primaryAttributeValue": "Display value of the activity's primary attribute.",+ "attributes": "JSON encoded list of the activity's remaining attributes.",+ },+ },+ "activity_types": {+ "description": "Catalog of activity types available in your Marketo instance, including the attributes each type records.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/mapi/#tag/Activities/operation/getAllActivityTypesUsingGET",+ "columns": {+ "id": "Unique identifier of the activity type.",+ "name": "Name of the activity type.",+ "description": "Description of what the activity type records.",+ "primaryAttribute": "The attribute that primarily identifies an activity of this type.",+ "attributes": "List of additional attributes recorded for this activity type.",+ },+ },+ "campaigns": {+ "description": "Smart campaigns and trigger campaigns in your Marketo instance.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/mapi/#tag/Campaigns",+ "columns": {+ "id": "Unique identifier of the campaign.",+ "name": "Name of the campaign.",+ "description": "Description of the campaign.",+ "type": "Campaign type, either batch or trigger.",+ "programName": "Name of the program the campaign belongs to.",+ "programId": "Identifier of the program the campaign belongs to.",+ "workspaceName": "Workspace the campaign lives in.",+ "createdAt": "Datetime the campaign was created.",+ "updatedAt": "Datetime the campaign was last modified.",+ "active": "Whether a trigger campaign is currently active.",+ },+ },+ "lists": {+ "description": "Static lists defined in your Marketo instance.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/mapi/#tag/Static-Lists",+ "columns": {+ "id": "Unique identifier of the list.",+ "name": "Name of the list.",+ "description": "Description of the list.",+ "programName": "Program the list belongs to, when it is a program-local list.",+ "workspaceName": "Workspace the list lives in.",+ "createdAt": "Datetime the list was created.",+ "updatedAt": "Datetime the list was last modified.",+ },+ },+ "programs": {+ "description": "Marketing programs, the containers Marketo uses to group assets, campaigns and costs.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Programs",+ "columns": {+ "id": "Unique identifier of the program.",+ "name": "Name of the program.",+ "description": "Description of the program.",+ "type": "Program type, for example Default, Event, Email or Engagement.",+ "channel": "Channel assigned to the program.",+ "status": "Current status of the program.",+ "url": "Link to the program inside Marketo.",+ "folder": "Folder the program is stored in.",+ "workspace": "Workspace the program belongs to.",+ "createdAt": "Datetime the program was created.",+ "updatedAt": "Datetime the program was last modified.",+ "costs": "Period costs recorded against the program.",+ "tags": "Tags applied to the program.",+ },+ },+ "emails": {+ "description": "Email assets in your Marketo instance.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Emails",+ "columns": {+ "id": "Unique identifier of the email asset.",+ "name": "Name of the email.",+ "description": "Description of the email.",+ "subject": "Subject line of the email.",+ "fromName": "Sender name shown to recipients.",+ "fromEmail": "Sender address the email is sent from.",+ "replyEmail": "Reply-to address for the email.",+ "status": "Approval status of the email, either draft or approved.",+ "template": "Identifier of the email template the asset is built on.",+ "folder": "Folder the email is stored in.",+ "workspace": "Workspace the email belongs to.",+ "operational": "Whether the email is operational and therefore ignores subscription status.",+ "createdAt": "Datetime the email was created.",+ "updatedAt": "Datetime the email was last modified.",+ },+ },+ "forms": {+ "description": "Form assets used to capture leads on landing pages and external sites.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Forms",+ "columns": {+ "id": "Unique identifier of the form.",+ "name": "Name of the form.",+ "description": "Description of the form.",+ "status": "Approval status of the form, either draft or approved.",+ "locale": "Locale the form renders in.",+ "buttonLabel": "Label shown on the form's submit button.",+ "buttonLocation": "Horizontal position of the submit button.",+ "folder": "Folder the form is stored in.",+ "createdAt": "Datetime the form was created.",+ "updatedAt": "Datetime the form was last modified.",+ },+ },+ "landing_pages": {+ "description": "Landing page assets in your Marketo instance.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Landing-Pages",+ "columns": {+ "id": "Unique identifier of the landing page.",+ "name": "Name of the landing page.",+ "description": "Description of the landing page.",+ "title": "Browser title of the landing page.",+ "URL": "Public URL of the landing page.",+ "status": "Approval status of the landing page, either draft or approved.",+ "template": "Identifier of the landing page template used.",+ "folder": "Folder the landing page is stored in.",+ "workspace": "Workspace the landing page belongs to.",+ "mobileEnabled": "Whether the landing page renders a mobile view.",+ "createdAt": "Datetime the landing page was created.",+ "updatedAt": "Datetime the landing page was last modified.",+ },+ },+ "smart_campaigns": {+ "description": "Smart campaign assets, including their smart list and flow configuration.",+ "docs_url": "https://developer.adobe.com/marketo-apis/api/asset/#tag/Smart-Campaigns",+ "columns": {+ "id": "Unique identifier of the smart campaign.",+ "name": "Name of the smart campaign.",+ "description": "Description of the smart campaign.",+ "type": "Smart campaign type, either batch or trigger.",+ "status": "Current status of the smart campaign.",+ "isActive": "Whether the smart campaign is currently active.",+ "isSystem": "Whether the smart campaign is managed by Marketo rather than a user.",+ "isCommunicationLimitEnabled": "Whether the campaign respects the instance's communication limit.",+ "folder": "Folder the smart campaign is stored in.",+ "workspace": "Workspace the smart campaign belongs to.",+ "createdAt": "Datetime the smart campaign was created.",+ "updatedAt": "Datetime the smart campaign was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.pynew file mode 100644index 000000000000..5e6f367b8db5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py@@ -0,0 +1,556 @@+import io+import re+import csv+import time+import dataclasses+from collections.abc import Iterator, Mapping+from datetime import UTC, date, datetime, timedelta+from typing import IO, Any, Optional, cast++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.settings import (+ ASSET_MAX_RETURN,+ BULK_WINDOW_DAYS,+ MARKETO_ENDPOINTS,+ REST_BATCH_SIZE,+ MarketoEndpointConfig,+)++# Every Marketo instance is reachable at <munchkin id>.mktorest.com — the host is not+# customer-supplied, so there is no credential-retargeting surface here.+MARKETO_DOMAIN_SUFFIX = ".mktorest.com"+MARKETO_HOST_TEMPLATE = "https://{munchkin_id}" + MARKETO_DOMAIN_SUFFIX+MUNCHKIN_ID_PATTERN = re.compile(r"^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$")++REQUEST_TIMEOUT_SECONDS = 120+# Access tokens live an hour; re-mint a minute early so a long page fetch can't straddle expiry.+TOKEN_EXPIRY_SAFETY_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5++# Marketo asks callers to check bulk export status no more than once a minute.+BULK_POLL_INTERVAL_SECONDS = 60+BULK_MAX_POLL_ATTEMPTS = 120+BULK_CHUNK_ROWS = 2000+# Bulk lead exports name every column explicitly; keep the request body bounded on instances+# with thousands of custom fields.+MAX_LEAD_EXPORT_FIELDS = 300++DEFAULT_BULK_LOOKBACK_DAYS = 365++# Body-level codes Marketo returns with HTTP 200. These are transient: rate/concurrency limits,+# request timeouts, and "too many bulk jobs queued".+RETRYABLE_ERROR_CODES = frozenset({"604", "606", "608", "615", "1029"})+# The token went stale mid-sync — re-mint once and replay the request.+TOKEN_ERROR_CODES = frozenset({"601", "602"})+++class MarketoAPIError(Exception):+ pass+++class MarketoRetryableError(MarketoAPIError):+ pass+++class MarketoTokenError(MarketoAPIError):+ pass+++class MarketoAuthError(MarketoAPIError):+ pass+++class MarketoResumeConfig:+ """Cursor for whichever transport the endpoint uses.++ Only one of the three is populated per endpoint; they are kept on one dataclass because the+ resume manager stores a single dataclass type per source.+ """++ next_page_token: Optional[str] = None+ offset: Optional[int] = None+ window_start: Optional[str] = None+++def build_base_url(munchkin_id: str) -> str:+ munchkin = (munchkin_id or "").strip()+ # People paste the whole endpoint from Admin → Web Services, so accept that shape too.+ if munchkin.startswith("https://"):+ munchkin = munchkin[len("https://") :]+ munchkin = munchkin.rstrip("/")+ if munchkin.endswith(MARKETO_DOMAIN_SUFFIX):+ munchkin = munchkin[: -len(MARKETO_DOMAIN_SUFFIX)]+ if not MUNCHKIN_ID_PATTERN.match(munchkin):+ raise ValueError(f"Invalid Marketo Munchkin account ID: {munchkin_id!r}")+ return MARKETO_HOST_TEMPLATE.format(munchkin_id=munchkin)+++def format_datetime(value: Any) -> str:+ """Render a cursor value as the ISO 8601 instant Marketo's filters expect."""+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time())+ elif isinstance(value, str):+ return value+ else:+ return str(value)++ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def parse_datetime(value: Any) -> Optional[datetime]:+ """Best-effort parse of a stored cursor value back into an aware datetime."""+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if not isinstance(value, str) or not value.strip():+ return None+ text = value.strip().replace("Z", "+00:00")+ try:+ parsed = datetime.fromisoformat(text)+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def raise_for_marketo_errors(body: Mapping[str, Any]) -> None:+ """Marketo reports failures in a 200 body: ``{"success": false, "errors": [...]}``."""+ if body.get("success", True):+ return++ errors = body.get("errors") or []+ first = errors[0] if errors else {}+ code = str(first.get("code", ""))+ message = first.get("message", "Unknown Marketo error")+ text = f"Marketo API error {code}: {message}"++ if code in RETRYABLE_ERROR_CODES:+ raise MarketoRetryableError(text)+ if code in TOKEN_ERROR_CODES:+ raise MarketoTokenError(text)+ raise MarketoAPIError(text)+++class MarketoClient:+ """Minimal Marketo transport: one host, one client-credentials token, three request shapes."""++ def __init__(self, munchkin_id: str, client_id: str, client_secret: str) -> None:+ self._base_url = build_base_url(munchkin_id)+ self._client_id = client_id+ self._client_secret = client_secret+ # The identity endpoint takes the credentials as query params, so redact both literals+ # from tracked-transport logs and sampled bodies. capture=False keeps every Marketo+ # response — lead emails and arbitrary customer campaign/form fields the generic+ # scrubber can't recognise — out of HTTP sample storage while still metering and logging.+ self._session = make_tracked_session(redact_values=(client_id, client_secret), capture=False)+ self._token: Optional[str] = None+ self._token_expires_at: float = 0.0++ @property+ def base_url(self) -> str:+ return self._base_url++ def _redact(self, text: str) -> str:+ """Strip credential literals from text bound for logs or a persisted error."""+ for secret in (self._client_secret, self._client_id):+ if secret:+ text = text.replace(secret, "***")+ return text++ def _mint_token(self) -> str:+ try:+ response = self._session.get(+ f"{self._base_url}/identity/oauth/token",+ params={+ "grant_type": "client_credentials",+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ # Connection/timeout errors carry the prepared URL, which here embeds the client+ # secret as a query param. That string is persisted as the import's latest_error,+ # so scrub the credentials before it can leak to anyone viewing failed imports.+ raise MarketoAuthError(f"Could not reach Marketo identity endpoint: {self._redact(str(e))}") from None+ if not response.ok:+ raise MarketoAuthError(+ f"Marketo authentication failed: status={response.status_code}, body={response.text[:500]}"+ )++ body = response.json()+ token = body.get("access_token")+ if not token:+ raise MarketoAuthError(f"Marketo authentication failed: no access token in response ({body})")++ raw_expires_in = body.get("expires_in")+ expires_in = int(raw_expires_in) if raw_expires_in is not None else 3600+ self._token = token+ self._token_expires_at = time.monotonic() + max(expires_in - TOKEN_EXPIRY_SAFETY_SECONDS, 0)+ return token++ def access_token(self, force_refresh: bool = False) -> str:+ if force_refresh or self._token is None or time.monotonic() >= self._token_expires_at:+ return self._mint_token()+ return self._token++ def request(+ self,+ method: str,+ path: str,+ *,+ params: Optional[Mapping[str, Any]] = None,+ json_body: Optional[Mapping[str, Any]] = None,+ stream: bool = False,+ ) -> requests.Response:+ """Issue one request, re-minting the token once on an HTTP 401."""++ def _send(token: str) -> requests.Response:+ return self._session.request(+ method,+ f"{self._base_url}{path}",+ params=dict(params) if params else None,+ json=dict(json_body) if json_body is not None else None,+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ stream=stream,+ )++ response = _send(self.access_token())+ if response.status_code == 401:+ response = _send(self.access_token(force_refresh=True))++ if response.status_code in (401, 403):+ raise MarketoAuthError(+ f"Marketo authentication failed: status={response.status_code}, path={path}, body={response.text[:500]}"+ )+ response.raise_for_status()+ return response++ # Only body-level transient codes are retried here. HTTP-level 429/5xx retries already+ # happen inside the tracked session, so the two layers never stack.+ @retry(+ retry=retry_if_exception_type(MarketoRetryableError),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+ )+ def request_json(+ self,+ method: str,+ path: str,+ *,+ params: Optional[Mapping[str, Any]] = None,+ json_body: Optional[Mapping[str, Any]] = None,+ ) -> dict[str, Any]:+ try:+ body = self.request(method, path, params=params, json_body=json_body).json()+ raise_for_marketo_errors(body)+ except MarketoTokenError:+ # A stale token surfaces as a 200 body error rather than a 401; re-mint and replay once.+ self.access_token(force_refresh=True)+ body = self.request(method, path, params=params, json_body=json_body).json()+ raise_for_marketo_errors(body)+ return cast(dict[str, Any], body)+++def validate_credentials(munchkin_id: str, client_id: str, client_secret: str) -> tuple[bool, Optional[str]]:+ try:+ client = MarketoClient(munchkin_id, client_id, client_secret)+ except ValueError as e:+ return False, str(e)++ try:+ client.access_token(force_refresh=True)+ except MarketoAuthError:+ return False, "Invalid Marketo client ID or client secret"+ except Exception:+ return False, "Could not reach Marketo — check your Munchkin account ID"+ return True, None+++def _normalize_row(row: Mapping[Any, Any], int_columns: tuple[str, ...]) -> dict[str, Any]:+ """Blank CSV cells become NULL, and known numeric columns come back as integers."""+ normalized: dict[str, Any] = {}+ for key, value in row.items():+ # csv.DictReader files any surplus columns under a `None` key; drop them.+ if key is None:+ continue+ if value == "" or value is None:+ normalized[key] = None+ continue+ if key in int_columns and isinstance(value, str):+ try:+ normalized[key] = int(value)+ continue+ except ValueError:+ pass+ normalized[key] = value+ return normalized+++def bulk_windows(+ start: datetime, end: datetime, window_days: int = BULK_WINDOW_DAYS+) -> list[tuple[datetime, datetime]]:+ """Split [start, end) into windows Marketo's 31-day export filter cap will accept."""+ windows: list[tuple[datetime, datetime]] = []+ cursor = start+ step = timedelta(days=window_days)+ while cursor < end:+ window_end = min(cursor + step, end)+ windows.append((cursor, window_end))+ cursor = window_end+ return windows+++def _lead_export_fields(client: MarketoClient) -> list[str]:+ body = client.request_json("GET", "/rest/v1/leads/describe.json")+ names: list[str] = []+ for entry in body.get("result") or []:+ rest = entry.get("rest") or {}+ name = rest.get("name")+ if name:+ names.append(name)+ return names[:MAX_LEAD_EXPORT_FIELDS]+++def _create_bulk_export(+ client: MarketoClient,+ obj: str,+ window: tuple[datetime, datetime],+ fields: Optional[list[str]],+) -> str:+ body: dict[str, Any] = {+ "format": "CSV",+ "filter": {"createdAt": {"startAt": format_datetime(window[0]), "endAt": format_datetime(window[1])}},+ }+ if fields:+ body["fields"] = fields++ created = client.request_json("POST", f"/bulk/v1/{obj}/export/create.json", json_body=body)+ results = created.get("result") or []+ if not results or not results[0].get("exportId"):+ raise MarketoAPIError(f"Marketo bulk export create returned no export id for {obj}")+ return str(results[0]["exportId"])+++def _await_bulk_export(client: MarketoClient, obj: str, export_id: str, logger: FilteringBoundLogger) -> None:+ for _ in range(BULK_MAX_POLL_ATTEMPTS):+ # Sleep before the first poll: Marketo never completes a job instantly and polling+ # faster than once a minute is rejected.+ time.sleep(BULK_POLL_INTERVAL_SECONDS)+ body = client.request_json("GET", f"/bulk/v1/{obj}/export/{export_id}/status.json")+ results = body.get("result") or []+ status = results[0].get("status") if results else None++ if status == "Completed":+ return+ if status in ("Failed", "Cancelled"):+ reason = results[0].get("errorMsg") or "no reason given"+ raise MarketoAPIError(f"Marketo bulk export {export_id} ended as {status}: {reason}")+ logger.debug(f"Marketo bulk export {export_id} status={status}")++ raise MarketoAPIError(+ f"Marketo bulk export {export_id} did not complete within "+ f"{BULK_MAX_POLL_ATTEMPTS * BULK_POLL_INTERVAL_SECONDS} seconds"+ )+++def _download_bulk_export(+ client: MarketoClient,+ obj: str,+ export_id: str,+ int_columns: tuple[str, ...],+) -> Iterator[list[dict[str, Any]]]:+ response = client.request("GET", f"/bulk/v1/{obj}/export/{export_id}/file.json", stream=True)++ if "application/json" in (response.headers.get("Content-Type") or ""):+ # A failed download comes back as a Marketo error envelope instead of CSV.+ raise_for_marketo_errors(response.json())+ return++ response.raw.decode_content = True+ # Wrap the raw stream rather than iterating lines: exported text columns can contain+ # newlines inside quoted fields, which line-splitting would tear apart.+ stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8", newline="")+ batch: list[dict[str, Any]] = []+ for row in csv.DictReader(stream):+ batch.append(_normalize_row(row, int_columns))+ if len(batch) >= BULK_CHUNK_ROWS:+ yield batch+ batch = []+ if batch:+ yield batch+++def _bulk_rows(+ client: MarketoClient,+ config: MarketoEndpointConfig,+ start: datetime,+ end: datetime,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ fields = _lead_export_fields(client) if config.needs_field_list else None++ for window_start, window_end in bulk_windows(start, end):+ export_id = _create_bulk_export(client, config.path, (window_start, window_end), fields)+ client.request_json("POST", f"/bulk/v1/{config.path}/export/{export_id}/enqueue.json")+ _await_bulk_export(client, config.path, export_id, logger)++ yield from _download_bulk_export(client, config.path, export_id, config.int_columns)++ # Checkpoint on the window boundary only once the whole window has been yielded, so a+ # resumed attempt re-exports the window it died in rather than skipping its tail.+ resumable_source_manager.save_state(MarketoResumeConfig(window_start=format_datetime(window_end)))+++def _rest_token_rows(+ client: MarketoClient,+ config: MarketoEndpointConfig,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ start_token: Optional[str],+) -> Iterator[list[dict[str, Any]]]:+ next_token = start_token+ while True:+ params: dict[str, Any] = {"batchSize": REST_BATCH_SIZE, **config.extra_params}+ if next_token:+ params["nextPageToken"] = next_token++ body = client.request_json("GET", config.path, params=params)+ rows = body.get("result") or []+ if rows:+ yield rows++ next_token = body.get("nextPageToken")+ # `moreResult` is absent on endpoints that return everything in one shot (activity types).+ if not body.get("moreResult") or not next_token:+ break++ resumable_source_manager.save_state(MarketoResumeConfig(next_page_token=next_token))+++def _asset_offset_rows(+ client: MarketoClient,+ config: MarketoEndpointConfig,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ start_offset: int,+) -> Iterator[list[dict[str, Any]]]:+ offset = start_offset+ while True:+ params: dict[str, Any] = {"offset": offset, "maxReturn": ASSET_MAX_RETURN, **config.extra_params}+ body = client.request_json("GET", config.path, params=params)+ rows = body.get("result") or []+ if rows:+ yield rows++ # A short page is the API's end-of-collection signal; there is no total count.+ if len(rows) < ASSET_MAX_RETURN:+ break++ offset += len(rows)+ resumable_source_manager.save_state(MarketoResumeConfig(offset=offset))+++def _resume_state(+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+) -> Optional[MarketoResumeConfig]:+ if not resumable_source_manager.can_resume():+ return None+ return resumable_source_manager.load_state()+++def resolve_bulk_start(+ resume: Optional[MarketoResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ start_date: Optional[str],+ now: Optional[datetime] = None,+) -> datetime:+ """Pick where a bulk export run begins: resume cursor > incremental watermark > start date."""+ now = now or datetime.now(UTC)++ if resume is not None and resume.window_start:+ resumed = parse_datetime(resume.window_start)+ if resumed is not None:+ return resumed++ if should_use_incremental_field and db_incremental_field_last_value is not None:+ watermark = parse_datetime(db_incremental_field_last_value)+ if watermark is not None:+ return watermark++ configured = parse_datetime(start_date) if start_date else None+ return configured or now - timedelta(days=DEFAULT_BULK_LOOKBACK_DAYS)+++def get_rows(+ munchkin_id: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ start_date: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = MARKETO_ENDPOINTS[endpoint]+ client = MarketoClient(munchkin_id, client_id, client_secret)+ resume = _resume_state(resumable_source_manager)++ if config.transport == "bulk":+ start = resolve_bulk_start(resume, should_use_incremental_field, db_incremental_field_last_value, start_date)+ yield from _bulk_rows(client, config, start, datetime.now(UTC), resumable_source_manager, logger)+ elif config.transport == "asset_offset":+ start_offset = resume.offset if resume is not None and resume.offset is not None else 0+ yield from _asset_offset_rows(client, config, resumable_source_manager, start_offset)+ else:+ start_token = resume.next_page_token if resume is not None else None+ yield from _rest_token_rows(client, config, resumable_source_manager, start_token)++ resumable_source_manager.clear_state()+++def marketo_source(+ munchkin_id: str,+ client_id: str,+ client_secret: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ start_date: Optional[str] = None,+) -> SourceResponse:+ config = MARKETO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ munchkin_id=munchkin_id,+ client_id=client_id,+ client_secret=client_secret,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ start_date=start_date,+ ),+ primary_keys=config.primary_key,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.pynew file mode 100644index 000000000000..bd440619a634--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/settings.py@@ -0,0 +1,137 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Marketo splits its surface across three transports that share one host and one token:+#+# - ``rest_token``: /rest/v1 list endpoints paginated with an opaque ``nextPageToken`` and a+# ``moreResult`` flag.+# - ``asset_offset``: /rest/asset/v1 endpoints paginated with ``offset`` + ``maxReturn`` (200 max).+# - ``bulk``: the async Bulk Extract API (create -> enqueue -> poll -> download CSV). Leads and+# activities have no usable synchronous list endpoint, so they can only come this way.+MarketoTransport = Literal["rest_token", "asset_offset", "bulk"]++# Marketo caps a bulk export's date filter at 31 days; stay under it.+BULK_WINDOW_DAYS = 30+# Asset API hard cap.+ASSET_MAX_RETURN = 200+# /rest/v1 list endpoints cap batchSize at 300.+REST_BATCH_SIZE = 300+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass(frozen=True)+class MarketoEndpointConfig:+ name: str+ transport: MarketoTransport+ # For rest_token/asset_offset this is the request path. For bulk it is the export object+ # segment ("leads" / "activities") used to build /bulk/v1/<object>/export/... .+ path: str+ primary_key: list[str]+ # Set only where a real server-side timestamp filter exists (bulk exports filter on a+ # mandatory createdAt range). Asset and /rest/v1 list endpoints stay full refresh: their+ # updated-since filters are undocumented for some resources and the collections are small.+ incremental_field: Optional[str] = None+ partition_key: Optional[str] = None+ # CSV columns to coerce back to integers — bulk downloads arrive as all-string CSV.+ int_columns: tuple[str, ...] = ()+ # Bulk lead exports must name every column they want; activities have a fixed column set.+ needs_field_list: bool = False+ extra_params: dict[str, str] = field(default_factory=dict)++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if self.incremental_field is None:+ return []+ return [_datetime_field(self.incremental_field)]+++MARKETO_ENDPOINTS: dict[str, MarketoEndpointConfig] = {+ "leads": MarketoEndpointConfig(+ name="leads",+ transport="bulk",+ path="leads",+ primary_key=["id"],+ incremental_field="createdAt",+ partition_key="createdAt",+ int_columns=("id",),+ needs_field_list=True,+ ),+ "activities": MarketoEndpointConfig(+ name="activities",+ transport="bulk",+ path="activities",+ # marketoGUID is the only globally unique identifier on an activity row.+ primary_key=["marketoGUID"],+ incremental_field="activityDate",+ partition_key="activityDate",+ int_columns=("leadId", "activityTypeId", "campaignId", "primaryAttributeValueId"),+ ),+ "activity_types": MarketoEndpointConfig(+ name="activity_types",+ transport="rest_token",+ path="/rest/v1/activities/types.json",+ primary_key=["id"],+ ),+ "campaigns": MarketoEndpointConfig(+ name="campaigns",+ transport="rest_token",+ path="/rest/v1/campaigns.json",+ primary_key=["id"],+ partition_key="createdAt",+ ),+ "lists": MarketoEndpointConfig(+ name="lists",+ transport="rest_token",+ path="/rest/v1/lists.json",+ primary_key=["id"],+ partition_key="createdAt",+ ),+ # Asset API timestamps come back as "2016-02-25T18:36:58Z+0000", which is not a format the+ # datetime partitioner can parse — these stay unpartitioned. They are small collections.+ "programs": MarketoEndpointConfig(+ name="programs",+ transport="asset_offset",+ path="/rest/asset/v1/programs.json",+ primary_key=["id"],+ ),+ "emails": MarketoEndpointConfig(+ name="emails",+ transport="asset_offset",+ path="/rest/asset/v1/emails.json",+ primary_key=["id"],+ ),+ "forms": MarketoEndpointConfig(+ name="forms",+ transport="asset_offset",+ path="/rest/asset/v1/forms.json",+ primary_key=["id"],+ ),+ "landing_pages": MarketoEndpointConfig(+ name="landing_pages",+ transport="asset_offset",+ path="/rest/asset/v1/landingPages.json",+ primary_key=["id"],+ ),+ "smart_campaigns": MarketoEndpointConfig(+ name="smart_campaigns",+ transport="asset_offset",+ path="/rest/asset/v1/smartCampaigns.json",+ primary_key=["id"],+ ),+}++ENDPOINTS = tuple(MARKETO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in MARKETO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.pyindex e3fb981025e7..0554c2560506 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/source.py@@ -1,32 +1,160 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.marketo import (MarketoSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.marketo import (+ MarketoResumeConfig,+ marketo_source,+ validate_credentials as validate_marketo_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MarketoSource(SimpleSource[MarketoSourceConfig]):+class MarketoSource(ResumableSource[MarketoSourceConfig, MarketoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Marketo has shipped one REST version since launch and exposes no version selector, so the+ # `/rest/v1` path segment is not a pinnable version.+ api_docs_url = "https://developer.adobe.com/marketo-apis/api/mapi/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MARKETO+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Marketo authentication failed": "PostHog could not authenticate with Marketo. Check the client ID and secret on your Marketo custom service, and make sure the service is still active.",+ "Marketo API error 601": "Your Marketo access token is invalid. Reconnect the source with a fresh client ID and secret.",+ "Marketo API error 603": "Your Marketo custom service does not have permission for this data. Add the missing API role permissions in Marketo and try again.",+ "Marketo API error 607": "Your Marketo instance hit its daily API quota. The sync will run again once the quota resets.",+ "Invalid Marketo Munchkin account ID": "The Munchkin account ID doesn't look right. Copy it from Marketo under Admin, Web Services.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MARKETO,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Marketo",+ caption="""Connect Adobe Marketo Engage to pull your leads, activities, campaigns, and program assets into the PostHog Data warehouse.++In Marketo, open **Admin → Web Services** for your Munchkin account ID, then **Admin → LaunchPoint** to create a custom service and copy its client ID and secret. The service's API role needs read access to leads, activities, campaigns, and assets.++Leads and activities come through Marketo's Bulk Extract API, so the first sync backfills from the start date you set below.""",iconPath="/static/services/marketo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/marketo",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["adobe marketo", "marketo engage"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="munchkin_id",+ label="Munchkin account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="123-ABC-456",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024-01-01",+ secret=False,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: MarketoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: MarketoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_marketo_credentials(config.munchkin_id, config.client_id, config.client_secret)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MarketoResumeConfig]:+ return ResumableSourceManager[MarketoResumeConfig](inputs, MarketoResumeConfig)++ def source_for_pipeline(+ self,+ config: MarketoSourceConfig,+ resumable_source_manager: ResumableSourceManager[MarketoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return marketo_source(+ munchkin_id=config.munchkin_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ logger=inputs.logger,+ 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,+ start_date=config.start_date,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.pynew file mode 100644index 000000000000..1f025f5c6b9b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py@@ -0,0 +1,671 @@+import io+import json+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime+from typing import Any, Optional, cast++import pytest+from unittest import mock++import requests+from requests import Response+from requests.structures import CaseInsensitiveDict++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.marketo import (+ BULK_CHUNK_ROWS,+ MarketoAPIError,+ MarketoAuthError,+ MarketoClient,+ MarketoResumeConfig,+ MarketoRetryableError,+ MarketoTokenError,+ _bulk_rows,+ _download_bulk_export,+ _lead_export_fields,+ _normalize_row,+ build_base_url,+ bulk_windows,+ format_datetime,+ get_rows,+ marketo_source,+ parse_datetime,+ raise_for_marketo_errors,+ resolve_bulk_start,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.settings import (+ MARKETO_ENDPOINTS,+ MarketoEndpointConfig,+)++SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.marketo.marketo.make_tracked_session"++MUNCHKIN = "123-ABC-456"+++class _RawStream(io.BytesIO):+ """BytesIO that tolerates the ``decode_content`` flag urllib3 raw streams carry."""++ decode_content = False+++class FakeResumeManager(ResumableSourceManager[MarketoResumeConfig]):+ def __init__(self, state: Optional[MarketoResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[MarketoResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[MarketoResumeConfig]:+ return self.state++ def save_state(self, data: MarketoResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _response(body: Any, status: int = 200, content_type: str = "application/json") -> Response:+ response = Response()+ response.status_code = status+ response._content = json.dumps(body).encode() if not isinstance(body, bytes) else body+ response.headers = CaseInsensitiveDict({"Content-Type": content_type})+ return response+++def _csv_response(text: str) -> Response:+ response = Response()+ response.status_code = 200+ response.headers = CaseInsensitiveDict({"Content-Type": "text/csv;charset=UTF-8"})+ response.raw = _RawStream(text.encode())+ return response+++def _token_body(expires_in: int = 3600, token: str = "tok-1") -> dict[str, Any]:+ return {"access_token": token, "token_type": "bearer", "expires_in": expires_in, "scope": "[email protected]"}+++def _make_client(+ session: mock.MagicMock,+ munchkin_id: str = MUNCHKIN,+) -> MarketoClient:+ with mock.patch(SESSION_PATCH, return_value=session):+ return MarketoClient(munchkin_id, "client-id", "client-secret")+++def _session(token_bodies: Optional[list[Any]] = None, responses: Optional[list[Response]] = None) -> mock.MagicMock:+ session = mock.MagicMock()+ session.get.side_effect = [_response(body) for body in (token_bodies or [_token_body()])]+ if responses is not None:+ session.request.side_effect = responses+ return session+++def _drain(items: Iterable[Any]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for batch in cast("Iterable[Any]", items):+ rows.extend(batch)+ return rows+++class TestMarketo:+ def test_build_base_url_accepts_a_bare_munchkin_id(self) -> None:+ assert build_base_url(MUNCHKIN) == "https://123-ABC-456.mktorest.com"++ @pytest.mark.parametrize(+ "raw",+ [" 123-ABC-456 ", "https://123-ABC-456.mktorest.com", "123-ABC-456.mktorest.com", "123-ABC-456/"],+ )+ def test_build_base_url_normalizes_pasted_endpoints(self, raw: str) -> None:+ assert build_base_url(raw) == "https://123-ABC-456.mktorest.com"++ @pytest.mark.parametrize("raw", ["", "123 ABC", "evil.com/../x", "123_ABC", "https://evil.com@marketo"])+ def test_build_base_url_rejects_anything_that_is_not_a_munchkin_id(self, raw: str) -> None:+ # The host template is fixed, so a bad id must fail loudly rather than build a weird host.+ with pytest.raises(ValueError):+ build_base_url(raw)++ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2024, 3, 1, 12, 30, tzinfo=UTC), "2024-03-01T12:30:00Z"),+ (datetime(2024, 3, 1, 12, 30), "2024-03-01T12:30:00Z"),+ ("2024-03-01T12:30:00Z", "2024-03-01T12:30:00Z"),+ ],+ )+ def test_format_datetime(self, value: Any, expected: str) -> None:+ assert format_datetime(value) == expected++ @pytest.mark.parametrize(+ "value,expected",+ [+ ("2024-03-01T12:30:00Z", datetime(2024, 3, 1, 12, 30, tzinfo=UTC)),+ ("2024-03-01", datetime(2024, 3, 1, tzinfo=UTC)),+ (datetime(2024, 3, 1, tzinfo=UTC), datetime(2024, 3, 1, tzinfo=UTC)),+ ("not a date", None),+ ("", None),+ (None, None),+ ],+ )+ def test_parse_datetime(self, value: Any, expected: Optional[datetime]) -> None:+ assert parse_datetime(value) == expected++ def test_success_body_raises_nothing(self) -> None:+ raise_for_marketo_errors({"success": True, "result": []})++ @pytest.mark.parametrize(+ "code,expected",+ [+ ("606", MarketoRetryableError),+ ("615", MarketoRetryableError),+ ("1029", MarketoRetryableError),+ ("604", MarketoRetryableError),+ ("601", MarketoTokenError),+ ("602", MarketoTokenError),+ ("603", MarketoAPIError),+ ("607", MarketoAPIError),+ ("1003", MarketoAPIError),+ ],+ )+ def test_error_codes_are_classified_by_whether_retrying_can_help(+ self, code: str, expected: type[Exception]+ ) -> None:+ with pytest.raises(expected) as excinfo:+ raise_for_marketo_errors({"success": False, "errors": [{"code": code, "message": "boom"}]})+ assert f"Marketo API error {code}" in str(excinfo.value)++ def test_retryable_and_token_errors_stay_distinct_from_the_generic_error(self) -> None:+ # 603 must not be treated as retryable — get_non_retryable_errors keys off its message.+ with pytest.raises(MarketoAPIError) as excinfo:+ raise_for_marketo_errors({"success": False, "errors": [{"code": "603", "message": "Access denied"}]})+ assert not isinstance(excinfo.value, MarketoRetryableError | MarketoTokenError)++ def test_token_is_minted_once_and_reused_across_requests(self) -> None:+ session = _session(responses=[_response({"success": True, "result": []})] * 2)+ client = _make_client(session)++ client.request_json("GET", "/rest/v1/campaigns.json")+ client.request_json("GET", "/rest/v1/lists.json")++ assert session.get.call_count == 1+ assert session.request.call_args.kwargs["headers"]["Authorization"] == "Bearer tok-1"++ def test_expired_token_is_reminted_before_the_next_request(self) -> None:+ # expires_in below the safety margin means the cached token is never considered fresh.+ session = _session(+ token_bodies=[_token_body(expires_in=0, token="tok-1"), _token_body(expires_in=0, token="tok-2")],+ responses=[_response({"success": True, "result": []})] * 2,+ )+ client = _make_client(session)++ client.request_json("GET", "/rest/v1/campaigns.json")+ client.request_json("GET", "/rest/v1/lists.json")++ assert session.get.call_count == 2+ assert session.request.call_args.kwargs["headers"]["Authorization"] == "Bearer tok-2"++ def test_http_401_remints_the_token_and_replays_the_request(self) -> None:+ session = _session(+ token_bodies=[_token_body(token="tok-1"), _token_body(token="tok-2")],+ responses=[_response({}, status=401), _response({"success": True, "result": [{"id": 1}]})],+ )+ client = _make_client(session)++ body = client.request_json("GET", "/rest/v1/campaigns.json")++ assert body["result"] == [{"id": 1}]+ assert session.request.call_args.kwargs["headers"]["Authorization"] == "Bearer tok-2"++ def test_persistent_401_surfaces_as_an_auth_error(self) -> None:+ session = _session(+ token_bodies=[_token_body(token="tok-1"), _token_body(token="tok-2")],+ responses=[_response({}, status=401), _response({}, status=401)],+ )+ client = _make_client(session)++ with pytest.raises(MarketoAuthError):+ client.request_json("GET", "/rest/v1/campaigns.json")++ def test_body_level_token_error_remints_and_replays_once(self) -> None:+ session = _session(+ token_bodies=[_token_body(token="tok-1"), _token_body(token="tok-2")],+ responses=[+ _response({"success": False, "errors": [{"code": "602", "message": "Access token expired"}]}),+ _response({"success": True, "result": [{"id": 7}]}),+ ],+ )+ client = _make_client(session)++ assert client.request_json("GET", "/rest/v1/campaigns.json")["result"] == [{"id": 7}]+ assert session.get.call_count == 2++ def test_token_error_that_survives_a_remint_is_raised(self) -> None:+ expired = {"success": False, "errors": [{"code": "601", "message": "Access token invalid"}]}+ session = _session(+ token_bodies=[_token_body(token="tok-1"), _token_body(token="tok-2")],+ responses=[_response(expired), _response(expired)],+ )+ client = _make_client(session)++ with pytest.raises(MarketoTokenError):+ client.request_json("GET", "/rest/v1/campaigns.json")++ def test_identity_endpoint_failure_is_an_auth_error(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = [_response({"error": "invalid_client"}, status=401)]+ client = _make_client(session)++ with pytest.raises(MarketoAuthError):+ client.access_token()++ def test_transport_error_while_minting_a_token_redacts_credentials(self) -> None:+ # A connection/timeout error carries the prepared URL, which embeds the credentials as+ # query params; that string is persisted as the import's latest_error, so both literals+ # must be scrubbed before the error escapes.+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError(+ "Max retries exceeded with url: /identity/oauth/token?client_id=client-id&client_secret=client-secret"+ )+ client = _make_client(session)++ with pytest.raises(MarketoAuthError) as excinfo:+ client.access_token()++ message = str(excinfo.value)+ assert "client-secret" not in message+ assert "client-id" not in message++ def test_session_is_built_without_http_sample_capture(self) -> None:+ # Marketo responses carry lead emails and arbitrary customer fields the generic scrubber+ # can't recognise, so they must never reach HTTP sample storage.+ with mock.patch(SESSION_PATCH) as session_factory:+ MarketoClient(MUNCHKIN, "client-id", "client-secret")++ assert session_factory.call_args.kwargs["capture"] is False+ assert session_factory.call_args.kwargs["redact_values"] == ("client-id", "client-secret")++ @pytest.mark.parametrize(+ "token_body,status,expected_ok",+ [+ (_token_body(), 200, True),+ ({"error": "invalid_client"}, 401, False),+ ],+ )+ def test_validate_credentials_maps_the_identity_probe(+ self, token_body: dict[str, Any], status: int, expected_ok: bool+ ) -> None:+ session = mock.MagicMock()+ session.get.side_effect = [_response(token_body, status=status)]+ with mock.patch(SESSION_PATCH, return_value=session):+ ok, message = validate_credentials(MUNCHKIN, "client-id", "client-secret")++ assert ok is expected_ok+ assert (message is None) is expected_ok++ def test_validate_credentials_rejects_a_malformed_munchkin_id_without_a_request(self) -> None:+ with mock.patch(SESSION_PATCH) as session_factory:+ ok, message = validate_credentials("not a munchkin", "client-id", "client-secret")++ assert ok is False+ assert message is not None and "Munchkin" in message+ session_factory.assert_not_called()++ def test_token_paging_walks_until_more_result_is_false(self) -> None:+ session = _session(+ responses=[+ _response({"success": True, "result": [{"id": 1}], "nextPageToken": "t2", "moreResult": True}),+ _response({"success": True, "result": [{"id": 2}], "nextPageToken": "t3", "moreResult": False}),+ ]+ )+ manager = FakeResumeManager()++ with mock.patch(SESSION_PATCH, return_value=session):+ rows = _drain(get_rows(MUNCHKIN, "cid", "secret", "campaigns", manager, mock.MagicMock()))++ assert rows == [{"id": 1}, {"id": 2}]+ assert [state.next_page_token for state in manager.saved] == ["t2"]+ assert manager.cleared is True++ def test_token_paging_stops_when_the_api_omits_more_result(self) -> None:+ # Activity types return everything in one response with no `moreResult` flag.+ session = _session(responses=[_response({"success": True, "result": [{"id": 1}], "nextPageToken": "t2"})])+ manager = FakeResumeManager()++ with mock.patch(SESSION_PATCH, return_value=session):+ rows = _drain(get_rows(MUNCHKIN, "cid", "secret", "activity_types", manager, mock.MagicMock()))++ assert rows == [{"id": 1}]+ assert manager.saved == []++ def test_token_paging_resumes_from_saved_state(self) -> None:+ session = _session(responses=[_response({"success": True, "result": [{"id": 9}], "moreResult": False})])+ manager = FakeResumeManager(MarketoResumeConfig(next_page_token="saved-token"))++ with mock.patch(SESSION_PATCH, return_value=session):+ _drain(get_rows(MUNCHKIN, "cid", "secret", "campaigns", manager, mock.MagicMock()))++ assert session.request.call_args.kwargs["params"]["nextPageToken"] == "saved-token"++ def test_offset_paging_stops_on_the_first_short_page(self) -> None:+ full_page = [{"id": index} for index in range(200)]+ session = _session(+ responses=[+ _response({"success": True, "result": full_page}),+ _response({"success": True, "result": [{"id": 999}]}),+ ]+ )+ manager = FakeResumeManager()++ with mock.patch(SESSION_PATCH, return_value=session):+ rows = _drain(get_rows(MUNCHKIN, "cid", "secret", "programs", manager, mock.MagicMock()))++ assert len(rows) == 201+ assert [call.kwargs["params"]["offset"] for call in session.request.call_args_list] == [0, 200]+ assert [state.offset for state in manager.saved] == [200]++ def test_offset_paging_stops_on_an_empty_result(self) -> None:+ session = _session(responses=[_response({"success": True})])+ manager = FakeResumeManager()++ with mock.patch(SESSION_PATCH, return_value=session):+ rows = _drain(get_rows(MUNCHKIN, "cid", "secret", "emails", manager, mock.MagicMock()))++ assert rows == []+ assert session.request.call_count == 1++ def test_offset_paging_resumes_from_saved_state(self) -> None:+ session = _session(responses=[_response({"success": True, "result": [{"id": 1}]})])+ manager = FakeResumeManager(MarketoResumeConfig(offset=400))++ with mock.patch(SESSION_PATCH, return_value=session):+ _drain(get_rows(MUNCHKIN, "cid", "secret", "forms", manager, mock.MagicMock()))++ assert session.request.call_args.kwargs["params"]["offset"] == 400++ @pytest.mark.parametrize(+ "start,end,expected",+ [+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 20, tzinfo=UTC), 1),+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 3, 1, tzinfo=UTC), 2),+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 1, tzinfo=UTC), 0),+ (datetime(2024, 2, 1, tzinfo=UTC), datetime(2024, 1, 1, tzinfo=UTC), 0),+ ],+ )+ def test_bulk_windows_respect_marketos_31_day_filter_cap(+ self, start: datetime, end: datetime, expected: int+ ) -> None:+ windows = bulk_windows(start, end)++ assert len(windows) == expected+ assert all((window_end - window_start).days <= 30 for window_start, window_end in windows)+ if windows:+ assert windows[0][0] == start+ assert windows[-1][1] == end++ @pytest.mark.parametrize(+ "resume,incremental,last_value,start_date,expected",+ [+ (+ MarketoResumeConfig(window_start="2024-06-01T00:00:00Z"),+ True,+ "2024-01-01T00:00:00Z",+ "2023-01-01",+ datetime(2024, 6, 1, tzinfo=UTC),+ ),+ (None, True, "2024-01-01T00:00:00Z", "2023-01-01", datetime(2024, 1, 1, tzinfo=UTC)),+ (None, False, "2024-01-01T00:00:00Z", "2023-01-01", datetime(2023, 1, 1, tzinfo=UTC)),+ (None, True, None, "2023-01-01", datetime(2023, 1, 1, tzinfo=UTC)),+ ],+ )+ def test_bulk_start_prefers_resume_then_watermark_then_start_date(+ self,+ resume: Optional[MarketoResumeConfig],+ incremental: bool,+ last_value: Optional[str],+ start_date: Optional[str],+ expected: datetime,+ ) -> None:+ assert resolve_bulk_start(resume, incremental, last_value, start_date) == expected++ def test_bulk_start_falls_back_to_a_lookback_when_nothing_is_configured(self) -> None:+ now = datetime(2024, 6, 1, tzinfo=UTC)++ resolved = resolve_bulk_start(None, False, None, None, now=now)++ assert resolved < now+ assert (now - resolved).days == 365++ def test_bulk_export_runs_create_enqueue_poll_download_per_window(self) -> None:+ csv_text = "marketoGUID,leadId,activityDate,activityTypeId\nabc,7,2024-01-02T00:00:00Z,1\n"+ session = _session(+ responses=[+ _response({"success": True, "result": [{"exportId": "exp-1", "status": "Created"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1", "status": "Queued"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1", "status": "Processing"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1", "status": "Completed"}]}),+ _csv_response(csv_text),+ ]+ )+ manager = FakeResumeManager()+ client = _make_client(session)++ with mock.patch("time.sleep") as sleep:+ rows = _drain(+ _bulk_rows(+ client,+ MARKETO_ENDPOINTS["activities"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 10, tzinfo=UTC),+ manager,+ mock.MagicMock(),+ )+ )++ base = f"https://{MUNCHKIN}.mktorest.com"+ paths = [call.args[1].removeprefix(base) for call in session.request.call_args_list]+ assert paths == [+ "/bulk/v1/activities/export/create.json",+ "/bulk/v1/activities/export/exp-1/enqueue.json",+ "/bulk/v1/activities/export/exp-1/status.json",+ "/bulk/v1/activities/export/exp-1/status.json",+ "/bulk/v1/activities/export/exp-1/file.json",+ ]+ assert rows == [+ {"marketoGUID": "abc", "leadId": 7, "activityDate": "2024-01-02T00:00:00Z", "activityTypeId": 1}+ ]+ # Marketo rejects polling faster than once a minute, so every poll waits first.+ assert sleep.call_count == 2+ assert [state.window_start for state in manager.saved] == ["2024-01-10T00:00:00Z"]++ def test_bulk_export_filters_on_the_window_boundaries(self) -> None:+ session = _session(+ responses=[+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"status": "Completed"}]}),+ _csv_response("marketoGUID\n"),+ ]+ )+ client = _make_client(session)++ with mock.patch("time.sleep"):+ _drain(+ _bulk_rows(+ client,+ MARKETO_ENDPOINTS["activities"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 5, tzinfo=UTC),+ FakeResumeManager(),+ mock.MagicMock(),+ )+ )++ create_body = session.request.call_args_list[0].kwargs["json"]+ assert create_body["format"] == "CSV"+ assert create_body["filter"]["createdAt"] == {+ "startAt": "2024-01-01T00:00:00Z",+ "endAt": "2024-01-05T00:00:00Z",+ }++ def test_bulk_lead_export_names_every_column_from_describe(self) -> None:+ describe = {+ "success": True,+ "result": [+ {"id": 1, "rest": {"name": "id"}},+ {"id": 2, "rest": {"name": "email"}},+ {"id": 3, "soap": {"name": "OnlySoap"}},+ ],+ }+ session = _session(+ responses=[+ _response(describe),+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"status": "Completed"}]}),+ _csv_response("id,email\n5,[email protected]\n"),+ ]+ )+ client = _make_client(session)++ with mock.patch("time.sleep"):+ rows = _drain(+ _bulk_rows(+ client,+ MARKETO_ENDPOINTS["leads"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 5, tzinfo=UTC),+ FakeResumeManager(),+ mock.MagicMock(),+ )+ )++ assert session.request.call_args_list[1].kwargs["json"]["fields"] == ["id", "email"]+ assert rows == [{"id": 5, "email": "[email protected]"}]++ def test_lead_export_fields_skip_entries_without_a_rest_name(self) -> None:+ session = _session(+ responses=[_response({"success": True, "result": [{"rest": {"name": "id"}}, {"soap": {"name": "x"}}, {}]})]+ )++ assert _lead_export_fields(_make_client(session)) == ["id"]++ @pytest.mark.parametrize("status", ["Failed", "Cancelled"])+ def test_a_terminal_export_status_fails_the_sync(self, status: str) -> None:+ session = _session(+ responses=[+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"exportId": "exp-1"}]}),+ _response({"success": True, "result": [{"status": status, "errorMsg": "too much data"}]}),+ ]+ )+ client = _make_client(session)++ with mock.patch("time.sleep"), pytest.raises(MarketoAPIError) as excinfo:+ _drain(+ _bulk_rows(+ client,+ MARKETO_ENDPOINTS["activities"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 5, tzinfo=UTC),+ FakeResumeManager(),+ mock.MagicMock(),+ )+ )++ assert status in str(excinfo.value)+ assert "too much data" in str(excinfo.value)++ def test_a_create_response_without_an_export_id_fails_the_sync(self) -> None:+ session = _session(responses=[_response({"success": True, "result": []})])+ client = _make_client(session)++ with pytest.raises(MarketoAPIError):+ _drain(+ _bulk_rows(+ client,+ MARKETO_ENDPOINTS["activities"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 5, tzinfo=UTC),+ FakeResumeManager(),+ mock.MagicMock(),+ )+ )++ def test_a_json_error_envelope_on_the_download_is_raised_not_parsed_as_csv(self) -> None:+ client = mock.MagicMock()+ client.request.return_value = _response(+ {"success": False, "errors": [{"code": "1003", "message": "Export not ready"}]}+ )++ with pytest.raises(MarketoAPIError):+ list(_download_bulk_export(client, "leads", "exp-1", ()))++ def test_download_keeps_newlines_inside_quoted_csv_fields(self) -> None:+ client = mock.MagicMock()+ client.request.return_value = _csv_response('id,notes\n1,"line one\nline two"\n')++ rows = _drain(_download_bulk_export(client, "leads", "exp-1", ("id",)))++ assert rows == [{"id": 1, "notes": "line one\nline two"}]++ def test_download_batches_large_exports(self) -> None:+ row_count = BULK_CHUNK_ROWS + 5+ body = "id\n" + "".join(f"{index}\n" for index in range(row_count))+ client = mock.MagicMock()+ client.request.return_value = _csv_response(body)++ batches = list(_download_bulk_export(client, "leads", "exp-1", ("id",)))++ assert [len(batch) for batch in batches] == [BULK_CHUNK_ROWS, 5]++ @pytest.mark.parametrize(+ "row,int_columns,expected",+ [+ ({"id": "42"}, ("id",), {"id": 42}),+ ({"id": ""}, ("id",), {"id": None}),+ ({"id": "not-a-number"}, ("id",), {"id": "not-a-number"}),+ ({"email": "[email protected]"}, ("id",), {"email": "[email protected]"}),+ ({None: ["overflow"]}, (), {}),+ ],+ )+ def test_normalize_row(self, row: dict[Any, Any], int_columns: tuple[str, ...], expected: dict[str, Any]) -> None:+ assert _normalize_row(row, int_columns) == expected++ @pytest.mark.parametrize("endpoint", sorted(MARKETO_ENDPOINTS))+ def test_source_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:+ config: MarketoEndpointConfig = MARKETO_ENDPOINTS[endpoint]++ response = marketo_source(MUNCHKIN, "cid", "secret", endpoint, FakeResumeManager(), mock.MagicMock())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_key+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_source_response_items_are_lazy(self) -> None:+ # Building the SourceResponse must not touch the network — the pipeline calls items().+ with mock.patch(SESSION_PATCH) as session_factory:+ marketo_source(MUNCHKIN, "cid", "secret", "campaigns", FakeResumeManager(), mock.MagicMock())++ session_factory.assert_not_called()++ def test_resume_state_is_cleared_only_after_the_endpoint_is_walked(self) -> None:+ session = _session(responses=[_response({"success": True, "result": [{"id": 1}], "moreResult": False})])+ manager = FakeResumeManager()++ with mock.patch(SESSION_PATCH, return_value=session):+ iterator: Iterator[Any] = get_rows(MUNCHKIN, "cid", "secret", "lists", manager, mock.MagicMock())+ next(iterator)+ assert manager.cleared is False+ _drain(iterator)++ assert manager.cleared is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo_source.pynew file mode 100644index 000000000000..6500c8bc73f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo_source.py@@ -0,0 +1,194 @@+from typing import Any, Optional++import pytest+from unittest import mock++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.marketo import (+ MarketoSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.marketo import MarketoResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.settings import (+ ENDPOINTS,+ MARKETO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.marketo.source import MarketoSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.marketo.source.validate_marketo_credentials"+)+SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.marketo.source.marketo_source"++INCREMENTAL_ENDPOINTS = sorted(name for name, c in MARKETO_ENDPOINTS.items() if c.incremental_field)+FULL_REFRESH_ENDPOINTS = sorted(name for name, c in MARKETO_ENDPOINTS.items() if not c.incremental_field)+++def _make_inputs(schema_name: str = "leads", **overrides: Any) -> mock.MagicMock:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "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 mock.MagicMock(**defaults)+++class TestMarketoSource:+ def setup_method(self) -> None:+ self.source = MarketoSource()+ self.team_id = 123+ self.config = MarketoSourceConfig(+ munchkin_id="123-ABC-456",+ client_id="client-id",+ client_secret="client-secret",+ start_date="2024-01-01",+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.MARKETO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Marketo"+ assert config.label == "Marketo"+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/marketo.png"++ @pytest.mark.parametrize(+ "name,required,secret",+ [+ ("munchkin_id", True, False),+ ("client_id", True, False),+ ("client_secret", True, True),+ ("start_date", False, False),+ ],+ )+ def test_source_fields(self, name: str, required: bool, secret: bool) -> None:+ fields = {+ field.name: field+ for field in self.source.get_source_config.fields+ if isinstance(field, SourceFieldInputConfig)+ }++ assert len(fields) == 4+ assert fields[name].required is required+ assert bool(fields[name].secret) is secret++ def test_api_docs_url_and_public_table_listing(self) -> None:+ assert self.source.api_docs_url is not None+ assert self.source.api_docs_url.startswith("https://")+ # get_schemas iterates a static catalog with no I/O, so the docs can render the tables.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_returns_the_whole_endpoint_catalog(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert sorted(schema.name for schema in schemas) == sorted(ENDPOINTS)++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["leads", "campaigns"])++ assert sorted(schema.name for schema in schemas) == ["campaigns", "leads"]++ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)+ def test_bulk_endpoints_advertise_their_server_side_filter(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is True+ assert [field["field"] for field in schema.incremental_fields] == [+ MARKETO_ENDPOINTS[endpoint].incremental_field+ ]++ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)+ def test_endpoints_without_a_server_side_filter_are_full_refresh(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ @pytest.mark.parametrize(+ "probe_result,expected",+ [+ ((True, None), (True, None)),+ (+ (False, "Invalid Marketo client ID or client secret"),+ (False, "Invalid Marketo client ID or client secret"),+ ),+ ],+ )+ def test_validate_credentials_passes_the_probe_result_through(+ self, probe_result: tuple[bool, Optional[str]], expected: tuple[bool, Optional[str]]+ ) -> None:+ with mock.patch(VALIDATE_PATCH, return_value=probe_result) as probe:+ assert self.source.validate_credentials(self.config, self.team_id) == expected++ probe.assert_called_once_with("123-ABC-456", "client-id", "client-secret")++ def test_get_resumable_source_manager_is_bound_to_the_marketo_cursor(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MarketoResumeConfig++ def test_source_for_pipeline_plumbs_config_and_inputs(self) -> None:+ inputs = _make_inputs(+ schema_name="activities",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-05-01T00:00:00Z",+ )+ manager = mock.MagicMock()++ with mock.patch(SOURCE_PATCH) as marketo_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = marketo_source.call_args.kwargs+ assert kwargs["munchkin_id"] == "123-ABC-456"+ assert kwargs["client_id"] == "client-id"+ assert kwargs["client_secret"] == "client-secret"+ assert kwargs["endpoint"] == "activities"+ assert kwargs["start_date"] == "2024-01-01"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_drops_a_stale_watermark_on_a_full_refresh(self) -> None:+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2024-05-01T00:00:00Z",+ )++ with mock.patch(SOURCE_PATCH) as marketo_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert marketo_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_are_keyed_by_endpoint_name(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) <= set(ENDPOINTS)+ assert set(descriptions) == set(ENDPOINTS)+ assert all(entry.get("description") for entry in descriptions.values())++ @pytest.mark.parametrize(+ "error_key",+ ["Marketo authentication failed", "Marketo API error 601", "Marketo API error 603", "Marketo API error 607"],+ )+ def test_permanent_failures_disable_the_source_instead_of_retrying(self, error_key: str) -> None:+ errors = self.source.get_non_retryable_errors()++ assert errors[error_key]