: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 nocrm import source (#67804)
Tom Owers9927ab17136b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a7b82982ebcc..ce57de2d5f69 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -210,6 +210,7 @@ the row lists both.| mysql | DB protocol | pymysql | ➖ || new_york_times | HTTP | requests | ✅ || okta | HTTP | requests | ✅ |+| nocrm | HTTP | requests | ✅ || northpass_lms | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |@@ -533,6 +534,7 @@ doesn't conflict with concurrent PRs.- nexiopay- ninjaone_rmm- nocrm+- northpass_lms- nutshell- nylas- oncehubdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 56dfb79aaada..49f5a9bc6a6c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2158,7 +2158,8 @@ class NinjaOneRMMSourceConfig(config.Config):@config.configclass NoCRMSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/canonical_descriptions.pynew file mode 100644index 000000000000..8b8877d203e2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/canonical_descriptions.py@@ -0,0 +1,124 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the noCRM.io v2 API reference (https://www.nocrm.io/api). Partial coverage is+# fine — anything omitted falls back to LLM enrichment using the docs_url and column data types.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "leads": {+ "description": "Sales leads (opportunities) tracked in noCRM.io, including their pipeline step, status and value.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the lead.",+ "title": "Title of the lead.",+ "description": "Free-text description of the lead.",+ "html_description": "HTML-rendered description of the lead.",+ "status": "Lead status: one of todo, standby, won, lost or cancelled.",+ "pipeline": "Name of the pipeline the lead belongs to.",+ "step": "Name of the current pipeline step.",+ "step_id": "Identifier of the current pipeline step.",+ "amount": "Monetary value of the lead.",+ "amount_percentage": "Weighted amount as a percentage.",+ "probalized_amount": "Amount weighted by win probability.",+ "probability": "Estimated win probability (percent).",+ "currency": "Currency code for the lead's amount.",+ "starred": "Whether the lead is starred/flagged.",+ "tags": "List of tags applied to the lead.",+ "created_from": "How the lead was created (e.g. manual, api, form).",+ "attachment_count": "Number of attachments on the lead.",+ "next_action_at": "Timestamp of the next scheduled action.",+ "remind_date": "Date of the next reminder.",+ "remind_time": "Time of the next reminder.",+ "estimated_closing_date": "Expected date the lead will close.",+ "closed_at": "Timestamp the lead was closed (won/lost/cancelled).",+ "created_at": "Timestamp the lead was created.",+ "updated_at": "Timestamp the lead was last updated.",+ "created_by_id": "Identifier of the user who created the lead.",+ "user_id": "Identifier of the user the lead is assigned to.",+ "client_folder_id": "Identifier of the client folder the lead belongs to.",+ "client_folder_name": "Name of the client folder the lead belongs to.",+ "team_id": "Identifier of the team the lead belongs to.",+ "team_name": "Name of the team the lead belongs to.",+ },+ },+ "activities": {+ "description": "Activity types configured for the account, used to categorise lead activity.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the activity type.",+ "name": "Name of the activity type.",+ "icon": "Icon associated with the activity type.",+ "color": "Colour associated with the activity type.",+ "kind": "Kind/category of the activity type.",+ "parent_id": "Identifier of the parent activity type, if any.",+ "is_disabled": "Whether the activity type is disabled.",+ "position": "Display order position.",+ },+ },+ "users": {+ "description": "Users belonging to the noCRM.io account.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the user.",+ "email": "Email address of the user.",+ "team_id": "Identifier of the team the user belongs to.",+ },+ },+ "teams": {+ "description": "Teams configured in the noCRM.io account.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the team.",+ "name": "Name of the team.",+ },+ },+ "steps": {+ "description": "Pipeline steps (stages) a lead can move through.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the step.",+ "name": "Name of the step.",+ },+ },+ "pipelines": {+ "description": "Sales pipelines configured in the account.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the pipeline.",+ "name": "Name of the pipeline.",+ },+ },+ "client_folders": {+ "description": "Client folders that group leads by account/company.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the client folder.",+ "name": "Name of the client folder.",+ },+ },+ "categories": {+ "description": "Categories used to classify client folders.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the category.",+ "name": "Name of the category.",+ },+ },+ "tags": {+ "description": "Predefined tags that can be applied to leads.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the tag.",+ "name": "Name of the tag.",+ },+ },+ "fields": {+ "description": "Custom field definitions configured for leads and client folders.",+ "docs_url": "https://www.nocrm.io/api",+ "columns": {+ "id": "Unique identifier for the custom field.",+ "name": "Name of the custom field.",+ "type": "Data type of the custom field.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/nocrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/nocrm.pynew file mode 100644index 000000000000..9ef27428b7c0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/nocrm.py@@ -0,0 +1,269 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.nocrm.settings import (+ NOCRM_ENDPOINTS,+ NoCRMEndpointConfig,+)++# noCRM caps `/leads` at a default of 100 per page; request the max to minimise round-trips against+# the low (~2000 req/day) account quota.+PAGE_SIZE = 100++REQUEST_TIMEOUT_SECONDS = 60++# noCRM hosts every account under `<subdomain>.nocrm.io`. Only the subdomain label is user-supplied,+# so restrict it to the DNS-label charset — this keeps a crafted value from breaking out of the+# `.nocrm.io` origin and pointing the authenticated request somewhere else (SSRF).+_SUBDOMAIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")+++class NoCRMRetryableError(Exception):+ pass+++class NoCRMConfigError(Exception):+ """The connector config is malformed (e.g. an invalid subdomain) and can never succeed."""+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce whatever the user typed to a bare, validated noCRM subdomain label.++ Accepts a bare label (`acme`) or a full host/URL (`acme.nocrm.io`, `https://acme.nocrm.io/`) and+ returns just `acme`. Raises `NoCRMConfigError` when nothing valid remains, so we never build a+ request URL around an attacker-controlled host.+ """+ value = (subdomain or "").strip().lower()+ # Strip scheme and any path if the user pasted a full URL.+ value = re.sub(r"^https?://", "", value)+ value = value.split("/")[0]+ # Strip the shared apex domain if present, leaving just the account label.+ value = value.removesuffix(".nocrm.io")+ if not _SUBDOMAIN_RE.match(value):+ raise NoCRMConfigError(+ "Invalid noCRM subdomain. Enter just your account's subdomain, e.g. 'acme' for acme.nocrm.io."+ )+ return value+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.nocrm.io/api/v2"+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "X-API-KEY": api_key,+ "Accept": "application/json",+ }+++def _format_updated_after(value: Any) -> str:+ """Format an incremental cursor as the ISO 8601 UTC string noCRM's `updated_after` expects."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime/date cursor at now.++ If bad source data pushes the `updated_at` cursor past now, every later sync would ask noCRM for+ changes since a future date and get nothing back, wedging the table until real data catches up.+ Asking for changes newer than now is a no-op anyway, so clamping lets the sync self-heal.+ """+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ return value+++def _build_base_params(+ config: NoCRMEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ """Query params shared by every page of a sync (everything except limit/offset)."""+ params: dict[str, Any] = {}++ if config.default_sort_order:+ params["order"] = config.default_sort_order+ params["direction"] = "asc"++ if (+ config.supports_incremental+ and config.incremental_param+ and should_use_incremental_field+ and db_incremental_field_last_value is not None+ ):+ params[config.incremental_param] = _format_updated_after(+ _clamp_future_value_to_now(db_incremental_field_last_value)+ )+ # Sort ascending by the changed field so pages arrive in the order the `asc` watermark expects.+ if config.incremental_sort_order:+ params["order"] = config.incremental_sort_order+ params["direction"] = "asc"++ return params+++class NoCRMResumeConfig:+ # Offset (row count already consumed) to resume limit/offset pagination from. The incremental+ # window is recomputed from the job's stable last-value, so only the offset needs persisting.+ offset: int = 0+++@retry(+ retry=retry_if_exception_type((NoCRMRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> tuple[list[dict], int | None]:+ """Fetch one page, returning the row list and the `X-TOTAL-COUNT` total when the header is present.++ noCRM list endpoints return a bare JSON array. Over-quota (429) and transient 5xx are retried;+ on 429 noCRM sends `API-RETRY-AFTER`, but tenacity's exponential backoff is a safe fallback that+ keeps us well under the daily cap without parsing the header.+ """+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise NoCRMRetryableError(f"noCRM API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"noCRM API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ body = response.json()+ # List endpoints return a bare array; be defensive about a wrapped object just in case.+ items = body if isinstance(body, list) else body.get("data", [])++ total_header = response.headers.get("X-TOTAL-COUNT")+ total = int(total_header) if total_header is not None and total_header.isdigit() else None++ return items, total+++def get_rows(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NoCRMResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict]]:+ config = NOCRM_ENDPOINTS[endpoint]+ base_url = _base_url(subdomain)+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values`+ # masks the API key in logged URLs and captured samples. `allow_redirects=False` stops a redirect+ # from sending the key to another host. `retry=Retry(total=0)` disables the adapter's own retries+ # so they don't stack on top of the tenacity retry in `_fetch_page`.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, retry=Retry(total=0))++ base_params = _build_base_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume is not None else 0++ # Guards against an endpoint that ignores `offset` and re-serves the first page forever: if a page+ # leads with the same id we already saw, pagination isn't advancing, so stop.+ previous_first_id: Any = None++ while True:+ params = {**base_params, "limit": PAGE_SIZE, "offset": offset}+ url = f"{base_url}{config.path}?{urlencode(params)}"++ items, total = _fetch_page(session, url, headers, logger)+ if not items:+ break++ first_id = items[0].get("id") if isinstance(items[0], dict) else None+ if offset > 0 and first_id is not None and first_id == previous_first_id:+ logger.warning(f"noCRM: endpoint {endpoint} did not honour offset pagination, stopping to avoid a loop")+ break+ previous_first_id = first_id++ yield items+ offset += len(items)++ # Terminate on a short final page or once we've consumed the pre-pagination total.+ if len(items) < PAGE_SIZE:+ break+ if total is not None and offset >= total:+ break++ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last page+ # rather than skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(NoCRMResumeConfig(offset=offset))+++def validate_credentials(api_key: str, subdomain: str) -> bool:+ """Probe the cheap `/ping` endpoint to confirm the API key and subdomain are genuine."""+ try:+ url = f"{_base_url(subdomain)}/ping"+ except NoCRMConfigError:+ return False+ try:+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, retry=Retry(total=0))+ response = session.get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def nocrm_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NoCRMResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = NOCRM_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ subdomain=subdomain,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ 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,+ # Leads are requested with `order=last_update&direction=asc` on incremental syncs, and the+ # ResumableSource offset state (not the watermark) drives mid-sync resume, so `asc` matches+ # the framework's incremental checkpointing.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/settings.pynew file mode 100644index 000000000000..dd7dc3e6bfc4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/settings.py@@ -0,0 +1,107 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class NoCRMEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ # True only when noCRM exposes a server-side change filter for this list endpoint. Today that's+ # just `/leads` via `updated_after`; every other endpoint is a small config/metadata list with no+ # timestamp filter, so it ships full refresh.+ supports_incremental: bool = False+ # Query param used for the server-side "changed since" filter (leads: `updated_after`).+ incremental_param: Optional[str] = None+ # `order` value that sorts the list ascending by the incremental field, so pages arrive in the+ # order the pipeline's `asc` watermark expects. Only set on incremental endpoints.+ incremental_sort_order: Optional[str] = None+ # `order` value for a stable ascending sort on full-refresh / non-incremental runs, guarding against+ # page-boundary skips if rows are inserted mid-sync. `None` means don't send an `order` param at all+ # (most metadata endpoints don't document one, so we avoid sending params they might reject).+ default_sort_order: Optional[str] = None+ # Stable creation timestamp used for datetime partitioning. None for small metadata endpoints with+ # no creation timestamp / not worth partitioning.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++def _updated_at_incremental_fields() -> list[IncrementalField]:+ # noCRM's `updated_after` filters leads by their last-update time, so `updated_at` is the only+ # meaningful incremental cursor. `created_at` is used for partitioning, not incremental sync.+ return [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++NOCRM_ENDPOINTS: dict[str, NoCRMEndpointConfig] = {+ "leads": NoCRMEndpointConfig(+ name="leads",+ path="/leads",+ supports_incremental=True,+ incremental_param="updated_after",+ incremental_sort_order="last_update",+ default_sort_order="id",+ partition_key="created_at",+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "activities": NoCRMEndpointConfig(+ name="activities",+ path="/activities",+ incremental_fields=[],+ ),+ "users": NoCRMEndpointConfig(+ name="users",+ path="/users",+ incremental_fields=[],+ ),+ "teams": NoCRMEndpointConfig(+ name="teams",+ path="/teams",+ incremental_fields=[],+ ),+ "steps": NoCRMEndpointConfig(+ name="steps",+ path="/steps",+ incremental_fields=[],+ ),+ "pipelines": NoCRMEndpointConfig(+ name="pipelines",+ path="/pipelines",+ incremental_fields=[],+ ),+ "client_folders": NoCRMEndpointConfig(+ name="client_folders",+ path="/clients",+ incremental_fields=[],+ ),+ "categories": NoCRMEndpointConfig(+ name="categories",+ path="/categories",+ incremental_fields=[],+ ),+ "tags": NoCRMEndpointConfig(+ name="tags",+ path="/predefined_tags",+ incremental_fields=[],+ ),+ "fields": NoCRMEndpointConfig(+ name="fields",+ path="/fields",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(NOCRM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NOCRM_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/source.pyindex 01f9819d8919..290a7ab02bdf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/source.py@@ -1,30 +1,156 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NoCRMSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.nocrm import (+ NoCRMResumeConfig,+ nocrm_source,+ validate_credentials as validate_nocrm_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NOCRM_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NoCRMSource(SimpleSource[NoCRMSourceConfig]):+class NoCRMSource(ResumableSource[NoCRMSourceConfig, NoCRMResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NOCRM+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `<subdomain>.nocrm.io`, so retargeting the subdomain must force the+ # editor to re-enter the key rather than reusing the stored one against a new host.+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.NO_CRM,category=DataWarehouseSourceCategory.CRM,- label="NoCRM",- iconPath="/static/services/nocrm.png",- fields=cast(list[FieldType], []),+ label="noCRM.io",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your noCRM.io account subdomain and API key to automatically pull your noCRM.io data into the PostHog Data warehouse.++Your subdomain is the first part of your noCRM.io URL — for `acme.nocrm.io`, enter `acme`.++You can create an API key as an account admin under **Admin panel → API & Webhooks → API keys**. The key is account-level and grants read access to leads, users, teams, pipelines and the other tables listed below.""",+ iconPath="/static/services/nocrm.png",+ docsUrl="https://posthog.com/docs/cdp/sources/nocrm",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API key surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Match the stable status text, not the per-account host/path.+ "401 Client Error: Unauthorized": "Your noCRM.io API key is invalid or has been revoked. Create a new API key in your noCRM.io admin panel, then reconnect.",+ "403 Client Error: Forbidden": "Your noCRM.io API key does not have permission to read this data. Check the key's permissions in noCRM.io, then reconnect.",+ }++ def get_schemas(+ self,+ config: NoCRMSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NOCRM_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.supports_incremental and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: NoCRMSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_nocrm_credentials(config.api_key, config.subdomain):+ return True, None++ return False, "Invalid noCRM.io subdomain or API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NoCRMResumeConfig]:+ return ResumableSourceManager[NoCRMResumeConfig](inputs, NoCRMResumeConfig)++ def source_for_pipeline(+ self,+ config: NoCRMSourceConfig,+ resumable_source_manager: ResumableSourceManager[NoCRMResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return nocrm_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.pynew file mode 100644index 000000000000..e4f07bfb6240--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py@@ -0,0 +1,342 @@+from collections.abc import Sequence+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm import nocrm+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.nocrm import (+ PAGE_SIZE,+ NoCRMConfigError,+ NoCRMResumeConfig,+ _base_url,+ _build_base_params,+ _clamp_future_value_to_now,+ _format_updated_after,+ get_rows,+ nocrm_source,+ normalize_subdomain,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.settings import NOCRM_ENDPOINTS+++class TestNormalizeSubdomain:+ @parameterized.expand(+ [+ ("bare_label", "acme", "acme"),+ ("uppercase", "ACME", "acme"),+ ("whitespace", " acme ", "acme"),+ ("full_host", "acme.nocrm.io", "acme"),+ ("full_url", "https://acme.nocrm.io/", "acme"),+ ("url_with_path", "https://acme.nocrm.io/api/v2/leads", "acme"),+ ("hyphenated", "acme-sales", "acme-sales"),+ # A stray path segment is truncated to the leading label rather than reaching the host.+ ("path_truncated", "acme/evil", "acme"),+ ]+ )+ def test_valid_subdomains_reduce_to_label(self, _name: str, value: str, expected: str) -> None:+ assert normalize_subdomain(value) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("dot_breakout", "acme.evil"),+ ("at_breakout", "evil@acme"),+ ("leading_hyphen", "-acme"),+ ("underscore", "acme_sales"),+ ("space_inside", "acme corp"),+ ]+ )+ def test_invalid_subdomains_raise(self, _name: str, value: str) -> None:+ with pytest.raises(NoCRMConfigError):+ normalize_subdomain(value)++ def test_base_url_is_pinned_to_nocrm_origin(self) -> None:+ # Only the subdomain label is user-controlled; the origin is always *.nocrm.io.+ assert _base_url("acme") == "https://acme.nocrm.io/api/v2"+ assert _base_url("https://acme.nocrm.io") == "https://acme.nocrm.io/api/v2"+++class TestFormatUpdatedAfter:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ assert _format_updated_after(value) == expected++ def test_non_utc_datetime_is_converted_to_utc(self) -> None:+ from datetime import timedelta, timezone++ value = datetime(2026, 3, 4, 12, 0, 0, tzinfo=timezone(timedelta(hours=5)))+ assert _format_updated_after(value) == "2026-03-04T07:00:00Z"+++class TestClampFutureValueToNow:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC)) == datetime(+ 2026, 6, 15, 12, 0, 0, tzinfo=UTC+ )++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_datetime_is_unchanged(self) -> None:+ value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ assert _clamp_future_value_to_now(value) == value++ def test_string_passthrough(self) -> None:+ assert _clamp_future_value_to_now("cursor") == "cursor"+++class TestBuildBaseParams:+ def test_leads_full_refresh_sorts_by_id_without_filter(self) -> None:+ params = _build_base_params(+ NOCRM_ENDPOINTS["leads"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert params == {"order": "id", "direction": "asc"}++ def test_leads_incremental_adds_updated_after_and_sorts_by_last_update(self) -> None:+ params = _build_base_params(+ NOCRM_ENDPOINTS["leads"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params["updated_after"] == "2026-03-04T02:58:14Z"+ # Incremental syncs must sort ascending by the changed field so the asc watermark advances.+ assert params["order"] == "last_update"+ assert params["direction"] == "asc"++ def test_leads_incremental_without_watermark_omits_filter(self) -> None:+ params = _build_base_params(+ NOCRM_ENDPOINTS["leads"], should_use_incremental_field=True, db_incremental_field_last_value=None+ )+ assert "updated_after" not in params++ @parameterized.expand([("users",), ("teams",), ("steps",), ("pipelines",), ("categories",), ("tags",), ("fields",)])+ def test_metadata_endpoints_send_no_order_or_filter(self, endpoint: str) -> None:+ # These endpoints don't document an `order` param, so we must not send one (nor a filter).+ params = _build_base_params(+ NOCRM_ENDPOINTS[endpoint],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params == {}+++class _FakeResumableManager:+ def __init__(self, state: NoCRMResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[NoCRMResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> NoCRMResumeConfig | None:+ return self._state++ def save_state(self, data: NoCRMResumeConfig) -> None:+ self.saved.append(data)+++def _page(n: int, start_id: int = 1) -> list[dict]:+ return [{"id": start_id + i} for i in range(n)]+++def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ responses: Sequence[tuple[list[dict], int | None]],+ endpoint: str = "leads",+ **kwargs: Any,+) -> tuple[list[dict], list[str]]:+ fetched: list[str] = []+ it = iter(responses)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> tuple[list[dict], int | None]:+ fetched.append(url)+ return next(it)++ monkeypatch.setattr(nocrm, "_fetch_page", fake_fetch)+ rows: list[dict] = []+ for batch in get_rows(+ api_key="key",+ subdomain="acme",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows, fetched+++class TestGetRows:+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:+ responses = [(_page(PAGE_SIZE, start_id=1), None), (_page(3, start_id=PAGE_SIZE + 1), None)]+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, responses)+ assert len(rows) == PAGE_SIZE + 3+ # Two requests, second offset advanced by the full first page.+ assert "offset=0" in fetched[0]+ assert f"offset={PAGE_SIZE}" in fetched[1]++ def test_stops_when_total_count_reached(self, monkeypatch: Any) -> None:+ # A full page whose X-TOTAL-COUNT equals the page size must not trigger a second request.+ responses = [(_page(PAGE_SIZE), PAGE_SIZE)]+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, responses)+ assert len(rows) == PAGE_SIZE+ assert len(fetched) == 1++ def test_stops_when_offset_is_ignored(self, monkeypatch: Any) -> None:+ # An endpoint that ignores offset re-serves the same first page; the no-progress guard must+ # break the loop instead of looping forever.+ same_page = _page(PAGE_SIZE, start_id=1)+ responses = [(same_page, None), (same_page, None)]+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, responses)+ assert len(rows) == PAGE_SIZE # only the first page was yielded+ assert len(fetched) == 2++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, [([], None)])+ assert rows == []+ assert len(fetched) == 1++ def test_saves_offset_after_each_page_with_more(self, monkeypatch: Any) -> None:+ responses = [(_page(PAGE_SIZE, start_id=1), None), (_page(2, start_id=PAGE_SIZE + 1), None)]+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, responses)+ # State saved once (after the full first page); not after the short final page.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(NoCRMResumeConfig(offset=PAGE_SIZE))+ responses = [(_page(2, start_id=PAGE_SIZE + 1), None)]+ rows, fetched = _collect(manager, monkeypatch, responses)+ assert len(rows) == 2+ # The first (and only) request must start at the saved offset, not 0.+ assert f"offset={PAGE_SIZE}" in fetched[0]+++class TestTokenRedaction:+ def test_get_rows_redacts_key_and_disables_redirects(self, monkeypatch: Any) -> None:+ session = MagicMock()+ make_session = MagicMock(return_value=session)+ monkeypatch.setattr(nocrm, "make_tracked_session", make_session)+ monkeypatch.setattr(nocrm, "_fetch_page", lambda *a, **k: ([], None))+ list(+ get_rows(+ api_key="secret-key",+ subdomain="acme",+ endpoint="leads",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)+ assert make_session.call_args.kwargs["allow_redirects"] is False++ def test_validate_credentials_rejects_invalid_subdomain_without_request(self) -> None:+ with patch.object(nocrm, "make_tracked_session") as make_session:+ assert validate_credentials("key", "acme.evil") is False+ # An invalid subdomain must fail before any authenticated request is built.+ make_session.assert_not_called()++ def test_validate_credentials_redacts_key(self) -> None:+ session = MagicMock()+ response = MagicMock()+ response.status_code = 200+ session.get.return_value = response+ with patch.object(nocrm, "make_tracked_session", return_value=session) as make_session:+ assert validate_credentials("secret-key", "acme") is True+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)+++def _response_with(status_code: int, body: bytes = b"[]", headers: dict[str, str] | None = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = body+ response.url = "https://acme.nocrm.io/api/v2/leads"+ if headers:+ response.headers.update(headers)+ return response+++_fetch_page_unwrapped = nocrm._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class TestFetchPage:+ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status)+ with pytest.raises(nocrm.NoCRMRetryableError):+ _fetch_page_unwrapped(session, "https://acme.nocrm.io/api/v2/leads", {}, MagicMock())++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_for_status(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "https://acme.nocrm.io/api/v2/leads", {}, MagicMock())++ def test_parses_bare_array_and_total_count_header(self) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(200, body=b'[{"id":1},{"id":2}]', headers={"X-TOTAL-COUNT": "42"})+ items, total = _fetch_page_unwrapped(session, "https://acme.nocrm.io/api/v2/leads", {}, MagicMock())+ assert items == [{"id": 1}, {"id": 2}]+ assert total == 42++ def test_missing_total_count_header_returns_none(self) -> None:+ session = MagicMock()+ session.get.return_value = _response_with(200, body=b'[{"id":1}]')+ _items, total = _fetch_page_unwrapped(session, "https://acme.nocrm.io/api/v2/leads", {}, MagicMock())+ assert total is None++ def test_wrapped_object_body_is_unwrapped(self) -> None:+ # Defensive path: if noCRM ever wraps the array in {"data": [...]}, we still read the rows.+ session = MagicMock()+ session.get.return_value = _response_with(200, body=b'{"data":[{"id":7}]}')+ items, _total = _fetch_page_unwrapped(session, "https://acme.nocrm.io/api/v2/leads", {}, MagicMock())+ assert items == [{"id": 7}]+++class TestSourceResponse:+ def test_leads_partitions_on_created_at(self) -> None:+ response = nocrm_source(+ api_key="k", subdomain="acme", endpoint="leads", logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.name == "leads"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.sort_mode == "asc"++ @parameterized.expand(+ [+ ("users",),+ ("teams",),+ ("steps",),+ ("pipelines",),+ ("categories",),+ ("tags",),+ ("fields",),+ ("activities",),+ ("client_folders",),+ ]+ )+ def test_metadata_endpoints_are_unpartitioned(self, endpoint: str) -> None:+ response = nocrm_source(+ api_key="k", subdomain="acme", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm_source.pynew file mode 100644index 000000000000..2f32def2e75a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm_source.py@@ -0,0 +1,134 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import 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 import NoCRMSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.nocrm import NoCRMResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.source import NoCRMSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestNoCRMSource:+ def setup_method(self) -> None:+ self.source = NoCRMSource()+ self.config = NoCRMSourceConfig(subdomain="acme", api_key="key")+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.NOCRM++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/nocrm"+ # Behind the release gate while in alpha.+ assert config.unreleasedSource is True+ field_names = [f.name for f in config.fields]+ assert field_names == ["subdomain", "api_key"]++ def test_api_key_field_is_a_secret_password_input(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if f.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == "password"+ assert api_key_field.required is True++ def test_connection_host_fields_includes_subdomain(self) -> None:+ # Changing the subdomain retargets where the API key is sent, so it must force key re-entry.+ assert "subdomain" in self.source.connection_host_fields++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ assert len(self.source.get_documented_tables()) == len(self.source.get_schemas(self.config, self.team_id))++ @pytest.mark.parametrize(+ "endpoint,expected_incremental",+ [+ ("leads", True),+ ("activities", False),+ ("users", False),+ ("teams", False),+ ("steps", False),+ ("pipelines", False),+ ("client_folders", False),+ ("categories", False),+ ("tags", False),+ ("fields", False),+ ],+ )+ def test_schema_incremental_support(self, endpoint: str, expected_incremental: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert endpoint in schemas+ assert schemas[endpoint].supports_incremental is expected_incremental+ if expected_incremental:+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == ["updated_at"]+ else:+ assert schemas[endpoint].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["leads", "users"])+ assert {s.name for s in schemas} == {"leads", "users"}++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ def test_validate_credentials_success(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.source.validate_nocrm_credentials",+ return_value=True,+ ):+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ def test_validate_credentials_failure(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.source.validate_nocrm_credentials",+ return_value=False,+ ):+ ok, message = self.source.validate_credentials(self.config, self.team_id)+ assert ok is False+ assert message is not None++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NoCRMResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "leads"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ captured: dict[str, Any] = {}+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.source.nocrm_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert captured["api_key"] == "key"+ assert captured["subdomain"] == "acme"+ assert captured["endpoint"] == "leads"+ assert captured["resumable_source_manager"] is manager+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ captured: dict[str, Any] = {}+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nocrm.source.nocrm_source",+ side_effect=lambda **kwargs: captured.update(kwargs),+ ):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert captured["db_incremental_field_last_value"] is None