: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 quo import source (#107257)
Tom Owers4db277b5f461
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5bb43941b9c2..d8c7105d39bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -577,6 +577,7 @@ the row lists both.| qualaroo | HTTP | requests | ✅ || qualtrics | HTTP | requests | ✅ || qualys_vmdr | HTTP (XML responses) | requests | ✅ |+| quo | HTTP | requests + `rest_source.RESTClient` | ✅ || railway | HTTP (GraphQL) | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ || ramp | HTTP | requests | ✅ |@@ -1306,7 +1307,6 @@ doesn't conflict with concurrent PRs.- qonto- quay- quickbooks-- quo- railz- raisely- rakendiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/quo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/quo.pyindex 904c8e1c29cd..f926493ff3aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/quo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/quo.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass QuoSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/canonical_descriptions.pynew file mode 100644index 000000000000..0382d550f1bc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/canonical_descriptions.py@@ -0,0 +1,116 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the official Quo API reference (https://www.quo.com/docs/mdx/api-reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "phone_numbers": {+ "description": "The phone numbers in your Quo workspace, with the users assigned to each.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/phone-numbers/list-phone-numbers",+ "columns": {+ "id": "The unique identifier of the Quo phone number.",+ "groupId": "The unique identifier of the group the Quo number belongs to.",+ "name": "The display name of the phone number.",+ "number": "The phone number in E.164 format, including the country code.",+ "formattedNumber": "The phone number in a human-readable format.",+ "users": "The users assigned to the phone number.",+ "restrictions": "Messaging and calling restrictions that apply to the phone number.",+ "createdAt": "Timestamp of when the phone number was added to the account, in ISO 8601 format.",+ "updatedAt": "Timestamp of the last update to the phone number's details, in ISO 8601 format.",+ },+ },+ "users": {+ "description": "The members of your Quo workspace.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/users/list-users",+ "columns": {+ "id": "The unique identifier of the user.",+ "email": "The user's email address.",+ "firstName": "The user's first name.",+ "lastName": "The user's last name.",+ "role": "The user's role in the organization.",+ "createdAt": "Timestamp of user creation, in ISO 8601 format.",+ "updatedAt": "Timestamp of last user update, in ISO 8601 format.",+ },+ },+ "contacts": {+ "description": "The contacts in your Quo workspace, including their default and custom fields.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/contacts/list-contacts",+ "columns": {+ "id": "The unique identifier of the contact.",+ "externalId": "A unique identifier from an external system, set when the contact was created via the API.",+ "source": "The external system the contact came from.",+ "sourceUrl": "A link to the contact in the external system it came from.",+ "defaultFields": "The contact's standard fields: name, company, role, emails and phone numbers.",+ "customFields": "The contact's custom fields, as defined in the workspace's contact custom fields.",+ "createdByUserId": "The unique identifier of the user who created the contact.",+ "createdAt": "Timestamp of contact creation, in ISO 8601 format.",+ "updatedAt": "Timestamp of last contact update, in ISO 8601 format.",+ },+ },+ "contact_custom_fields": {+ "description": "The user-defined custom fields available on contacts in your Quo workspace.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/contact-custom-fields/get-contact-custom-fields",+ "columns": {+ "key": "The identifying key of the custom contact field.",+ "name": "The name of the custom contact field, as set in the Quo interface.",+ "type": "The data type of the custom contact field.",+ },+ },+ "conversations": {+ "description": "The call and message conversations in your Quo workspace, one per phone number and participant set.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/conversations/list-conversations",+ "columns": {+ "id": "The unique identifier of the conversation.",+ "phoneNumberId": "The unique identifier of the Quo phone number associated with the conversation.",+ "participants": "The phone numbers involved in the conversation, excluding your Quo number, in E.164 format.",+ "name": "The display name of the conversation.",+ "assignedTo": "The unique identifier of the user the conversation is assigned to.",+ "lastActivityAt": "Timestamp of the most recent activity in the conversation, in ISO 8601 format.",+ "lastActivityId": "The unique identifier of the most recent activity in the conversation.",+ "mutedUntil": "Timestamp until which the conversation is muted, in ISO 8601 format.",+ "snoozedUntil": "Timestamp until which the conversation is snoozed, in ISO 8601 format.",+ "deletedAt": "Timestamp of when the conversation was deleted, in ISO 8601 format.",+ "createdAt": "Timestamp of conversation creation, in ISO 8601 format.",+ "updatedAt": "Timestamp of last conversation update, in ISO 8601 format.",+ },+ },+ "calls": {+ "description": "The calls made and received on your Quo phone numbers.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/calls/list-calls",+ "columns": {+ "id": "The unique identifier of the call.",+ "phoneNumberId": "The unique identifier of the Quo number associated with the call.",+ "userId": "The unique identifier of the Quo user associated with the call.",+ "participants": "The phone numbers involved in the call, including the Quo number, in E.164 format.",+ "direction": "The direction of the call relative to the Quo number: incoming or outgoing.",+ "status": "The current status of the call.",+ "duration": "The total duration of the call in seconds.",+ "answeredAt": "Timestamp of when the call was answered, in ISO 8601 format.",+ "answeredBy": "The unique identifier of the user who answered the call.",+ "initiatedBy": "The unique identifier of the user who initiated the call.",+ "completedAt": "Timestamp of when the call ended, in ISO 8601 format.",+ "forwardedFrom": "The number the call was forwarded from.",+ "forwardedTo": "The number the call was forwarded to.",+ "createdAt": "Timestamp of when the call record was created, in ISO 8601 format.",+ "updatedAt": "Timestamp of when the call record was last updated, in ISO 8601 format.",+ },+ },+ "messages": {+ "description": "The text messages sent and received on your Quo phone numbers.",+ "docs_url": "https://www.quo.com/docs/mdx/api-reference/messages/list-messages",+ "columns": {+ "id": "The unique identifier of the message.",+ "conversationId": "The unique identifier of the conversation the message belongs to.",+ "phoneNumberId": "The unique identifier of the Quo number the message was sent or received on.",+ "userId": "The unique identifier of the Quo user associated with the message.",+ "to": "The recipient phone numbers in E.164 format. Includes your Quo number for incoming messages.",+ "from": "The sender, typically a phone number in E.164 format.",+ "text": "The content of the message.",+ "media": "Media attached to the message, each with a URL and MIME type.",+ "direction": "The direction of the message relative to the Quo number: incoming or outgoing.",+ "status": "The delivery status of the message.",+ "createdAt": "Timestamp of when the message was created, in ISO 8601 format.",+ "updatedAt": "Timestamp of when the message status was last updated, in ISO 8601 format.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/quo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/quo.pynew file mode 100644index 000000000000..1c6a39ce2aac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/quo.py@@ -0,0 +1,216 @@+from collections.abc import Callable, Iterable, Iterator+from typing import Any, Optional++from requests import Session++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+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.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.settings import (+ QUO_BASE_URL,+ QUO_ENDPOINTS,+ QuoEndpointConfig,+)+++@frozen+class QuoResumeConfig:+ page_token: str+++def _to_iso(value: Any) -> Optional[str]:+ """Coerce an incremental watermark to the ISO 8601 string Quo's `createdAfter`-style filters take."""+ parsed = parse_datetime_value(value)+ return parsed.isoformat() if parsed is not None else None+++def _auth_headers(api_key: str) -> dict[str, str]:+ # Quo takes the raw API key in the Authorization header, with no Bearer prefix.+ return {"Accept": "application/json", "Authorization": api_key}+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is valid. /v1/phone-numbers is a cheap authenticated probe with no required params."""+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{QUO_BASE_URL}/v1/phone-numbers",+ headers=_auth_headers(api_key),+ )+ return ok+++def _build_params(+ config: QuoEndpointConfig, cursor_field: Optional[str], watermark_iso: Optional[str]+) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.page_size is not None:+ params["maxResults"] = config.page_size+ if watermark_iso is not None and cursor_field is not None:+ server_filter = config.incremental_params.get(cursor_field)+ if server_filter is not None:+ params[server_filter] = watermark_iso+ return params+++def _paginate(session: Session, path: str, params: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:+ """Yield pages of `data` rows, following the `nextPageToken` cursor until it runs out."""+ page_token: Optional[str] = None+ while True:+ page_params = dict(params)+ if page_token is not None:+ page_params["pageToken"] = page_token+ response = session.get(f"{QUO_BASE_URL}{path}", params=page_params)+ response.raise_for_status()+ body = response.json()+ rows = body.get("data") or []+ if rows:+ yield rows+ page_token = body.get("nextPageToken")+ if not page_token:+ return+++def _fan_out_rows(api_key: str, config: QuoEndpointConfig, params: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:+ """Fan calls/messages out over the conversations list.++ Quo requires `phoneNumberId` and `participants` on every calls/messages request, and the+ conversations list is the only endpoint that enumerates both. Each (phone number,+ participants) pair is queried once; a call or message belongs to exactly one such pair, so+ rows stay unique within a batch.+ """+ session = make_tracked_session(headers=_auth_headers(api_key), redact_values=(api_key,))+ conversations = QUO_ENDPOINTS["conversations"]+ seen: set[tuple[str, tuple[str, ...]]] = set()+ for conversation_page in _paginate(session, conversations.path, {"maxResults": conversations.page_size}):+ for conversation in conversation_page:+ phone_number_id = conversation.get("phoneNumberId")+ participants = conversation.get("participants") or []+ if not phone_number_id or not participants:+ continue+ if not config.supports_group_conversations and len(participants) > 1:+ # /v1/calls serves one-to-one conversations only, so a group conversation's+ # calls cannot be listed. Skipping it beats a guaranteed 400 per group.+ continue+ pair = (phone_number_id, tuple(sorted(participants)))+ if pair in seen:+ continue+ seen.add(pair)+ # Repeated `participants` keys without brackets is the encoding Quo documents;+ # requests produces that for a list value.+ yield from _paginate(+ session, config.path, {**params, "phoneNumberId": phone_number_id, "participants": participants}+ )+++def _rest_source(+ api_key: str,+ config: QuoEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[QuoResumeConfig],+ params: dict[str, Any],+ db_incremental_field_last_value: Optional[Any],+):+ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": QUO_BASE_URL,+ "headers": {"Accept": "application/json"},+ # The framework auth redacts the key from logs. Quo's Authorization header carries+ # the raw key, which is exactly what api_key auth with the default name sends.+ "auth": {"type": "api_key", "api_key": api_key, "name": "Authorization", "location": "header"},+ # Also used for the endpoints documented as unpaginated: with no nextPageToken in the+ # body it stops after one page, and it follows the cursor if Quo ever adds one.+ "paginator": JSONResponseCursorPaginator(cursor_path="nextPageToken", cursor_param="pageToken"),+ },+ "resources": [+ {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "data_selector": "data",+ "params": params,+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"cursor": resume.page_token}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; the state is saved after the page it covers+ # is yielded, so a crash re-yields that page and merge dedupes it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(QuoResumeConfig(page_token=str(state["cursor"])))++ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def _source_response(endpoint: str, config: QuoEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=[config.primary_key],+ # Quo lists return newest-first and the fan-out restarts per conversation, so rows never+ # arrive globally ascending. "desc" defers the watermark commit to the end of a+ # successful sync instead of checkpointing it mid-run.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def quo_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[QuoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = schema_for_resource(QUO_ENDPOINTS, endpoint)++ last_value = db_incremental_field_last_value if should_use_incremental_field else None+ cursor_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ params = _build_params(config, cursor_field, _to_iso(last_value))++ if config.fan_out_over_conversations:+ return _source_response(endpoint, config, lambda: _fan_out_rows(api_key, config, params))++ resource = _rest_source(+ api_key,+ config,+ team_id,+ job_id,+ resumable_source_manager,+ params,+ last_value,+ )+ return _source_response(endpoint, config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/settings.pynew file mode 100644index 000000000000..08ddea6c915f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/settings.py@@ -0,0 +1,93 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++QUO_BASE_URL = "https://api.quo.com"++# Quo caps `maxResults` at 100 on calls, messages and conversations, and at 50 on contacts.+# The users endpoint declares no maximum in the OpenAPI spec, so it stays on the lower cap.+MAX_PAGE_SIZE = 100+SMALL_PAGE_SIZE = 50+++@frozen+class QuoEndpointConfig:+ name: str+ path: str+ primary_key: str = "id"+ # None means the endpoint returns the full collection in one unpaginated response.+ page_size: int | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Incremental field name -> the server-side query param that filters on it.+ incremental_params: dict[str, str] = field(default_factory=dict)+ # Stable creation-time field used for datetime partitioning, never an updated_at-style+ # field, which would rewrite partitions on every sync.+ partition_key: str | None = None+ # Quo requires `phoneNumberId` and `participants` on every calls/messages request, so those+ # endpoints fan out over the conversations list, which carries both per row.+ fan_out_over_conversations: bool = False+ # /v1/calls serves one-to-one conversations only (`participants` caps at one number);+ # /v1/messages accepts the full participants array of a group conversation.+ supports_group_conversations: bool = True+++QUO_ENDPOINTS: dict[str, QuoEndpointConfig] = {+ "phone_numbers": QuoEndpointConfig(+ name="phone_numbers",+ path="/v1/phone-numbers",+ partition_key="createdAt",+ ),+ "users": QuoEndpointConfig(+ name="users",+ path="/v1/users",+ page_size=SMALL_PAGE_SIZE,+ partition_key="createdAt",+ ),+ "contacts": QuoEndpointConfig(+ name="contacts",+ path="/v1/contacts",+ page_size=SMALL_PAGE_SIZE,+ partition_key="createdAt",+ ),+ "contact_custom_fields": QuoEndpointConfig(+ name="contact_custom_fields",+ path="/v1/contact-custom-fields",+ primary_key="key",+ ),+ "conversations": QuoEndpointConfig(+ name="conversations",+ path="/v1/conversations",+ page_size=MAX_PAGE_SIZE,+ incremental_fields=[incremental_field("createdAt"), incremental_field("updatedAt")],+ incremental_params={"createdAt": "createdAfter", "updatedAt": "updatedAfter"},+ partition_key="createdAt",+ ),+ "calls": QuoEndpointConfig(+ name="calls",+ path="/v1/calls",+ page_size=MAX_PAGE_SIZE,+ incremental_fields=[incremental_field("createdAt")],+ incremental_params={"createdAt": "createdAfter"},+ partition_key="createdAt",+ fan_out_over_conversations=True,+ supports_group_conversations=False,+ ),+ "messages": QuoEndpointConfig(+ name="messages",+ path="/v1/messages",+ page_size=MAX_PAGE_SIZE,+ incremental_fields=[incremental_field("createdAt")],+ incremental_params={"createdAt": "createdAfter"},+ partition_key="createdAt",+ fan_out_over_conversations=True,+ ),+}++ENDPOINTS = tuple(QUO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in QUO_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/source.pyindex 1b206b2fca7d..e488171c2ba6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/source.py@@ -1,28 +1,125 @@-from typing import cast+from typing import Optional, cast-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 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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.quo import QuoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.quo import (+ QuoResumeConfig,+ quo_source,+ validate_credentials as validate_quo_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class QuoSource(SimpleSource[QuoSourceConfig]):- api_docs_url = "https://www.quo.com/api"+class QuoSource(ResumableSource[QuoSourceConfig, QuoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs++ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://www.quo.com/docs/mdx/api-reference/changelog"@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.QUO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.quo.com": "Quo authentication failed. Check that your API key is correct and still active, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.quo.com": "Quo denied access. Check that the API key was created by a workspace owner or admin.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.quo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: QuoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: QuoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_quo_credentials(config.api_key):+ return True, None++ return False, "Invalid Quo API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[QuoResumeConfig]:+ return ResumableSourceManager[QuoResumeConfig](inputs, QuoResumeConfig)++ def source_for_pipeline(+ self,+ config: QuoSourceConfig,+ resumable_source_manager: ResumableSourceManager[QuoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return quo_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.QUO,category=DataWarehouseSourceCategory.COMMUNICATION,label="Quo",- keywords=["openphone", "phone", "sms"],+ caption="""Enter your Quo API key to pull your Quo (formerly OpenPhone) data into the PostHog Data warehouse.++You can generate an API key in your Quo workspace settings, under the API tab. You need workspace owner or admin access to do this.""",+ keywords=["openphone", "phone", "sms", "calls"],iconPath="/static/services/quo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/quo",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo.pynew file mode 100644index 000000000000..035f79d9b4c1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo.py@@ -0,0 +1,366 @@+import json+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.quo import (+ QuoResumeConfig,+ _to_iso,+ quo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.settings import ENDPOINTS, QUO_ENDPOINTS++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials and the fan-out build their own tracked session in the quo module.+QUO_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.quo.quo.make_tracked_session"++WATERMARK = datetime(2026, 1, 1, tzinfo=UTC)+WATERMARK_ISO = "2026-01-01T00:00:00+00:00"+++def _body(items: list[dict[str, Any]], next_page_token: str | None) -> dict[str, Any]:+ body: dict[str, Any] = {"data": items}+ if next_page_token is not None:+ body["nextPageToken"] = next_page_token+ return body+++def _response(items: list[dict[str, Any]], next_page_token: str | None = None) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(_body(items, next_page_token)).encode()+ return resp+++def _json_response(items: list[dict[str, Any]], next_page_token: str | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = 200+ resp.json.return_value = _body(items, next_page_token)+ return resp+++def _make_manager(resume_state: QuoResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list capturing each request AT PREPARE TIME.++ ``request.params``/``request.url`` are mutated in place across pages, so inspecting them+ after the run shows only the final state; snapshot a copy when each request is prepared.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return quo_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestToIso:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (datetime(2026, 1, 1, tzinfo=UTC), "2026-01-01T00:00:00+00:00"),+ (datetime(2026, 1, 1), "2026-01-01T00:00:00+00:00"),+ (date(2026, 1, 2), "2026-01-02T00:00:00+00:00"),+ ("2026-01-01T00:00:00Z", "2026-01-01T00:00:00+00:00"),+ (1700000000, None),+ ],+ )+ def test_to_iso_values(self, value: Any, expected: Optional[str]):+ assert _to_iso(value) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(QUO_SESSION_PATCH)+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)++ assert validate_credentials("key") is expected++ @mock.patch(QUO_SESSION_PATCH)+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key") is False++ @mock.patch(QUO_SESSION_PATCH)+ def test_validate_credentials_probes_phone_numbers_with_raw_key(self, mock_session):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)++ validate_credentials("key")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.quo.com/v1/phone-numbers"+ # Quo takes the raw key in the Authorization header, with no Bearer prefix.+ assert call.kwargs["headers"]["Authorization"] == "key"+++class TestTopLevelPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_via_page_token(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(+ session,+ [+ _response([{"id": "US1"}, {"id": "US2"}], next_page_token="tok"),+ _response([{"id": "US3"}]),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("users", manager))++ assert [row["id"] for row in rows] == ["US1", "US2", "US3"]+ assert requests_seen[0]["params"] == {"maxResults": 50}+ assert requests_seen[1]["params"] == {"maxResults": 50, "pageToken": "tok"}+ # State is saved only while a next page exists.+ manager.save_state.assert_called_once_with(QuoResumeConfig(page_token="tok"))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_requests_carry_api_key_in_authorization_header(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_response([{"id": "US1"}])])++ _rows(_source("users", _make_manager()))++ auth = requests_seen[0]["auth"]+ assert isinstance(auth, APIKeyAuth)+ assert auth.name == "Authorization"+ assert auth.api_key == "key"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_state(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_response([{"id": "US9"}])])++ manager = _make_manager(QuoResumeConfig(page_token="tok5"))+ rows = _rows(_source("users", manager))++ assert [row["id"] for row in rows] == ["US9"]+ assert requests_seen[0]["params"]["pageToken"] == "tok5"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unpaginated_endpoint_issues_one_request_without_page_size(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_response([{"id": "PN1"}])])++ rows = _rows(_source("phone_numbers", _make_manager()))++ assert [row["id"] for row in rows] == ["PN1"]+ assert len(requests_seen) == 1+ assert requests_seen[0]["params"] == {}++ @pytest.mark.parametrize(+ "incremental_field, expected_param",+ [+ ("createdAt", "createdAfter"),+ ("updatedAt", "updatedAfter"),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_run_maps_cursor_field_to_server_filter(self, MockSession, incremental_field, expected_param):+ session = MockSession.return_value+ requests_seen = _wire(session, [_response([{"id": "CN1"}])])++ _rows(+ _source(+ "conversations",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=WATERMARK,+ incremental_field=incremental_field,+ )+ )++ assert requests_seen[0]["params"] == {"maxResults": 100, expected_param: WATERMARK_ISO}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_omits_time_filters(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_response([{"id": "CN1"}])])++ _rows(_source("conversations", _make_manager()))++ assert requests_seen[0]["params"] == {"maxResults": 100}+++class TestFanOut:+ def _fan_out_requests(self, session: mock.MagicMock) -> list[tuple[str, dict[str, Any]]]:+ return [(call.args[0], dict(call.kwargs.get("params") or {})) for call in session.get.call_args_list]++ @mock.patch(QUO_SESSION_PATCH)+ def test_calls_fan_out_per_conversation(self, mock_session):+ session = mock_session.return_value+ session.get.side_effect = [+ _json_response(+ [+ {"id": "CN1", "phoneNumberId": "PN1", "participants": ["+15550001"]},+ {"id": "CN2", "phoneNumberId": "PN2", "participants": ["+15550002"]},+ ]+ ),+ _json_response([{"id": "AC1"}]),+ _json_response([{"id": "AC2"}]),+ ]++ rows = _rows(_source("calls", _make_manager()))++ assert [row["id"] for row in rows] == ["AC1", "AC2"]+ requests_seen = self._fan_out_requests(session)+ assert requests_seen[0] == ("https://api.quo.com/v1/conversations", {"maxResults": 100})+ assert requests_seen[1] == (+ "https://api.quo.com/v1/calls",+ {"maxResults": 100, "phoneNumberId": "PN1", "participants": ["+15550001"]},+ )+ assert requests_seen[2] == (+ "https://api.quo.com/v1/calls",+ {"maxResults": 100, "phoneNumberId": "PN2", "participants": ["+15550002"]},+ )++ @pytest.mark.parametrize(+ "endpoint, expected_group_queried",+ [+ # /v1/calls serves one-to-one conversations only; /v1/messages accepts the group's+ # full participants array.+ ("calls", False),+ ("messages", True),+ ],+ )+ @mock.patch(QUO_SESSION_PATCH)+ def test_group_conversations_skipped_for_calls_only(self, mock_session, endpoint, expected_group_queried):+ session = mock_session.return_value+ group_conversation = {"id": "CN1", "phoneNumberId": "PN1", "participants": ["+15550001", "+15550002"]}+ one_to_one = {"id": "CN2", "phoneNumberId": "PN1", "participants": ["+15550003"]}+ child_pages = [_json_response([{"id": "A1"}])]+ if expected_group_queried:+ child_pages.append(_json_response([{"id": "A2"}]))+ session.get.side_effect = [_json_response([group_conversation, one_to_one]), *child_pages]++ _rows(_source(endpoint, _make_manager()))++ child_requests = self._fan_out_requests(session)[1:]+ participants_queried = [params["participants"] for _url, params in child_requests]+ if expected_group_queried:+ assert participants_queried == [["+15550001", "+15550002"], ["+15550003"]]+ else:+ assert participants_queried == [["+15550003"]]++ @mock.patch(QUO_SESSION_PATCH)+ def test_duplicate_and_incomplete_conversations_produce_no_extra_requests(self, mock_session):+ session = mock_session.return_value+ session.get.side_effect = [+ _json_response(+ [+ {"id": "CN1", "phoneNumberId": "PN1", "participants": ["+15550001"]},+ # Same pair again (e.g. a deleted and recreated conversation).+ {"id": "CN2", "phoneNumberId": "PN1", "participants": ["+15550001"]},+ {"id": "CN3", "phoneNumberId": None, "participants": ["+15550002"]},+ {"id": "CN4", "phoneNumberId": "PN1", "participants": []},+ ]+ ),+ _json_response([{"id": "AM1"}]),+ ]++ rows = _rows(_source("messages", _make_manager()))++ assert [row["id"] for row in rows] == ["AM1"]+ assert len(session.get.call_args_list) == 2++ @mock.patch(QUO_SESSION_PATCH)+ def test_child_pagination_follows_page_token(self, mock_session):+ session = mock_session.return_value+ session.get.side_effect = [+ _json_response([{"id": "CN1", "phoneNumberId": "PN1", "participants": ["+15550001"]}]),+ _json_response([{"id": "AC1"}], next_page_token="tok"),+ _json_response([{"id": "AC2"}]),+ ]++ rows = _rows(_source("calls", _make_manager()))++ assert [row["id"] for row in rows] == ["AC1", "AC2"]+ requests_seen = self._fan_out_requests(session)+ assert requests_seen[2][1]["pageToken"] == "tok"++ @mock.patch(QUO_SESSION_PATCH)+ def test_incremental_watermark_applied_to_child_requests_only(self, mock_session):+ session = mock_session.return_value+ session.get.side_effect = [+ _json_response([{"id": "CN1", "phoneNumberId": "PN1", "participants": ["+15550001"]}]),+ _json_response([{"id": "AC1"}]),+ ]++ _rows(+ _source(+ "calls",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=WATERMARK,+ incremental_field="createdAt",+ )+ )++ requests_seen = self._fan_out_requests(session)+ # The parent walk stays unfiltered: an old conversation can still receive new calls.+ assert "createdAfter" not in requests_seen[0][1]+ assert requests_seen[1][1]["createdAfter"] == WATERMARK_ISO+++class TestQuoSourceResponse:+ def test_unknown_endpoint_raises_unknown_resource(self):+ with pytest.raises(UnknownResourceError):+ _source("not_a_table", _make_manager())++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_response_metadata_per_endpoint(self, MockSession, endpoint):+ config = QUO_ENDPOINTS[endpoint]+ response = _source(endpoint, _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ # Quo lists return newest-first, so the watermark must only commit at sync end.+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(QUO_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "createdAt"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo_source.pynew file mode 100644index 000000000000..052dc5ad0579--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/quo/tests/test_quo_source.py@@ -0,0 +1,52 @@+import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.quo import QuoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.quo.source import QuoSource+++class TestQuoSource:+ def setup_method(self):+ self.source = QuoSource()+ self.team_id = 123+ self.config = QuoSourceConfig(api_key="test-key")++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.quo.com/v1/conversations?maxResults=100",+ "403 Client Error: Forbidden for url: https://api.quo.com/v1/calls?phoneNumberId=PN1",+ ],+ )+ def test_non_retryable_errors_match_quo_client_errors(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.quo.com/v1/calls",+ "429 Client Error: Too Many Requests for url: https://api.quo.com/v1/messages",+ ],+ )+ def test_non_retryable_errors_do_not_match_retryable_or_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Quo API key"),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.quo.source.validate_quo_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key)