Skip to content

: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.

feat(data-warehouse): implement pipeliner import source (#69381)

Tom Owers2a1eb35b39fe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 1ae8eb80bdfd..7f91d73f1606 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -282,6 +282,7 @@ the row lists both.
| pingdom | HTTP | requests | ✅ |
| pinterest_ads | HTTP | requests | ✅ |
| pipedrive | HTTP | requests | ✅ |
+| pipeliner | HTTP | requests | ✅ |
| plain | HTTP | requests | ✅ |
| planhat | HTTP | requests | ✅ |
| plausible | HTTP | requests | ✅ |
@@ -644,7 +645,6 @@ doesn't conflict with concurrent PRs.
- perk
- persona
- pexels
-- pipeliner
- pivotal_tracker
- piwik
- planetscale
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 2de0a2bf2302..76a2e6e60174 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
@@ -2626,7 +2626,10 @@ class PipedriveSourceConfig(config.Config):
@config.config
class PipelinerSourceConfig(config.Config):
- pass
+ service_url: str
+ space_id: str
+ username: str
+ password: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/canonical_descriptions.py
new file mode 100644
index 000000000000..3138b8806e4f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/canonical_descriptions.py
@@ -0,0 +1,205 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Pipeliner CRM (Coevera) REST API OpenAPI spec and docs
+# (https://developers.pipelinersales.com/api-docs).
+_DOCS_URL = "https://developers.pipelinersales.com/api-docs/core-api-concepts/understanding-the-crm-concept"
+
+_COMMON_COLUMNS = {
+ "id": "Unique identifier of the entity (UUID).",
+ "created": "Creation time (UTC).",
+ "modified": "Last modification time (UTC).",
+ "is_deleted": "Whether the entity is considered deleted.",
+ "revision": "Revision when the entity was last changed.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "Companies or organizations tracked in the CRM, including address, industry, and ownership details.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the account and its default text representation.",
+ "owner_id": "Id of the sales user who owns this account.",
+ "account_type_id": "Id of the account type assigned to this account.",
+ "customer_type_id": "Id of the customer category (e.g. Lead, Prospect, Customer).",
+ "industry_id": "Id of the industry classification.",
+ "email1": "Primary email address of the account.",
+ "phone1": "Primary phone number of the account.",
+ "home_page": "Website URL of the account.",
+ "address": "Street address of the account.",
+ "city": "City of the account address.",
+ "state_province": "State or province of the account address.",
+ "country": "Country of the account address.",
+ "zip_code": "ZIP or postal code of the account address.",
+ "parent_account_id": "Id of the parent account in a corporate hierarchy.",
+ "unit_id": "Id of the sales unit this account is assigned to.",
+ "is_archived": "True when the account has been archived.",
+ },
+ },
+ "appointments": {
+ "description": "Calendar appointments (meetings), including start/end times, location, and linked CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "subject": "Short summary line shown in calendars and lists.",
+ "description": "Free-form description of the appointment.",
+ "start_date": "Start timestamp of the appointment.",
+ "end_date": "End timestamp of the appointment.",
+ "duration": "Duration of the appointment, derived from start/end dates.",
+ "location": "Free-text physical location of the appointment.",
+ "organizer": "Email of the user organizing the appointment.",
+ "owner_id": "Id of the sales user who owns this appointment.",
+ "activity_type_id": "Id of the appointment type.",
+ "status": "Current status of the appointment (NotStarted, InProgress, Completed, Canceled).",
+ "unit_id": "Id of the sales unit this appointment is assigned to.",
+ "recurrence_rule": "iCalendar RRULE string describing the recurrence pattern; empty for one-off appointments.",
+ },
+ },
+ "clients": {
+ "description": "Users of the Pipeliner team space (sales team members), including their role and sales unit membership.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Display name of the user.",
+ "email": "Email address of the user.",
+ "first_name": "First name of the user.",
+ "last_name": "Last name of the user.",
+ "position": "Job title or position of the user.",
+ "master_right_id": "Id of the user role, determining what features and entities the user can access.",
+ "default_unit_id": "Id of the user's default sales unit.",
+ "last_active": "Timestamp of the user's most recent login or API request.",
+ "timezone_name": "IANA timezone name from the user profile.",
+ },
+ },
+ "contacts": {
+ "description": "People who have a relation to an account, including contact details and their primary account link.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "first_name": "Given name of the contact.",
+ "last_name": "Family name of the contact.",
+ "formatted_name": "Display version of the contact name (title, first, middle, last).",
+ "email1": "Primary email address of the contact.",
+ "phone1": "Primary phone number of the contact.",
+ "position": "Job title or position of the contact.",
+ "owner_id": "Id of the sales user who owns this contact.",
+ "contact_type_id": "Id of the contact type assigned to this contact.",
+ "address": "Street address of the contact.",
+ "city": "City of the contact address.",
+ "state_province": "State or province of the contact address.",
+ "country": "Country of the contact address.",
+ "zip_code": "ZIP or postal code of the contact address.",
+ "quick_account_name": "Free-text company name used when the contact is not linked to an Account record.",
+ "unit_id": "Id of the sales unit this contact is assigned to.",
+ "is_archived": "True when the contact has been archived.",
+ },
+ },
+ "leads": {
+ "description": "Potential deals before qualification, with source, ranking, process step, and close details.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the lead and its default text representation.",
+ "owner_id": "Id of the lead owner; may be empty when the lead is unassigned.",
+ "lead_source_id": "Id of the lead source (how the lead originated, e.g. Website, Referral).",
+ "lead_type_id": "Id of the lead type.",
+ "step_id": "Id of the lead process step the lead is currently in.",
+ "ranking": "Qualitative ranking score (1-10) indicating the strength of the lead.",
+ "status": "Current status of the lead (Open, Lost, Qualified).",
+ "is_archived": "True when the lead has been archived (lost).",
+ "qualify_date": "Timestamp of when the lead was qualified; empty for unqualified leads.",
+ "lost_date": "Timestamp of when the lead was archived (lost).",
+ "reason_of_close_id": "Id of the reason recorded when the lead was archived (lost).",
+ "unit_id": "Id of the sales unit this lead is assigned to.",
+ },
+ },
+ "notes": {
+ "description": "Free-form notes attached to accounts, contacts, leads, opportunities, projects, or quotes.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "note": "Free-form text body of the note (sanitized HTML allowed).",
+ "owner_id": "Id of the user who authored the note.",
+ "account_id": "Id of the account the note is attached to.",
+ "contact_id": "Id of the contact the note is attached to.",
+ "lead_oppty_id": "Id of the lead or opportunity the note is attached to.",
+ "project_id": "Id of the project the note is attached to.",
+ "quote_id": "Id of the quote the note is attached to.",
+ },
+ },
+ "opportunities": {
+ "description": "Existing or potential business revenue with a contact or account, moving through pipeline stages.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the opportunity and its default text representation.",
+ "owner_id": "Id of the sales user who owns this opportunity.",
+ "oppty_type_id": "Id of the opportunity type; each type maps to one pipeline.",
+ "step_id": "Id of the pipeline step the opportunity is currently in.",
+ "value": "Monetary value of the opportunity in the team space base currency, with foreign value and currency code.",
+ "closing_date": "Expected or actual closing date of the opportunity.",
+ "status": "Current status of the opportunity (Open, Won, Lost).",
+ "ranking": "Qualitative ranking score (1-10) indicating the strength of the opportunity.",
+ "is_archived": "True when the opportunity has been archived (lost).",
+ "was_qualified": "True when the opportunity has gone through the qualification step at least once.",
+ "qualify_date": "Timestamp of when the opportunity was qualified.",
+ "won_date": "Timestamp of when the opportunity was won.",
+ "lost_date": "Timestamp of when the opportunity was archived (lost).",
+ "reason_of_close_id": "Id of the reason recorded when the opportunity was archived (lost).",
+ "lead_source_id": "Id of the lead source (how the opportunity originated).",
+ "unit_id": "Id of the sales unit this opportunity is assigned to.",
+ },
+ },
+ "pipelines": {
+ "description": "Sales pipelines that opportunities move through, each composed of ordered steps.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the pipeline and its default text representation.",
+ },
+ },
+ "products": {
+ "description": "Products from the catalog that can be attached to opportunities as line items.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the product, shown in catalogs and pickers.",
+ "description": "Free-form description of the product.",
+ "sku": "Stock-keeping unit (SKU) identifier of the product; unique across products.",
+ "product_category_id": "Id of the product category this product belongs to.",
+ "product_type_id": "Id of the product type.",
+ "unit_symbol": "Unit of measure shown next to product quantities (e.g. pcs, kg, hours).",
+ },
+ },
+ "steps": {
+ "description": "Individual stages within a sales pipeline or lead/quote process, with win probability and expected timeframe.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the step and its default text representation.",
+ "pipeline_id": "Id of the opportunity pipeline this step belongs to.",
+ "lead_process_id": "Id of the lead process this step belongs to.",
+ "percent": "Probability percent associated with the step (0-100) for opportunity pipeline steps.",
+ "sort_order": "Position of the step within its pipeline or process; lower values appear first.",
+ "timeframe": "Expected number of days a record should spend in this step.",
+ },
+ },
+ "tasks": {
+ "description": "To-do items and logged activities (e.g. tasks, calls), with due dates, priority, and linked CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "subject": "Short summary line shown in lists and notifications.",
+ "description": "Free-form description of what the task entails.",
+ "due_date": "Date by which the task is expected to be completed.",
+ "start_date": "Date when work on the task is scheduled to begin.",
+ "priority": "Priority level of the task (1 - Low, 2 - Medium, 3 - High, 4 - Urgent).",
+ "status": "Current status of the task (NotStarted, InProgress, Completed, Deferred).",
+ "owner_id": "Id of the task owner; may be empty when the task is unassigned.",
+ "activity_type_id": "Id of the task type (e.g. Task, Call, Email).",
+ "unit_id": "Id of the sales unit this task is assigned to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/pipeliner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/pipeliner.py
new file mode 100644
index 000000000000..1e0e6e6a966c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/pipeliner.py
@@ -0,0 +1,304 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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.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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.settings import PIPELINER_ENDPOINTS
+
+# Pipeliner caps list pages at 100 records (default 30); the largest page minimizes round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+HOST_NOT_ALLOWED_ERROR = "Pipeliner service URL is not allowed"
+
+# Cheap collection used to confirm the API key pair is genuine. The keys are space-wide, so one
+# probe validates access to every entity collection.
+DEFAULT_PROBE_ENTITY = "Clients"
+
+# The default cursor advertised in settings.py; every Pipeliner entity carries `modified`.
+DEFAULT_INCREMENTAL_FIELD = "modified"
+
+
+class PipelinerRetryableError(Exception):
+ pass
+
+
+class PipelinerHostNotAllowedError(Exception):
+ pass
+
+
+class PipelinerResumeConfig:
+ # `page_info.end_cursor` of the last page yielded; passed back via `after` to resume from the
+ # next page. Merge dedupes any re-pulled rows on the primary key.
+ cursor: str | None = None
+ # The formatted incremental filter value the cursor was minted under. Reapplied verbatim on
+ # resume so the resumed query walks the same result set even if the stored watermark advanced
+ # while earlier batches were being persisted.
+ filter_value: str | None = None
+
+
+def normalize_service_url(service_url: str) -> str:
+ """Turn whatever the user typed into a bare API host.
+
+ Accepts values like ``us-east.api.pipelinersales.com``,
+ ``https://us-east.api.pipelinersales.com/``, or a full base URL including the
+ ``/api/v100/rest/spaces/...`` path, and returns just the host.
+ """
+ service_url = service_url.strip()
+ service_url = re.sub(r"^https?://", "", service_url, flags=re.IGNORECASE)
+ return service_url.split("/")[0].strip()
+
+
+def _base_url(service_url: str, space_id: str) -> str:
+ return f"https://{normalize_service_url(service_url)}/api/v100/rest/spaces/{space_id.strip()}"
+
+
+def _make_session(username: str, password: str) -> requests.Session:
+ # allow_redirects=False: the service URL is user-controlled, so never follow a redirect that
+ # could point at an internal address (SSRF).
+ session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(username, password),
+ allow_redirects=False,
+ )
+ session.auth = (username, password)
+ return session
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Pipeliner stores every timestamp in UTC and accepts ISO 8601 values in filters."""
+ if isinstance(value, datetime):
+ utc_dt = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
+ return utc_dt.strftime("%Y-%m-%d %H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d 00:00:00")
+ return str(value)
+
+
+def _reject_redirect(response: requests.Response) -> None:
+ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than
+ # parsing the redirect body as data — the Location could point at an internal address (SSRF).
+ if response.is_redirect or response.is_permanent_redirect:
+ raise PipelinerHostNotAllowedError(
+ f"Pipeliner API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+
+@retry(
+ retry=retry_if_exception_type((PipelinerRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], str | None, bool]:
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PipelinerRetryableError(f"Pipeliner API error (retryable): status={response.status_code}, url={url}")
+
+ _reject_redirect(response)
+
+ if not response.ok:
+ logger.error(f"Pipeliner API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # List endpoints wrap records in {"success": bool, "data": [...], "page_info": {...}}.
+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):
+ raise PipelinerRetryableError(f"Pipeliner returned an unexpected payload for {url}: {type(data).__name__}")
+
+ page_info = data.get("page_info") or {}
+ end_cursor = page_info.get("end_cursor") if isinstance(page_info, dict) else None
+ has_next_page = bool(page_info.get("has_next_page")) if isinstance(page_info, dict) else False
+ return data["data"], end_cursor if isinstance(end_cursor, str) else None, has_next_page
+
+
+def get_rows(
+ service_url: str,
+ space_id: str,
+ username: str,
+ password: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PipelinerResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PIPELINER_ENDPOINTS[endpoint]
+
+ # Re-check at run time (not just at source-create) in case the service URL was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(normalize_service_url(service_url), team_id)
+ if not host_ok:
+ raise PipelinerHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ session = _make_session(username, password)
+ url = f"{_base_url(service_url, space_id)}/entities/{config.entity}"
+
+ cursor_field = incremental_field or DEFAULT_INCREMENTAL_FIELD
+ filter_value: str | None = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ filter_value = _format_incremental_value(db_incremental_field_last_value)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor: str | None = None
+ if resume is not None:
+ cursor = resume.cursor
+ filter_value = resume.filter_value
+ logger.debug(f"Pipeliner: resuming {endpoint} from cursor {cursor}")
+
+ # Ascending sort on a monotonic field keeps page boundaries stable, and for incremental syncs
+ # matches sort_mode="asc" so the pipeline's watermark checkpoints correctly. `filter`,
+ # `order-by`, and the `after` cursor are documented as regular list parameters and are re-sent
+ # on every page, so the time window applies to the whole walk, not just page one.
+ order_by = cursor_field if should_use_incremental_field else config.partition_key
+
+ while True:
+ params: dict[str, Any] = {"first": PAGE_SIZE, "order-by": order_by}
+ if filter_value is not None:
+ params[f"filter[{cursor_field}]"] = filter_value
+ params[f"filter-op[{cursor_field}]"] = "gte"
+ if cursor is not None:
+ params["after"] = cursor
+
+ items, end_cursor, has_next_page = _fetch_page(session, url, params, logger)
+ if items:
+ yield items
+
+ # `has_next_page` false (or an empty/cursor-less page, defensively) ends the collection.
+ if not has_next_page or not end_cursor or not items:
+ break
+
+ cursor = end_cursor
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(PipelinerResumeConfig(cursor=cursor, filter_value=filter_value))
+
+
+def pipeliner_source(
+ service_url: str,
+ space_id: str,
+ username: str,
+ password: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PipelinerResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = PIPELINER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ service_url=service_url,
+ space_id=space_id,
+ username=username,
+ password=password,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
+
+
+def check_access(
+ service_url: str,
+ space_id: str,
+ username: str,
+ password: str,
+ entity: str = DEFAULT_PROBE_ENTITY,
+) -> tuple[int, Optional[str]]:
+ """Probe a single entity collection to validate the API key pair.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = _make_session(username, password)
+ url = f"{_base_url(service_url, space_id)}/entities/{entity}"
+ try:
+ response = session.get(url, params={"first": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Pipeliner: {e}"
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return 0, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ # Error responses carry {"code", "name", "message", ...}; surface the message when present.
+ try:
+ message = response.json().get("message")
+ except Exception:
+ message = None
+ return response.status_code, message or f"Pipeliner returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(
+ service_url: str,
+ space_id: str,
+ username: str,
+ password: str,
+ schema_name: Optional[str] = None,
+ team_id: Optional[int] = None,
+) -> tuple[bool, str | None]:
+ host = normalize_service_url(service_url)
+ if not host or not re.match(r"^[A-Za-z0-9.\-]+$", host):
+ return False, "Invalid Pipeliner service URL"
+
+ if not space_id.strip() or not re.match(r"^[A-Za-z0-9\-]+$", space_id.strip()):
+ return False, "Invalid Pipeliner space ID"
+
+ # The service URL is fully customer-controlled, so block hosts that resolve to private/
+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(host, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ status, message = check_access(service_url, space_id, username, password)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Pipeliner API credentials"
+ if status == 403:
+ if schema_name is None:
+ # Valid credentials, missing permission for this probe — let source creation through.
+ return True, None
+ return False, "Your Pipeliner API application lacks the required permissions for this endpoint"
+ return False, message or "Could not validate Pipeliner API credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/settings.py
new file mode 100644
index 000000000000..45909bc52d39
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/settings.py
@@ -0,0 +1,54 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class PipelinerEndpointConfig:
+ name: str
+ # Entity collection name in the REST path, e.g. `/entities/Accounts`.
+ entity: str
+ # Every Pipeliner entity carries a server-maintained `modified` timestamp and the list
+ # endpoints accept `filter[modified]` + `filter-op[modified]=gte`, so all endpoints
+ # advertise it as the incremental cursor.
+ incremental_fields: list[IncrementalField] = field(
+ default_factory=lambda: [_datetime_incremental_field("modified")]
+ )
+ # `created` never changes; `modified` mutates on every edit and would rewrite partitions.
+ partition_key: str = "created"
+ # Pipeliner entity ids are UUIDs, unique across the whole team space.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Pipeliner CRM (Coevera) REST API list endpoints (https://developers.pipelinersales.com).
+# The API exposes ~200 entity collections; these are the core CRM streams a user actually
+# wants to analyze. `Activities` is deliberately absent — it is an abstract union of Tasks
+# and Appointments, which are synced directly instead.
+PIPELINER_ENDPOINTS: dict[str, PipelinerEndpointConfig] = {
+ "accounts": PipelinerEndpointConfig(name="accounts", entity="Accounts"),
+ "appointments": PipelinerEndpointConfig(name="appointments", entity="Appointments"),
+ "clients": PipelinerEndpointConfig(name="clients", entity="Clients"),
+ "contacts": PipelinerEndpointConfig(name="contacts", entity="Contacts"),
+ "leads": PipelinerEndpointConfig(name="leads", entity="Leads"),
+ "notes": PipelinerEndpointConfig(name="notes", entity="Notes"),
+ "opportunities": PipelinerEndpointConfig(name="opportunities", entity="Opportunities"),
+ "pipelines": PipelinerEndpointConfig(name="pipelines", entity="Pipelines"),
+ "products": PipelinerEndpointConfig(name="products", entity="Products"),
+ "steps": PipelinerEndpointConfig(name="steps", entity="Steps"),
+ "tasks": PipelinerEndpointConfig(name="tasks", entity="Tasks"),
+}
+
+ENDPOINTS = tuple(PIPELINER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PIPELINER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/source.py
index 44863475ad03..d3c3f732cf21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/source.py
@@ -1,30 +1,178 @@
-from typing import cast
+from typing import Optional, cast
from 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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PipelinerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.pipeliner import (
+ HOST_NOT_ALLOWED_ERROR,
+ PipelinerResumeConfig,
+ pipeliner_source,
+ validate_credentials as validate_pipeliner_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PIPELINER_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PipelinerSource(SimpleSource[PipelinerSourceConfig]):
+class PipelinerSource(ResumableSource[PipelinerSourceConfig, PipelinerResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PIPELINER
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `service_url` is where the stored API key pair is sent; retargeting it must re-require
+ # the credentials.
+ return ["service_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PIPELINER,
category=DataWarehouseSourceCategory.CRM,
label="Pipeliner",
+ keywords=["coevera", "pipeliner crm"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Import data from your Pipeliner CRM (Coevera) team space into the PostHog Data warehouse.
+
+To connect, create an API application in Pipeliner under **Administration → Unit, Users & Roles → Applications**, then click **Show API Access** to reveal the space ID, service URL, and API credentials. The username and password are shown only once, so store them safely.
+""",
iconPath="/static/services/pipeliner.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/pipeliner",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="service_url",
+ label="Service URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="us-east.api.pipelinersales.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="space_id",
+ label="Space ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ # The username is not a user-chosen handle but half of the generated API key
+ # pair (shown once in Pipeliner), so it is stored and treated as a secret.
+ SourceFieldInputConfig(
+ name="username",
+ label="API username",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="API password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Pipeliner API credentials are invalid or have been revoked. Create a new API application under Administration → Applications, then reconnect.",
+ "403 Client Error": "Your Pipeliner API application does not have access to this data. Check the application's permissions, then reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The Pipeliner service URL is not allowed. Please use the service URL shown in your API application's access details.",
+ }
+
+ def get_schemas(
+ self,
+ config: PipelinerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(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: PipelinerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key pair is space-wide, so a single probe validates access to every schema.
+ return validate_pipeliner_credentials(
+ config.service_url, config.space_id, config.username, config.password, schema_name, team_id
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PipelinerResumeConfig]:
+ return ResumableSourceManager[PipelinerResumeConfig](inputs, PipelinerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PipelinerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PipelinerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in PIPELINER_ENDPOINTS:
+ raise ValueError(f"Unknown Pipeliner schema '{inputs.schema_name}'")
+
+ return pipeliner_source(
+ service_url=config.service_url,
+ space_id=config.space_id,
+ username=config.username,
+ password=config.password,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner.py
new file mode 100644
index 000000000000..e94d2645a2cd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner.py
@@ -0,0 +1,330 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner import pipeliner as pipeliner_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.pipeliner import (
+ PAGE_SIZE,
+ PipelinerHostNotAllowedError,
+ PipelinerResumeConfig,
+ _format_incremental_value,
+ get_rows,
+ normalize_service_url,
+ pipeliner_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.settings import ENDPOINTS
+
+
+def _response(
+ *, status_code: int = 200, json_data: Any = None, text: str = "", json_raises: bool = False
+) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (302, 303, 307)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ if json_raises:
+ response.json.side_effect = ValueError("not json")
+ else:
+ response.json.return_value = json_data
+ return response
+
+
+def _page(items: list[dict[str, Any]], end_cursor: Optional[str] = None, has_next_page: bool = False) -> dict[str, Any]:
+ payload: dict[str, Any] = {"success": True, "data": items}
+ if end_cursor is not None or has_next_page:
+ payload["page_info"] = {"end_cursor": end_cursor, "has_next_page": has_next_page}
+ return payload
+
+
+class TestNormalizeServiceUrl:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("us-east.api.pipelinersales.com", "us-east.api.pipelinersales.com"),
+ ("https://us-east.api.pipelinersales.com", "us-east.api.pipelinersales.com"),
+ ("http://us-east.api.pipelinersales.com/", "us-east.api.pipelinersales.com"),
+ (" eu-central.api.pipelinersales.com ", "eu-central.api.pipelinersales.com"),
+ (
+ "https://us-east.api.pipelinersales.com/api/v100/rest/spaces/abc",
+ "us-east.api.pipelinersales.com",
+ ),
+ ],
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize_service_url(raw) == expected
+
+
+class TestFormatIncrementalValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04 02:58:14"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04 02:58:14"),
+ (date(2026, 3, 4), "2026-03-04 00:00:00"),
+ ("2026-03-04 00:00:00", "2026-03-04 00:00:00"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_incremental_value(value) == expected
+
+
+class TestGetRows:
+ def _run(self, manager, responses, **kwargs):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with mock.patch.object(pipeliner_module, "make_tracked_session", return_value=session):
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ service_url="us-east.api.pipelinersales.com",
+ space_id="space-1",
+ username="user",
+ password="pass",
+ endpoint="accounts",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, session
+
+ def _manager(self, resume: Optional[PipelinerResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+ def test_paginates_with_after_cursor_until_last_page(self):
+ manager = self._manager()
+ page1 = _response(json_data=_page([{"id": "1"}, {"id": "2"}], end_cursor="cur1", has_next_page=True))
+ page2 = _response(json_data=_page([{"id": "3"}], end_cursor="cur2", has_next_page=False))
+ rows, session = self._run(manager, [page1, page2])
+
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ first_params = session.get.call_args_list[0].kwargs["params"]
+ assert "after" not in first_params
+ assert first_params["first"] == PAGE_SIZE
+ second_params = session.get.call_args_list[1].kwargs["params"]
+ assert second_params["after"] == "cur1"
+
+ def test_requests_target_space_scoped_entity_url(self):
+ manager = self._manager()
+ _rows, session = self._run(manager, [_response(json_data=_page([{"id": "1"}]))])
+
+ url = session.get.call_args_list[0].args[0]
+ assert url == "https://us-east.api.pipelinersales.com/api/v100/rest/spaces/space-1/entities/Accounts"
+
+ def test_incremental_run_sends_server_side_filter_and_matching_sort(self):
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [_response(json_data=_page([{"id": "1"}]))],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="modified",
+ )
+
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert params["filter[modified]"] == "2026-01-01 00:00:00"
+ assert params["filter-op[modified]"] == "gte"
+ assert params["order-by"] == "modified"
+
+ def test_incremental_first_sync_has_no_filter_but_sorts_by_cursor_field(self):
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [_response(json_data=_page([{"id": "1"}]))],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="modified",
+ )
+
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert "filter[modified]" not in params
+ assert params["order-by"] == "modified"
+
+ def test_full_refresh_has_no_filter_and_sorts_by_created(self):
+ manager = self._manager()
+ _rows, session = self._run(
+ manager,
+ [_response(json_data=_page([{"id": "1"}]))],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert not any(key.startswith("filter") for key in params)
+ assert params["order-by"] == "created"
+
+ def test_saves_state_after_yielding_each_page(self):
+ manager = self._manager()
+ page1 = _response(json_data=_page([{"id": "1"}], end_cursor="cur1", has_next_page=True))
+ page2 = _response(json_data=_page([{"id": "2"}], end_cursor="cur2", has_next_page=False))
+ self._run(manager, [page1, page2])
+
+ # State is saved once per followed page boundary — after page 1 yielded, not for the last page.
+ assert manager.save_state.call_count == 1
+ saved = manager.save_state.call_args.args[0]
+ assert isinstance(saved, PipelinerResumeConfig)
+ assert saved.cursor == "cur1"
+
+ def test_resumes_from_saved_cursor_and_reapplies_saved_filter(self):
+ manager = self._manager(PipelinerResumeConfig(cursor="resume-cur", filter_value="2026-01-01 00:00:00"))
+ _rows, session = self._run(
+ manager,
+ [_response(json_data=_page([{"id": "9"}]))],
+ should_use_incremental_field=True,
+ # A watermark that advanced mid-job must not replace the filter the cursor was minted under.
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ incremental_field="modified",
+ )
+
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert params["after"] == "resume-cur"
+ assert params["filter[modified]"] == "2026-01-01 00:00:00"
+
+ def test_empty_page_terminates_even_when_has_next_page(self):
+ manager = self._manager()
+ page = _response(json_data=_page([], end_cursor="cur1", has_next_page=True))
+ rows, session = self._run(manager, [page])
+
+ assert rows == []
+ assert session.get.call_count == 1
+
+ def test_missing_page_info_terminates(self):
+ manager = self._manager()
+ rows, session = self._run(manager, [_response(json_data={"success": True, "data": [{"id": "1"}]})])
+
+ assert [r["id"] for r in rows] == ["1"]
+ assert session.get.call_count == 1
+
+ def test_redirect_response_is_rejected(self):
+ # The service URL is user-controlled; a 3xx could point at an internal address (SSRF).
+ manager = self._manager()
+ with pytest.raises(PipelinerHostNotAllowedError):
+ self._run(manager, [_response(status_code=302)])
+
+ def test_blocks_unsafe_host_before_any_request(self):
+ manager = self._manager()
+ session = mock.MagicMock()
+ with (
+ mock.patch.object(pipeliner_module, "_is_host_safe", return_value=(False, "internal address")),
+ mock.patch.object(pipeliner_module, "make_tracked_session", return_value=session),
+ ):
+ with pytest.raises(PipelinerHostNotAllowedError):
+ list(
+ get_rows(
+ service_url="10.0.0.1",
+ space_id="space-1",
+ username="user",
+ password="pass",
+ endpoint="accounts",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ )
+ )
+ session.get.assert_not_called()
+
+
+class TestPipelinerSourceResponse:
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_response_shape(self, endpoint):
+ response = pipeliner_source(
+ service_url="us-east.api.pipelinersales.com",
+ space_id="space-1",
+ username="user",
+ password="pass",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ # `created` never changes; partitioning on `modified` would rewrite partitions on every edit.
+ assert response.partition_keys == ["created"]
+ assert response.partition_mode == "datetime"
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(pipeliner_module, "make_tracked_session", return_value=session)
+
+ def test_success(self):
+ with self._patch_session(_response(status_code=200, json_data=_page([]))):
+ assert validate_credentials("us-east.api.pipelinersales.com", "space-1", "user", "pass") == (True, None)
+
+ def test_invalid_credentials(self):
+ with self._patch_session(_response(status_code=401)):
+ valid, msg = validate_credentials("us-east.api.pipelinersales.com", "space-1", "user", "pass")
+ assert valid is False
+ assert msg == "Invalid Pipeliner API credentials"
+
+ def test_403_at_source_create_is_accepted(self):
+ with self._patch_session(_response(status_code=403)):
+ assert validate_credentials(
+ "us-east.api.pipelinersales.com", "space-1", "user", "pass", schema_name=None
+ ) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with self._patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials(
+ "us-east.api.pipelinersales.com", "space-1", "user", "pass", schema_name="accounts"
+ )
+ assert valid is False
+ assert msg is not None
+
+ @pytest.mark.parametrize("bad_service_url", ["", "not a host!", "https://"])
+ def test_invalid_service_url_short_circuits(self, bad_service_url):
+ valid, msg = validate_credentials(bad_service_url, "space-1", "user", "pass")
+ assert valid is False
+ assert msg == "Invalid Pipeliner service URL"
+
+ @pytest.mark.parametrize("bad_space_id", ["", " ", "space/../../etc"])
+ def test_invalid_space_id_short_circuits(self, bad_space_id):
+ valid, msg = validate_credentials("us-east.api.pipelinersales.com", bad_space_id, "user", "pass")
+ assert valid is False
+ assert msg == "Invalid Pipeliner space ID"
+
+ def test_error_message_surfaced_from_api_envelope(self):
+ body = {"code": 404, "name": "ERROR_NOT_FOUND", "message": "Space not found.", "success": False}
+ with self._patch_session(_response(status_code=404, json_data=body)):
+ valid, msg = validate_credentials("us-east.api.pipelinersales.com", "space-1", "user", "pass")
+ assert valid is False
+ assert msg == "Space not found."
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("us-east.api.pipelinersales.com", "space-1", "user", "pass")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ with self._patch_session(_response(status_code=302)):
+ valid, msg = validate_credentials("us-east.api.pipelinersales.com", "space-1", "user", "pass")
+ assert valid is False
+ assert msg == pipeliner_module.HOST_NOT_ALLOWED_ERROR
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(pipeliner_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("10.0.0.1", "space-1", "user", "pass", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner_source.py
new file mode 100644
index 000000000000..a69a49592530
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipeliner/tests/test_pipeliner_source.py
@@ -0,0 +1,148 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PipelinerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.pipeliner import PipelinerResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.source import PipelinerSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestPipelinerSource:
+ def setup_method(self):
+ self.source = PipelinerSource()
+ self.team_id = 123
+ self.config = PipelinerSourceConfig(
+ service_url="us-east.api.pipelinersales.com",
+ space_id="space-1",
+ username="api-user",
+ password="api-pass",
+ )
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PIPELINER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Pipeliner"
+ assert config.label == "Pipeliner"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/pipeliner.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["service_url", "space_id", "username", "password"]
+
+ # Both halves of the generated API key pair are credentials — a non-secret one would be
+ # returned in job_inputs to anyone with source read access.
+ for credential_field in config.fields[-2:]:
+ assert isinstance(credential_field, SourceFieldInputConfig)
+ assert credential_field.type == SourceFieldInputConfigType.PASSWORD
+ assert credential_field.secret is True
+ assert credential_field.required is True
+
+ def test_service_url_is_a_connection_host_field(self):
+ # Retargeting the service URL must force re-entry of the API key pair — without this an
+ # editor could point the stored credentials at a server they control and exfiltrate them.
+ assert "service_url" in self.source.connection_host_fields
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints_with_incremental_support(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert [f["field"] for f in schema.incremental_fields] == ["modified"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["accounts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "accounts"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_get_documented_tables_lists_static_catalog(self):
+ tables = {t["name"] for t in self.source.get_documented_tables()}
+ assert tables == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected",
+ [
+ ((True, None), (True, None)),
+ ((False, "Invalid Pipeliner API credentials"), (False, "Invalid Pipeliner API credentials")),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.source.validate_pipeliner_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="accounts")
+
+ assert result == expected
+ mock_validate.assert_called_once_with(
+ self.config.service_url,
+ self.config.space_id,
+ self.config.username,
+ self.config.password,
+ "accounts",
+ self.team_id,
+ )
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PipelinerResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.source.pipeliner_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_pipeliner_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "opportunities"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01 00:00:00"
+ inputs.incremental_field = "modified"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_pipeliner_source.call_args.kwargs
+ assert kwargs["service_url"] == "us-east.api.pipelinersales.com"
+ assert kwargs["space_id"] == "space-1"
+ assert kwargs["username"] == "api-user"
+ assert kwargs["password"] == "api-pass"
+ assert kwargs["endpoint"] == "opportunities"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01 00:00:00"
+ assert kwargs["incremental_field"] == "modified"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pipeliner.source.pipeliner_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_pipeliner_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "accounts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_pipeliner_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "unknown"
+
+ with pytest.raises(ValueError, match="Unknown Pipeliner schema"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)