: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 the crisp import source (#115661)
Tom Owers0753f6787a26
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0b08d2a39c3d..568627c57aea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -257,6 +257,7 @@ the row lists both.| courier | HTTP | requests + `rest_source.RESTClient` | ✅ || coveralls | HTTP | requests | ✅ || crates_io | HTTP | requests | ✅ |+| crisp | HTTP | requests + `rest_source.RESTClient` | ✅ || criteo | HTTP | requests + `rest_source.RESTClient` | ✅ || cronitor | HTTP | requests | ✅ || crossref | HTTP | requests | ✅ |@@ -1092,7 +1093,6 @@ doesn't conflict with concurrent PRs.- copper- cosmosdb- couchbase-- crisp- crowdstrike_falcon- cube_cloud- curvediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.pynew file mode 100644index 000000000000..c6fe36d0c978--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/canonical_descriptions.py@@ -0,0 +1,88 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "conversations": {+ "description": "Support conversations in the workspace, including conversations without messages.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-conversations",+ "columns": {+ "session_id": "The conversation identifier.",+ "people_id": "The identifier of the contact linked to the conversation.",+ "state": "The conversation state: pending, unresolved, or resolved.",+ "created_at": "The time when Crisp created the conversation.",+ "updated_at": "The time when Crisp last updated the conversation.",+ },+ },+ "messages": {+ "description": "Messages from each conversation, including operator notes and events.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#get-messages-in-conversation",+ "columns": {+ "session_id": "The conversation that contains the message.",+ "fingerprint": "The message identifier within the conversation.",+ "timestamp": "The time when Crisp sent the message.",+ "content": "The message text or structured content for other message types.",+ "edited": "Whether someone edited the message after sending it.",+ },+ },+ "people": {+ "description": "Contact profiles with personal information, company information, and segments.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-people-profiles",+ "columns": {+ "people_id": "The contact identifier.",+ "email": "The email address of the contact.",+ "person": "Personal information for the contact.",+ "company": "Company information for the contact.",+ "created_at": "The time when Crisp created the contact profile.",+ },+ },+ "people_events": {+ "description": "Events recorded for each contact profile.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-people-events",+ "columns": {+ "people_id": "The contact that owns the event.",+ "text": "The event text.",+ "data": "Additional data attached to the event.",+ "timestamp": "The time when Crisp recorded the event.",+ },+ },+ "operators": {+ "description": "Joined operators and plugin developers in the workspace. Pending invitations are excluded.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-website-operators",+ "columns": {+ "user_id": "The operator identifier.",+ "type": "The member type: operator or sandbox.",+ "role": "The operator role in the workspace.",+ "availability": "The availability of the operator.",+ },+ },+ "visitors": {+ "description": "Visitors on the website at the time of the sync. This table contains no visitor history.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-visitors",+ "columns": {+ "session_id": "The visitor session identifier.",+ "active": "Whether the visitor actively browses the website.",+ "last_page": "The last page that the visitor opened.",+ },+ },+ "helpdesk_locales": {+ "description": "Helpdesk locales with public URLs and content counts.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-helpdesk-locales",+ "columns": {+ "locale_id": "The locale identifier.",+ "locale": "The locale code in ISO 639-1 format.",+ "url": "The public helpdesk URL for the locale.",+ },+ },+ "helpdesk_articles": {+ "description": "Published article titles and URLs for each helpdesk locale. Article bodies and drafts are excluded.",+ "docs_url": "https://docs.crisp.chat/references/rest-api/v1/#list-helpdesk-pages",+ "columns": {+ "locale": "The locale code of the helpdesk article.",+ "entity_id": "The article identifier within the locale.",+ "title": "The article title.",+ "url": "The public article URL.",+ "tree_path": "The content path in the helpdesk tree.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.pynew file mode 100644index 000000000000..7ebca5e0cbcb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/crisp.py@@ -0,0 +1,254 @@+from collections.abc import Callable+from datetime import UTC, datetime+from typing import Any+from urllib.parse import quote++from requests import Request, Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ ResponseAction,+)+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 schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.settings import ENDPOINTS, CrispEndpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig+++@frozen+class CrispResumeConfig:+ paginator_state: dict[str, Any]+++class CrispPathPaginator(PageNumberPaginator):+ def __init__(self, page_size: int | None = None) -> None:+ super().__init__(base_page=1)+ self.page_size = page_size++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ if self.page_size is not None and data is not None and len(data) < self.page_size:+ self._has_next_page = False+ return+ super().update_state(response, data)++ def init_request(self, request: Request) -> None:+ self.update_request(request)++ def update_request(self, request: Request) -> None:+ if request.url is None:+ raise ValueError("Crisp pagination requires a request URL")+ request.url = f"{request.url.rsplit('/', 1)[0]}/{self.page}"+++class CrispMessagesPaginator(BasePaginator):+ def __init__(self) -> None:+ super().__init__()+ self.timestamp_before: int | None = None++ def init_request(self, request: Request) -> None:+ self.update_request(request)++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ if not data:+ self._has_next_page = False+ return+ oldest = min(int(row["timestamp"]) for row in data)+ if self.timestamp_before is not None and oldest >= self.timestamp_before:+ raise ValueError("Crisp message pagination did not advance")+ self.timestamp_before = oldest++ def update_request(self, request: Request) -> None:+ if self.timestamp_before is not None:+ if request.params is None:+ request.params = {}+ request.params["timestamp_before"] = self.timestamp_before++ def get_resume_state(self) -> dict[str, Any] | None:+ return {"timestamp_before": self.timestamp_before} if self.has_next_page else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ self.timestamp_before = int(state["timestamp_before"])+++def client_config(config: CrispSourceConfig, api_version: str) -> ClientConfig:+ return {+ "base_url": f"https://api.crisp.chat/{api_version}/",+ "auth": {"type": "http_basic", "username": config.token_identifier, "password": config.token_key},+ "headers": {"X-Crisp-Tier": "website", "Accept": "application/json"},+ # operators/list returns pending-invitation credentials that the sample scrubbers do not redact.+ "capture": False,+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": (10, 60),+ "retry_budget_seconds": 240,+ "retry_after_max_seconds": 120,+ }+++def endpoint_config(endpoint: CrispEndpoint, website_id: str) -> Endpoint:+ response_actions: list[ResponseAction] = [+ {+ "status_code": 200,+ "json_field": "error",+ "json_values": [True],+ "action": "raise",+ "message": "Crisp returned an API error",+ }+ ]+ if endpoint.name in ("conversations", "people"):+ response_actions.append({"status_code": 416, "action": "ignore"})+ paginator: BasePaginator+ if endpoint.pagination == "messages":+ paginator = CrispMessagesPaginator()+ elif endpoint.pagination == "single":+ paginator = SinglePagePaginator()+ else:+ # Other lists have no documented page size, so a short page cannot prove that they ended.+ per_page = endpoint.params.get("per_page")+ paginator = CrispPathPaginator(page_size=int(per_page) if per_page is not None else None)+ return {+ "path": endpoint.path.replace("{website_id}", quote(website_id, safe="")),+ "params": dict(endpoint.params),+ "paginator": paginator,+ "data_selector": "data",+ "data_selector_required": True,+ "response_actions": response_actions,+ }+++def resource_config(endpoint: CrispEndpoint, website_id: str) -> EndpointResource:+ return {+ "name": endpoint.name,+ "table_name": endpoint.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config(endpoint, website_id),+ }+++def parent_path_map(field: str) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def encode_path(row: dict[str, Any]) -> dict[str, Any]:+ return {**row, "_path_id": quote(str(row[field]), safe="")}++ return encode_path+++def normalize_row(row: dict[str, Any]) -> dict[str, Any]:+ for name in ("created_at", "updated_at", "timestamp", "dispatched_at", "waiting_since"):+ value = row.get(name)+ if isinstance(value, int | float) and not isinstance(value, bool):+ row[name] = datetime.fromtimestamp(value / 1000, tz=UTC)+ return row+++def normalize_operator(row: dict[str, Any]) -> dict[str, Any]:+ # Pending invitations include credentials, so only joined operators enter the warehouse.+ return {"type": row["type"], **row["details"]}+++def credential_resource(config: CrispSourceConfig, team_id: int, api_version: str, schema_name: str | None) -> Resource:+ if schema_name is None:+ endpoint: Endpoint = {+ "path": f"website/{quote(config.website_id, safe='')}",+ "paginator": "single_page",+ "data_selector": "data",+ "data_selector_required": True,+ }+ else:+ settings = schema_for_resource(ENDPOINTS, schema_name)+ if settings.fanout is not None:+ settings = ENDPOINTS[settings.fanout.parent_name]+ endpoint = endpoint_config(settings, config.website_id)+ endpoint["paginator"] = "single_page"+ rest_config: RESTAPIConfig = {+ "client": client_config(config, api_version),+ "resources": [{"name": "credential_probe", "endpoint": endpoint}],+ }+ return rest_api_resource(rest_config, team_id, "crisp_credential_probe", None)+++def crisp_source(+ config: CrispSourceConfig,+ inputs: SourceInputs,+ manager: ResumableSourceManager[CrispResumeConfig],+ api_version: str,+) -> SourceResponse:+ settings = schema_for_resource(ENDPOINTS, inputs.schema_name)+ resume = manager.load_state()++ def save_state(state: dict[str, Any] | None) -> None:+ if state is not None:+ manager.save_state(CrispResumeConfig(paginator_state=state))++ initial_state = resume.paginator_state if resume is not None else None+ if settings.fanout is not None:+ parent = ENDPOINTS[settings.fanout.parent_name]+ parent_endpoint = endpoint_config(parent, config.website_id)+ parent_endpoint.pop("params", None)+ child_endpoint = endpoint_config(settings, config.website_id)+ child_endpoint.pop("params", None)+ child_endpoint["response_actions"] = [+ *settings.fanout.child_response_actions,+ *(child_endpoint.get("response_actions") or []),+ ]+ resource = build_dependent_resource(+ endpoint_configs=ENDPOINTS,+ child_endpoint=settings.name,+ fanout=settings.fanout,+ client_config=client_config(config, api_version),+ path_format_values={"website_id": quote(config.website_id, safe="")},+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra=parent_endpoint,+ child_endpoint_extra=child_endpoint,+ parent_data_map=parent_path_map(settings.fanout.resolve_param),+ page_size_param=None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ assert isinstance(resource, Resource)+ else:+ rest_config: RESTAPIConfig = {+ "client": client_config(config, api_version),+ "resources": [resource_config(settings, config.website_id)],+ }+ resource = rest_api_resource(+ rest_config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ if settings.name == "operators":+ resource.add_filter(lambda row: row.get("type") in ("operator", "sandbox"))+ resource.add_map(normalize_operator)+ resource.add_map(normalize_row)+ return SourceResponse(+ name=settings.name,+ items=lambda: resource,+ primary_keys=list(settings.primary_keys),+ partition_keys=[settings.partition_key] if settings.partition_key else None,+ partition_mode="datetime" if settings.partition_key else None,+ partition_format="month" if settings.partition_key else None,+ sort_mode="desc" if settings.pagination == "messages" else None,+ on_complete=manager.clear_state,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.pynew file mode 100644index 000000000000..63eddce03e19--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/settings.py@@ -0,0 +1,110 @@+from dataclasses import field+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField+++@frozen+class CrispEndpoint:+ name: str+ path: str+ primary_keys: tuple[str, ...]+ partition_key: str | None = None+ pagination: Literal["path", "messages", "single"] = "path"+ params: dict[str, str | int] = field(default_factory=dict)+ fanout: DependentEndpointConfig | None = None+ should_sync_default: bool = True+ page_size: int = 50+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++# Timestamp filters need an authenticated future-date probe before incremental sync can safely use them.+# Campaign listing requires user-tier tokens, so website-token imports exclude campaigns.+ENDPOINTS: dict[str, CrispEndpoint] = {+ "conversations": CrispEndpoint(+ name="conversations",+ path="website/{website_id}/conversations/1",+ primary_keys=("session_id",),+ partition_key="created_at",+ params={"per_page": 50, "include_empty": "1", "filter_inbox_id": "all", "order_date_created": "1"},+ ),+ "messages": CrispEndpoint(+ name="messages",+ path="website/{website_id}/conversation/{session_id}/messages",+ primary_keys=("session_id", "fingerprint"),+ partition_key="timestamp",+ pagination="messages",+ fanout=DependentEndpointConfig(+ parent_name="conversations",+ resolve_param="session_id",+ resolve_field="_path_id",+ include_from_parent=["session_id"],+ parent_field_renames={"session_id": "session_id"},+ parent_params={"per_page": 50, "include_empty": "1", "filter_inbox_id": "all", "order_date_created": "1"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ should_sync_default=False,+ ),+ "people": CrispEndpoint(+ name="people",+ path="website/{website_id}/people/profiles/1",+ primary_keys=("people_id",),+ partition_key="created_at",+ params={"per_page": 50},+ ),+ "people_events": CrispEndpoint(+ name="people_events",+ path="website/{website_id}/people/events/{people_id}/list/1",+ # Events have no documented unique identifier. A timestamp alone can discard distinct events.+ primary_keys=(),+ partition_key="timestamp",+ fanout=DependentEndpointConfig(+ parent_name="people",+ resolve_param="people_id",+ resolve_field="_path_id",+ include_from_parent=["people_id"],+ parent_field_renames={"people_id": "people_id"},+ parent_params={"per_page": 50},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ should_sync_default=False,+ ),+ "operators": CrispEndpoint(+ name="operators",+ path="website/{website_id}/operators/list",+ primary_keys=("user_id",),+ pagination="single",+ ),+ "visitors": CrispEndpoint(+ name="visitors",+ path="website/{website_id}/visitors/list/1",+ primary_keys=("session_id",),+ should_sync_default=False,+ ),+ "helpdesk_locales": CrispEndpoint(+ name="helpdesk_locales",+ path="website/{website_id}/helpdesk/locales/1",+ primary_keys=("locale_id",),+ should_sync_default=False,+ ),+ "helpdesk_articles": CrispEndpoint(+ name="helpdesk_articles",+ path="website/{website_id}/helpdesk/page/list/{locale}/articles/1",+ primary_keys=("locale", "entity_id"),+ fanout=DependentEndpointConfig(+ parent_name="helpdesk_locales",+ resolve_param="locale",+ resolve_field="_path_id",+ include_from_parent=["locale"],+ parent_field_renames={"locale": "locale"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ should_sync_default=False,+ ),+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.pyindex cd7a8f197e6d..4d48bb6c1bf6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/source.py@@ -1,18 +1,120 @@from typing import cast+from uuid import UUID-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.crisp import (+ CrispResumeConfig,+ credential_resource,+ crisp_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CrispSource(SimpleSource[CrispSourceConfig]):+class CrispSource(ResumableSource[CrispSourceConfig, CrispResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://docs.crisp.chat/references/rest-api/v1/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CRISP+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Crisp rejected the token. Enter a valid website token identifier and key.",+ "403 Client Error": "Crisp denied access. Check that the website token belongs to this workspace.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CrispSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(+ ENDPOINTS,+ {name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items()},+ names,+ should_sync_default={name: endpoint.should_sync_default for name, endpoint in ENDPOINTS.items()},+ )+ for schema in schemas:+ schema.detected_primary_keys = list(ENDPOINTS[schema.name].primary_keys)+ return schemas++ def validate_credentials(+ self,+ config: CrispSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ UUID(config.website_id)+ except ValueError:+ return False, "Enter the workspace UUID from Crisp Settings > Workspace Settings > Setup Instructions."+ if not config.token_identifier.isascii() or not config.token_key.isascii() or ":" in config.token_identifier:+ return False, "Enter the website token identifier and key exactly as Crisp provides them."+ try:+ probe = credential_resource(config, team_id, self.resolve_api_version(api_version), schema_name)+ next(iter(probe), None)+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status == 401:+ return False, "Crisp rejected the token. Enter a valid website token identifier and key."+ if status == 403:+ if schema_name is None:+ # Website tokens have no table scopes, so a denied workspace probe must fail validation.+ return False, "Crisp denied access. Check that the website token belongs to this workspace."+ return False, "Crisp denied access to this table. Check the workspace token permissions."+ if status == 404:+ return False, "Crisp could not find the workspace. Check the workspace UUID."+ raise+ return True, None++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CrispResumeConfig]:+ return ResumableSourceManager(inputs, CrispResumeConfig)++ def source_for_pipeline(+ self,+ config: CrispSourceConfig,+ resumable_source_manager: ResumableSourceManager[CrispResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return crisp_source(config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version))+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -20,6 +122,37 @@ class CrispSource(SimpleSource[CrispSourceConfig]):category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Crisp",iconPath="/static/services/crisp.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/crisp",+ caption="Use a website token from Crisp Settings > Workspace Settings > Advanced configuration > API Token.",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="website_id",+ label="Workspace UUID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ secret=False,+ placeholder="00000000-0000-0000-0000-000000000000",+ caption="Find this in Crisp Settings > Workspace Settings > Setup Instructions.",+ ),+ SourceFieldInputConfig(+ name="token_identifier",+ label="Token identifier",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ ),+ SourceFieldInputConfig(+ name="token_key",+ label="Token key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/conftest.pynew file mode 100644index 000000000000..53db87ccd006--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/conftest.py@@ -0,0 +1,12 @@+import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig+++def config() -> CrispSourceConfig:+ return CrispSourceConfig(+ website_id="00000000-0000-4000-8000-000000000001",+ token_identifier="example-identifier",+ token_key="example-key",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.pynew file mode 100644index 000000000000..46975df62197--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp.py@@ -0,0 +1,276 @@+from datetime import UTC, datetime+from typing import Any++import pytest++from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RunStopped,+ ScriptedResponse,+ SourceDriver,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.crisp import CrispResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.source import CrispSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig+++def page(rows: list[dict[str, Any]]) -> ScriptedResponse:+ return ScriptedResponse(json={"error": False, "reason": "listed", "data": rows})+++ ("schema", "path", "key", "params"),+ [+ (+ "conversations",+ "conversations",+ "session_id",+ {"per_page": ("50",), "include_empty": ("1",), "filter_inbox_id": ("all",), "order_date_created": ("1",)},+ ),+ ("people", "people/profiles", "people_id", {"per_page": ("50",)}),+ ("visitors", "visitors/list", "session_id", {}),+ ("helpdesk_locales", "helpdesk/locales", "locale_id", {}),+ ],+)+def test_path_pages_stop_at_short_or_empty_page_and_commit_before_next_request(+ config: CrispSourceConfig, schema: str, path: str, key: str, params: dict[str, tuple[str, ...]]+) -> None:+ first = [{key: str(number), "created_at": 1000} for number in range(50 if "per_page" in params else 1)]+ script = [page(first), page([{key: "last", "created_at": None}])]+ if "per_page" not in params:+ script.append(page([]))+ result = SourceDriver(CrispSource(), config).run(schema, script)+ assert result.raised is None+ assert result.paths == [f"/v1/website/{config.website_id}/{path}/{number}" for number in range(1, len(script) + 1)]+ assert result.queries == [params] * len(script)+ assert [row[key] for row in result.rows] == [row[key] for row in first] + ["last"]+ assert result.rows[0]["created_at"] == datetime.fromtimestamp(1, UTC)+ assert result.rows[-1]["created_at"] is None+ assert result.committed_states == [+ CrispResumeConfig(paginator_state={"page": number}) for number in range(2, len(script) + 1)+ ]++[email protected]("schema", ["conversations", "people"])+def test_out_of_range_page_completes_without_discarding_rows(config: CrispSourceConfig, schema: str) -> None:+ key = "session_id" if schema == "conversations" else "people_id"+ result = SourceDriver(CrispSource(), config).run(+ schema,+ [+ page([{key: str(number)} for number in range(50)]),+ ScriptedResponse(status=416, json={"error": True, "reason": "invalid_page"}),+ ],+ )+ assert result.raised is None+ assert len(result.rows) == 50+ assert result.paths[-1].endswith("/2")+++def test_path_resume_uses_saved_page_after_interruption(config: CrispSourceConfig) -> None:+ driver = SourceDriver(CrispSource(), config)+ stopped = driver.run("visitors", [page([{"session_id": "one"}]), RunStopped("handoff")])+ assert isinstance(stopped.raised, RunStopped)+ assert stopped.saved_states == stopped.committed_states == [CrispResumeConfig(paginator_state={"page": 2})]+ resumed = driver.run(+ "visitors", [page([{"session_id": "two"}]), page([])], resume_state=stopped.committed_states[-1]+ )+ assert resumed.raised is None+ assert resumed.paths[0].endswith("/visitors/list/2")+ assert [row["session_id"] for row in resumed.rows] == ["two"]+++def test_messages_page_backwards_for_each_conversation(config: CrispSourceConfig) -> None:+ result = SourceDriver(CrispSource(), config).run(+ "messages",+ [+ page([{"session_id": "session-one"}, {"session_id": "session-two"}]),+ page(+ [+ {"fingerprint": 2, "timestamp": 1000, "content": "Example"},+ {+ "fingerprint": 3,+ "timestamp": 2000,+ "content": {"type": "file", "url": "https://example.com/file"},+ },+ ]+ ),+ page([{"fingerprint": 1, "timestamp": 500, "content": None}]),+ page([]),+ page([{"fingerprint": 1, "timestamp": 3000}]),+ page([]),+ ],+ )+ assert result.raised is None+ root = f"/v1/website/{config.website_id}"+ assert result.paths == [+ f"{root}/conversations/1",+ *[f"{root}/conversation/session-one/messages"] * 3,+ *[f"{root}/conversation/session-two/messages"] * 2,+ ]+ assert result.params("timestamp_before") == [None, None, "1000", "500", None, "3000"]+ assert [row["session_id"] for row in result.rows] == ["session-one"] * 3 + ["session-two"]+ assert [row["fingerprint"] for row in result.rows] == [2, 3, 1, 1]+ assert result.rows[1]["content"] == {"type": "file", "url": "https://example.com/file"}+ assert result.rows[2]["content"] is None+ assert result.rows[2]["timestamp"] == datetime.fromtimestamp(0.5, UTC)+ assert result.committed_states[0].paginator_state == {+ "completed": [],+ "current": f"website/{config.website_id}/conversation/session-one/messages",+ "child_state": {"timestamp_before": 1000},+ }+++def test_message_resume_skips_finished_conversations_and_restores_timestamp(config: CrispSourceConfig) -> None:+ first_path = f"website/{config.website_id}/conversation/one/messages"+ second_path = f"website/{config.website_id}/conversation/two/messages"+ result = SourceDriver(CrispSource(), config).run(+ "messages",+ [+ page([{"session_id": "one"}, {"session_id": "two"}]),+ page([{"fingerprint": 1, "timestamp": 500}]),+ page([]),+ ],+ resume_state=CrispResumeConfig(+ paginator_state={+ "completed": [first_path],+ "current": second_path,+ "child_state": {"timestamp_before": 1000},+ }+ ),+ )+ assert result.raised is None+ assert result.params("timestamp_before") == [None, "1000", "500"]+ assert [row["session_id"] for row in result.rows] == ["two"]+ assert all("/conversation/one/" not in path for path in result.paths)++[email protected]("second_timestamp", [1000, 2000])+def test_messages_fail_when_timestamp_filter_does_not_advance(config: CrispSourceConfig, second_timestamp: int) -> None:+ result = SourceDriver(CrispSource(), config).run(+ "messages",+ [+ page([{"session_id": "one"}]),+ page([{"fingerprint": 1, "timestamp": 1000}]),+ page([{"fingerprint": 2, "timestamp": second_timestamp}]),+ ],+ )+ assert isinstance(result.raised, ValueError)+ assert "did not advance" in str(result.raised)+ assert len(result.rows) == 1+ assert result.committed_states[-1].paginator_state["child_state"] == {"timestamp_before": 1000}+++ ("schema", "parent_path", "parent", "child_path", "child", "parent_field"),+ [+ (+ "people_events",+ "people/profiles",+ {"people_id": "profile/one"},+ "people/events/profile%2Fone/list",+ {"text": "Example event", "timestamp": 1000, "data": {"count": 2}},+ "people_id",+ ),+ (+ "helpdesk_articles",+ "helpdesk/locales",+ {"locale_id": "locale-one", "locale": "en"},+ "helpdesk/page/list/en/articles",+ {"entity_id": "article-one", "title": "Example article", "url": "https://example.com/help"},+ "locale",+ ),+ ],+)+def test_child_path_pagination_keeps_parent_fields(+ config: CrispSourceConfig,+ schema: str,+ parent_path: str,+ parent: dict[str, Any],+ child_path: str,+ child: dict[str, Any],+ parent_field: str,+) -> None:+ script = [page([parent]), page([child]), page([])]+ if schema == "helpdesk_articles":+ script.append(page([]))+ result = SourceDriver(CrispSource(), config).run(schema, script)+ assert result.raised is None+ root = f"/v1/website/{config.website_id}"+ paths = [+ f"{root}/{parent_path}/1",+ f"{root}/{child_path}/1",+ f"{root}/{child_path}/2",+ ]+ if schema == "helpdesk_articles":+ paths.append(f"{root}/{parent_path}/2")+ assert result.paths == paths+ assert result.rows[0][parent_field] == parent[parent_field]+ assert not any(key.startswith("_path") or key.startswith(f"_{parent_path}") for key in result.rows[0])+ assert result.queries[1:3] == [{}, {}]+++def test_deleted_parent_does_not_drop_other_messages(config: CrispSourceConfig) -> None:+ result = SourceDriver(CrispSource(), config).run(+ "messages",+ [+ page([{"session_id": "deleted"}, {"session_id": "active"}]),+ ScriptedResponse(status=404, json={"error": True, "reason": "not_found"}),+ page([{"fingerprint": 1, "timestamp": 1000}]),+ page([]),+ ],+ )+ assert result.raised is None+ assert [row["session_id"] for row in result.rows] == ["active"]+++def test_operators_exclude_invitation_credentials_and_flatten_details(config: CrispSourceConfig) -> None:+ result = SourceDriver(CrispSource(), config).run(+ "operators",+ [+ page(+ [+ {+ "type": "invite",+ "details": {"email": "[email protected]", "identifier": "fake-invite", "key": "fake-key"},+ },+ {+ "type": "operator",+ "details": {+ "user_id": "operator-one",+ "email": "[email protected]",+ "availability": "online",+ },+ },+ {"type": "sandbox", "details": {"user_id": "developer-one", "email": "[email protected]"}},+ ]+ )+ ],+ )+ assert result.raised is None+ assert result.paths == [f"/v1/website/{config.website_id}/operators/list"]+ assert result.rows == [+ {"type": "operator", "user_id": "operator-one", "email": "[email protected]", "availability": "online"},+ {"type": "sandbox", "user_id": "developer-one", "email": "[email protected]"},+ ]++[email protected]("status", [401, 403])+def test_auth_errors_fail_extraction(config: CrispSourceConfig, status: int) -> None:+ result = SourceDriver(CrispSource(), config).run(+ "people", [ScriptedResponse(status=status, json={"error": True, "reason": "unauthorized"})]+ )+ assert isinstance(result.raised, HTTPError)+ assert len(result.requests) == 1+ assert result.rows == []+++ "body",+ [{"error": True, "reason": "failure", "data": []}, {"error": False, "reason": "listed", "unexpected": []}, {}],+)+def test_bad_envelopes_cannot_complete_as_empty_tables(config: CrispSourceConfig, body: dict[str, Any]) -> None:+ result = SourceDriver(CrispSource(), config).run("conversations", [ScriptedResponse(json=body)])+ assert result.raised is not None+ assert result.rows == []+ assert result.committed_states == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp_source.pynew file mode 100644index 000000000000..25d1db1b9b2c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crisp/tests/test_crisp_source.py@@ -0,0 +1,63 @@+import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.crisp.source import CrispSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.crisp import CrispSourceConfig+++ ("status", "schema", "valid", "message"),+ [+ (200, None, True, None),+ (401, None, False, "Crisp rejected the token"),+ (403, None, False, "Crisp denied access"),+ (403, "people", False, "Crisp denied access to this table"),+ (404, None, False, "Crisp could not find the workspace"),+ (200, "messages", True, None),+ ],+)+def test_credential_probe_maps_workspace_and_table_errors(+ config: CrispSourceConfig, status: int, schema: str | None, valid: bool, message: str | None+) -> None:+ body = {+ "error": status != 200,+ "reason": "resolved" if status == 200 else "unauthorized",+ "data": {"website_id": config.website_id} if schema is None else [],+ }+ with scripted_network([ScriptedResponse(status=status, json=body)]) as network:+ result = CrispSource().validate_credentials(config, team_id=1, schema_name=schema)+ assert result[0] is valid+ if message is None:+ assert result[1] is None+ else:+ assert result[1] is not None and message in result[1]+ request = network.requests_log[0]+ assert request.path == (+ f"/v1/website/{config.website_id}"+ if schema is None+ else f"/v1/website/{config.website_id}/{'conversations/1' if schema == 'messages' else 'people/profiles/1'}"+ )+ assert request.headers["x-crisp-tier"] == "website"+++ ("field", "value", "message"),+ [+ ("website_id", "https://example.com/website", "workspace UUID"),+ ("token_identifier", "example:identifier", "token identifier and key"),+ ("token_identifier", "identifiér", "token identifier and key"),+ ("token_key", "key\u200b", "token identifier and key"),+ ],+)+def test_invalid_credentials_fail_before_network(+ config: CrispSourceConfig, field: str, value: str, message: str+) -> None:+ setattr(config, field, value)+ with scripted_network([]) as network:+ valid, error = CrispSource().validate_credentials(config, team_id=1)+ assert not valid+ assert error is not None and message in error+ assert network.requests_log == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/crisp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/crisp.pyindex 94ea020fa79f..041dd4d4c09a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/crisp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/crisp.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CrispSourceConfig(config.Config):- pass+ website_id: str+ token_identifier: str+ token_key: str