: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 plivo import source (#72612)
Tom Owersd0671afb0be6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a161c699ec36..0fa044e1ca5a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -425,6 +425,7 @@ the row lists both.| planhat | HTTP | requests | ✅ || platform_sh | HTTP | requests | ✅ || plausible | HTTP | requests | ✅ |+| plivo | HTTP | requests + `rest_source.RESTClient` | ✅ || polar | HTTP | requests | ✅ || plaid | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |@@ -869,7 +870,6 @@ doesn't conflict with concurrent PRs.- pivotal_tracker- piwik- planetscale-- plivo- plunk- podiumdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plivo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plivo.pyindex 7ceb0ee13715..7ef5101c7fdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plivo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/plivo.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PlivoSourceConfig(config.Config):- pass+ auth_id: str+ auth_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/canonical_descriptions.pynew file mode 100644index 000000000000..2fdcbcc9eb34--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "messages": {+ "description": "A message detail record (MDR) for each SMS or MMS sent or received through Plivo.",+ "docs_url": "https://www.plivo.com/docs/sms/api/message",+ "columns": {+ "message_uuid": "Unique identifier of the message.",+ "message_time": "Time at which the message was sent or received, in UTC.",+ "message_direction": "Direction of the message: inbound or outbound.",+ "message_state": "Delivery status of the message (e.g. queued, sent, delivered, failed, undelivered).",+ "message_type": "Type of the message: sms, mms, or whatsapp.",+ "from_number": "Phone number or sender ID the message was sent from.",+ "to_number": "Phone number the message was sent to.",+ "units": "Number of billing units the message was split into.",+ "total_rate": "Per-unit rate charged for the message, in your account currency.",+ "total_amount": "Total amount charged for the message, in your account currency.",+ "error_code": "Plivo error code when the message failed or was undelivered.",+ "destination_country_iso2": "ISO 3166-1 alpha-2 code of the destination phone number's country.",+ "powerpack_id": "Identifier of the Powerpack used to send the message, if any.",+ "requester_ip": "IP address the send-message API request originated from.",+ "resource_uri": "URI of the message resource on the Plivo API.",+ },+ },+ "calls": {+ "description": "A call detail record (CDR) for each completed voice call made or received through Plivo.",+ "docs_url": "https://www.plivo.com/docs/voice/api/call",+ "columns": {+ "call_uuid": "Unique identifier of the call.",+ "from_number": "Phone number or endpoint the call originated from.",+ "to_number": "Phone number or endpoint the call was placed to.",+ "initiation_time": "Time at which the call was initiated.",+ "answer_time": "Time at which the call was answered.",+ "end_time": "Time at which the call ended.",+ "call_duration": "Total duration of the call in seconds.",+ "bill_duration": "Duration of the call that was billed, in seconds.",+ "total_rate": "Per-minute rate charged for the call, in your account currency.",+ "total_amount": "Total amount charged for the call, in your account currency.",+ "call_direction": "Direction of the call: inbound or outbound.",+ "call_state": "Final state of the call (e.g. ANSWER, BUSY, NO_ANSWER, FAILED).",+ "hangup_cause_name": "Reason the call ended (e.g. Normal Hangup, Busy Line).",+ "hangup_cause_code": "Numeric Plivo hangup cause code.",+ "hangup_source": "Which party or system ended the call.",+ "parent_call_uuid": "Identifier of the parent call for calls created by a transfer or dial.",+ "resource_uri": "URI of the call resource on the Plivo API.",+ },+ },+ "recordings": {+ "description": "A recording of a call or conference stored on your Plivo account.",+ "docs_url": "https://www.plivo.com/docs/voice/api/recording",+ "columns": {+ "recording_id": "Unique identifier of the recording.",+ "add_time": "Time at which the recording was created.",+ "call_uuid": "Identifier of the call the recording belongs to.",+ "conference_name": "Name of the conference that was recorded, if any.",+ "recording_url": "URL where the recording file can be fetched.",+ "recording_duration_ms": "Duration of the recording in milliseconds.",+ "recording_format": "Audio format of the recording file (e.g. mp3, wav).",+ "recording_type": "Whether the recording is of a call or a conference.",+ "recording_channels": "Number of audio channels in the recording.",+ "from_number": "Phone number the recorded call originated from.",+ "to_number": "Phone number the recorded call was placed to.",+ "resource_uri": "URI of the recording resource on the Plivo API.",+ },+ },+ "applications": {+ "description": "A Plivo application defining how incoming calls and messages to your numbers and endpoints are handled.",+ "docs_url": "https://www.plivo.com/docs/voice/api/application",+ "columns": {+ "app_id": "Unique identifier of the application.",+ "app_name": "Name of the application.",+ "answer_url": "URL Plivo invokes to fetch instructions when a call is answered.",+ "answer_method": "HTTP method used to invoke the answer URL.",+ "hangup_url": "URL notified when a call ends.",+ "message_url": "URL Plivo invokes when a message is received.",+ "default_number_app": "Whether this is the default application for your numbers.",+ "default_endpoint_app": "Whether this is the default application for your endpoints.",+ "enabled": "Whether the application is enabled.",+ "sub_account": "Subaccount the application belongs to, if any.",+ "resource_uri": "URI of the application resource on the Plivo API.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/plivo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/plivo.pynew file mode 100644index 000000000000..1c04e2e6a4a2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/plivo.py@@ -0,0 +1,231 @@+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++from dateutil import parser as dateutil_parser++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.rest_source.auth import HttpBasicAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+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.plivo.settings import (+ MAX_QUERY_RANGE_DAYS,+ PAGE_SIZE,+ PLIVO_BASE_URL,+ PLIVO_ENDPOINTS,+ RETENTION_DAYS,+ PlivoEndpointConfig,+)+++class PlivoResumeConfig:+ # ISO start/end of the <=30-day window being paged. Both None for non-windowed endpoints.+ # window_end pins the resumed window's upper bound so re-deriving it against a later "now"+ # can't shift offsets mid-window.+ window_start: str | None = None+ window_end: str | None = None+ # Next page offset within the current window/listing.+ offset: int = 0+++def _coerce_datetime(value: Any) -> datetime:+ """Coerce an incremental cursor / resume value into an aware UTC datetime."""+ if isinstance(value, datetime):+ return value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ parsed = dateutil_parser.parse(str(value))+ return parsed.astimezone(UTC) if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def _format_filter_value(dt: datetime) -> str:+ """Plivo time filters take `yyyy-MM-dd HH:mm:ss` in UTC."""+ return dt.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S")+++def _build_windows(start: datetime, end: datetime) -> list[tuple[datetime, datetime]]:+ """Contiguous (start, end] slices of at most MAX_QUERY_RANGE_DAYS covering [start, end]."""+ windows: list[tuple[datetime, datetime]] = []+ window_start = start+ step = timedelta(days=MAX_QUERY_RANGE_DAYS)+ while window_start < end:+ window_end = min(window_start + step, end)+ windows.append((window_start, window_end))+ window_start = window_end+ return windows+++def _normalize_row(row: dict[str, Any], config: PlivoEndpointConfig) -> dict[str, Any]:+ """Parse Plivo's timestamp strings into datetimes so incremental watermarks and datetime+ partitioning operate on real timestamps rather than lexicographic strings."""+ for field_name in config.datetime_fields:+ value = row.get(field_name)+ if isinstance(value, str) and value:+ try:+ row[field_name] = dateutil_parser.parse(value)+ except (ValueError, OverflowError):+ pass # leave the raw string for a value we can't parse+ return row+++def _make_client(auth_id: str, auth_token: str) -> RESTClient:+ return RESTClient(base_url=PLIVO_BASE_URL, auth=HttpBasicAuth(auth_id, auth_token))+++def _paginate(+ client: RESTClient,+ path: str,+ params: dict[str, Any],+ config: PlivoEndpointConfig,+ initial_offset: int,+ on_checkpoint: Callable[[int | None], None],+) -> Iterator[list[dict[str, Any]]]:+ """Walk one offset-paginated listing, yielding normalized row pages.++ `on_checkpoint(offset | None)` fires after each yielded page has been consumed downstream —+ with the next page's offset while more pages remain, then `None` once the listing is done.+ """+ paginator = OffsetPaginator(+ limit=PAGE_SIZE,+ offset=initial_offset,+ total_path="meta.total_count",+ )++ def resume_hook(state: Optional[dict[str, Any]]) -> None:+ on_checkpoint(int(state["offset"]) if state else None)++ for page in client.paginate(+ path=path,+ params=params,+ paginator=paginator,+ data_selector="objects",+ resume_hook=resume_hook,+ ):+ yield [_normalize_row(row, config) for row in page]+++def get_rows(+ auth_id: str,+ auth_token: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[PlivoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PLIVO_ENDPOINTS[endpoint]+ client = _make_client(auth_id, auth_token)+ path = f"Account/{auth_id}/{config.path}"+ now = datetime.now(UTC)++ filter_field = incremental_field if should_use_incremental_field and incremental_field else config.time_filter_field++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if not config.windowed:+ params: dict[str, Any] = {}+ if should_use_incremental_field and db_incremental_field_last_value is not None and filter_field:+ params[f"{filter_field}__gt"] = _format_filter_value(_coerce_datetime(db_incremental_field_last_value))++ def checkpoint(offset: int | None) -> None:+ # Save AFTER each yielded page so a crash re-yields the last page (merge dedupes on+ # the primary key). Nothing to checkpoint once the listing is exhausted.+ if offset is not None:+ resumable_source_manager.save_state(PlivoResumeConfig(offset=offset))++ yield from _paginate(client, path, params, config, resume.offset if resume else 0, checkpoint)+ return++ # Windowed endpoints (MDRs/CDRs): Plivo rejects list requests spanning more than 30 days and+ # only retains 90 days, so fetch contiguous <=30-day windows from the effective start to now.+ if resume is not None and resume.window_start:+ start = _coerce_datetime(resume.window_start)+ elif should_use_incremental_field and db_incremental_field_last_value is not None:+ # Records older than the retention window are gone server-side; don't request them.+ start = max(_coerce_datetime(db_incremental_field_last_value), now - timedelta(days=RETENTION_DAYS))+ else:+ start = now - timedelta(days=RETENTION_DAYS)++ windows = _build_windows(start, now)+ if resume is not None and resume.window_end and windows:+ # Pin the resumed window's saved upper bound so its page offsets stay aligned.+ resumed_end = _coerce_datetime(resume.window_end)+ windows[0] = (windows[0][0], resumed_end)+ windows[1:] = _build_windows(resumed_end, now)++ for index, (window_start, window_end) in enumerate(windows):+ params = {+ f"{filter_field}__gt": _format_filter_value(window_start),+ f"{filter_field}__lte": _format_filter_value(window_end),+ }+ # The saved page offset only applies to the window the crashed attempt was mid-way through.+ initial_offset = resume.offset if (index == 0 and resume is not None and resume.window_start) else 0++ window_start_iso = window_start.isoformat()+ window_end_iso = window_end.isoformat()++ def window_checkpoint(+ offset: int | None, window_start_iso: str = window_start_iso, window_end_iso: str = window_end_iso+ ) -> None:+ if offset is not None:+ resumable_source_manager.save_state(+ PlivoResumeConfig(window_start=window_start_iso, window_end=window_end_iso, offset=offset)+ )+ else:+ # Window exhausted: point the checkpoint at the next window's start so a retry+ # skips everything already synced. For the final window this leaves a checkpoint+ # at "now", so a late retry only fetches the gap since this run.+ resumable_source_manager.save_state(PlivoResumeConfig(window_start=window_end_iso, offset=0))++ yield from _paginate(client, path, params, config, initial_offset, window_checkpoint)+++def plivo_source(+ auth_id: str,+ auth_token: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[PlivoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = PLIVO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ auth_id=auth_id,+ auth_token=auth_token,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ 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,+ # Plivo lists return newest-first within a listing/window and expose no sort param, so the+ # stream is not globally ascending. "desc" makes the pipeline persist the incremental+ # watermark only after a fully successful run instead of checkpointing per batch.+ 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 validate_credentials(auth_id: str, auth_token: str) -> bool:+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(auth_token,)),+ f"{PLIVO_BASE_URL}/Account/{auth_id}/",+ auth=HttpBasicAuth(auth_id, auth_token),+ )+ return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/settings.pynew file mode 100644index 000000000000..17c93813fe41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++PLIVO_BASE_URL = "https://api.plivo.com/v1"++# Plivo list endpoints cap `limit` at 20 records per page.+PAGE_SIZE = 20++# Message (MDR) and call (CDR) records are retained for 90 days, and a single list request+# may only span a 30-day time range (Plivo returns a 400 beyond that). Windowed endpoints+# chunk their fetch into <= 30-day slices covering at most the retention window.+RETENTION_DAYS = 90+MAX_QUERY_RANGE_DAYS = 30+++@dataclass+class PlivoEndpointConfig:+ name: str+ # Path relative to /v1/Account/{auth_id}/, e.g. "Message/".+ path: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # The record timestamp used for server-side `<field>__gt` / `<field>__lte` filters.+ time_filter_field: str | None = None+ # Stable creation-style timestamp used for datetime partitioning.+ partition_key: str | None = None+ # Response fields parsed from Plivo's timestamp strings into datetimes.+ datetime_fields: tuple[str, ...] = ()+ # Whether requests must be chunked into MAX_QUERY_RANGE_DAYS windows over RETENTION_DAYS.+ windowed: bool = False+++PLIVO_ENDPOINTS: dict[str, PlivoEndpointConfig] = {+ "messages": PlivoEndpointConfig(+ name="messages",+ path="Message/",+ primary_keys=["message_uuid"],+ incremental_fields=[incremental_field("message_time")],+ time_filter_field="message_time",+ # message_time is the send/receive time and never changes for a message_uuid.+ partition_key="message_time",+ datetime_fields=("message_time",),+ windowed=True,+ ),+ "calls": PlivoEndpointConfig(+ name="calls",+ path="Call/",+ primary_keys=["call_uuid"],+ incremental_fields=[incremental_field("end_time")],+ time_filter_field="end_time",+ # The call list only returns completed calls, whose end_time is immutable.+ partition_key="end_time",+ datetime_fields=("initiation_time", "answer_time", "end_time"),+ windowed=True,+ ),+ "recordings": PlivoEndpointConfig(+ name="recordings",+ path="Recording/",+ primary_keys=["recording_id"],+ incremental_fields=[incremental_field("add_time")],+ time_filter_field="add_time",+ partition_key="add_time",+ datetime_fields=("add_time",),+ # Recordings are stored until deleted (no 90-day retention), so the first sync must+ # walk the full history rather than a retention-bounded window.+ windowed=False,+ ),+ "applications": PlivoEndpointConfig(+ name="applications",+ path="Application/",+ primary_keys=["app_id"],+ # The application list exposes no server-side time filter — full refresh only.+ ),+}++ENDPOINTS = tuple(PLIVO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PLIVO_ENDPOINTS.items()+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "messages": (+ "Message detail records (MDRs) for every SMS/MMS sent or received. "+ "Plivo retains messages for 90 days, so the first sync backfills at most that window."+ ),+ "calls": (+ "Call detail records (CDRs) for completed voice calls. "+ "Plivo retains call records for 90 days, so the first sync backfills at most that window."+ ),+ "recordings": "Call and conference recordings stored on your Plivo account.",+ "applications": "Plivo applications that control how calls and messages to your numbers are handled.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/source.pyindex 32dcba4ff385..b0a34ce37406 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/source.py@@ -1,19 +1,48 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.plivo import PlivoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.plivo import (+ PlivoResumeConfig,+ plivo_source,+ validate_credentials as validate_plivo_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PLIVO_BASE_URL,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PlivoSource(SimpleSource[PlivoSourceConfig]):+class PlivoSource(ResumableSource[PlivoSourceConfig, PlivoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://www.plivo.com/docs/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PLIVO@@ -24,7 +53,101 @@ class PlivoSource(SimpleSource[PlivoSourceConfig]):name=SchemaExternalDataSourceType.PLIVO,category=DataWarehouseSourceCategory.COMMUNICATION,label="Plivo",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["sms", "voice", "cpaas"],+ caption=(+ "Enter your Plivo Auth ID and Auth Token to sync your SMS message and voice call "+ "detail records into the PostHog Data warehouse. Both are shown on the overview page "+ "of the [Plivo console](https://console.plivo.com/dashboard/).\n\n"+ "Plivo retains message and call records for **90 days**, so syncing them into the "+ "warehouse lets you keep history beyond that window."+ ),iconPath="/static/services/plivo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/plivo",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="auth_id",+ label="Auth ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="MAXXXXXXXXXXXXXXXXXX",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="auth_token",+ label="Auth token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Plivo returns 401 for a bad Auth ID/Token pair and 403 for a valid credential that lacks+ # access to the resource; neither can succeed on retry.+ auth_message = (+ "Plivo authentication failed. Check the Auth ID and Auth Token from your Plivo console and reconnect."+ )+ return {+ f"401 Client Error: Unauthorized for url: {PLIVO_BASE_URL}": auth_message,+ f"403 Client Error: Forbidden for url: {PLIVO_BASE_URL}": (+ "Your Plivo credentials don't have access to this resource. "+ "Check the account's permissions in the Plivo console."+ ),+ }++ def get_schemas(+ self,+ config: PlivoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions=ENDPOINT_DESCRIPTIONS,+ )++ def validate_credentials(+ self, config: PlivoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_plivo_credentials(config.auth_id, config.auth_token):+ return True, None++ return False, "Invalid Plivo Auth ID or Auth Token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlivoResumeConfig]:+ return ResumableSourceManager[PlivoResumeConfig](inputs, PlivoResumeConfig)++ def source_for_pipeline(+ self,+ config: PlivoSourceConfig,+ resumable_source_manager: ResumableSourceManager[PlivoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return plivo_source(+ auth_id=config.auth_id,+ auth_token=config.auth_token,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.pynew file mode 100644index 000000000000..49501db1ffa7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py@@ -0,0 +1,284 @@+import json+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.plivo import (+ PlivoResumeConfig,+ _build_windows,+ get_rows,+ plivo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.settings import ENDPOINTS, PAGE_SIZE++# 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 builds its own tracked session in the plivo module.+PLIVO_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.plivo.plivo.make_tracked_session"+)++FROZEN_NOW = "2026-07-21 12:00:00"+MESSAGE_URL = "https://api.plivo.com/v1/Account/MA123/Message/"+++def _make_manager(resume_state: PlivoResumeConfig | 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 _page(objects: list[dict[str, Any]], total_count: int) -> dict[str, Any]:+ return {"meta": {"limit": PAGE_SIZE, "total_count": total_count}, "objects": objects}+++def _wire(session: mock.MagicMock, respond: Callable[[str, dict[str, Any]], dict[str, Any]]) -> list[dict[str, Any]]:+ """Wire a mock session that routes each request through `respond(url, params)`.++ Params are snapshotted at prepare time — the paginator mutates the params dict in place+ across pages, so inspecting it after the run would only show the final state.+ """+ session.headers = {}+ calls: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snap = {"url": request.url, "params": dict(request.params or {})}+ calls.append(snap)+ prepared = mock.MagicMock()+ prepared.url = request.url+ prepared.snap = snap+ return prepared++ def _send(prepared: Any, **kwargs: Any) -> Response:+ resp = Response()+ resp.status_code = 200+ resp.url = prepared.url+ resp._content = json.dumps(respond(prepared.snap["url"], prepared.snap["params"])).encode()+ return resp++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = _send+ return calls+++def _run(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> list[list[dict[str, Any]]]:+ return list(+ get_rows(+ auth_id="MA123",+ auth_token="token",+ endpoint=endpoint,+ resumable_source_manager=manager,+ **kwargs,+ )+ )+++class TestBuildWindows:+ @pytest.mark.parametrize(+ "start_days_ago, expected_boundaries",+ [+ # 90-day span chunks into three contiguous 30-day windows.+ (90, ["2026-04-22 12:00", "2026-05-22 12:00", "2026-06-21 12:00", "2026-07-21 12:00"]),+ # A span under 30 days is a single window.+ (10, ["2026-07-11 12:00", "2026-07-21 12:00"]),+ # A start at/after the end yields no windows (e.g. a future-dated cursor).+ (0, ["2026-07-21 12:00"]),+ (-5, []),+ ],+ )+ def test_windows_are_contiguous_and_capped_at_30_days(self, start_days_ago, expected_boundaries):+ end = datetime(2026, 7, 21, 12, 0, 0, tzinfo=UTC)+ windows = _build_windows(end - timedelta(days=start_days_ago), end)++ if len(expected_boundaries) < 2:+ assert windows == []+ return++ boundaries = [windows[0][0], *(w[1] for w in windows)]+ assert [b.strftime("%Y-%m-%d %H:%M") for b in boundaries] == expected_boundaries+ assert all(we - ws <= timedelta(days=30) for ws, we in windows)+++@freeze_time(FROZEN_NOW)+class TestWindowedEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_walks_retention_in_30_day_windows(self, MockSession: mock.MagicMock) -> None:+ calls = _wire(MockSession.return_value, lambda url, params: _page([], 0))++ _run("messages", _make_manager())++ # 90 days of retention → three contiguous 30-day windows, each filtered server-side.+ windows = [(c["params"]["message_time__gt"], c["params"]["message_time__lte"]) for c in calls]+ assert windows == [+ ("2026-04-22 12:00:00", "2026-05-22 12:00:00"),+ ("2026-05-22 12:00:00", "2026-06-21 12:00:00"),+ ("2026-06-21 12:00:00", "2026-07-21 12:00:00"),+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_starts_at_cursor_and_filters_server_side(self, MockSession: mock.MagicMock) -> None:+ calls = _wire(+ MockSession.return_value,+ lambda url, params: _page([{"message_uuid": "m1", "message_time": "2026-07-15 09:30:00+00:00"}], 1),+ )++ batches = _run(+ "messages",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 11, 12, 0, 0, tzinfo=UTC),+ incremental_field="message_time",+ )++ assert len(calls) == 1+ assert calls[0]["url"] == MESSAGE_URL+ assert calls[0]["params"]["message_time__gt"] == "2026-07-11 12:00:00"+ assert calls[0]["params"]["message_time__lte"] == "2026-07-21 12:00:00"+ assert calls[0]["params"]["limit"] == PAGE_SIZE+ assert calls[0]["params"]["offset"] == 0++ rows = [row for batch in batches for row in batch]+ assert [r["message_uuid"] for r in rows] == ["m1"]+ # Timestamp strings are parsed so the incremental watermark compares datetimes.+ assert rows[0]["message_time"] == datetime(2026, 7, 15, 9, 30, 0, tzinfo=UTC)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_future_cursor_makes_no_requests(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, lambda url, params: _page([], 0))++ batches = _run(+ "messages",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 8, 1, tzinfo=UTC),+ incremental_field="message_time",+ )++ assert batches == []+ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pagination_saves_offset_then_window_checkpoint(self, MockSession: mock.MagicMock) -> None:+ def respond(url: str, params: dict[str, Any]) -> dict[str, Any]:+ offset = params["offset"]+ rows = [{"message_uuid": f"m{offset + i}"} for i in range(PAGE_SIZE if offset == 0 else 5)]+ return _page(rows, total_count=PAGE_SIZE + 5)++ calls = _wire(MockSession.return_value, respond)+ manager = _make_manager()++ batches = _run(+ "messages",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 11, 12, 0, 0, tzinfo=UTC),+ incremental_field="message_time",+ )++ assert [params["offset"] for params in (c["params"] for c in calls)] == [0, PAGE_SIZE]+ assert sum(len(b) for b in batches) == PAGE_SIZE + 5++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ # Mid-window: checkpoint the next page offset with the window bounds pinned.+ assert saved[0].offset == PAGE_SIZE+ assert saved[0].window_start == datetime(2026, 7, 11, 12, 0, 0, tzinfo=UTC).isoformat()+ assert saved[0].window_end == datetime(2026, 7, 21, 12, 0, 0, tzinfo=UTC).isoformat()+ # Window exhausted: checkpoint points at the next window's start with a fresh offset.+ assert saved[-1].window_start == datetime(2026, 7, 21, 12, 0, 0, tzinfo=UTC).isoformat()+ assert saved[-1].offset == 0++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_pins_saved_window_and_offset(self, MockSession: mock.MagicMock) -> None:+ calls = _wire(MockSession.return_value, lambda url, params: _page([{"message_uuid": "x"}], 1))++ window_start = datetime(2026, 6, 11, 12, 0, 0, tzinfo=UTC)+ window_end = datetime(2026, 7, 11, 12, 0, 0, tzinfo=UTC)+ manager = _make_manager(+ PlivoResumeConfig(window_start=window_start.isoformat(), window_end=window_end.isoformat(), offset=40)+ )++ _run("messages", manager)++ # First request resumes the saved window at the saved page offset...+ assert calls[0]["params"]["message_time__gt"] == "2026-06-11 12:00:00"+ assert calls[0]["params"]["message_time__lte"] == "2026-07-11 12:00:00"+ assert calls[0]["params"]["offset"] == 40+ # ...then the walk continues from the saved window's end to now, from offset 0.+ assert calls[1]["params"]["message_time__gt"] == "2026-07-11 12:00:00"+ assert calls[1]["params"]["message_time__lte"] == "2026-07-21 12:00:00"+ assert calls[1]["params"]["offset"] == 0+++@freeze_time(FROZEN_NOW)+class TestNonWindowedEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_recordings_incremental_filters_without_windowing(self, MockSession: mock.MagicMock) -> None:+ calls = _wire(MockSession.return_value, lambda url, params: _page([{"recording_id": "r1", "add_time": ""}], 1))++ batches = _run(+ "recordings",+ _make_manager(),+ should_use_incremental_field=True,+ # A cursor older than the 90-day MDR/CDR retention must NOT be clamped here —+ # recordings persist until deleted.+ db_incremental_field_last_value=datetime(2025, 1, 1, tzinfo=UTC),+ incremental_field="add_time",+ )++ assert len(calls) == 1+ assert calls[0]["url"] == "https://api.plivo.com/v1/Account/MA123/Recording/"+ assert calls[0]["params"]["add_time__gt"] == "2025-01-01 00:00:00"+ assert "add_time__lte" not in calls[0]["params"]+ # An empty timestamp string stays untouched instead of failing the row.+ assert batches[0][0]["add_time"] == ""++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_applications_full_refresh_has_no_filters_and_resumes_offset(self, MockSession: mock.MagicMock) -> None:+ calls = _wire(MockSession.return_value, lambda url, params: _page([{"app_id": "a1"}], 41))++ manager = _make_manager(PlivoResumeConfig(offset=40))+ _run("applications", manager)++ assert calls[0]["url"] == "https://api.plivo.com/v1/Account/MA123/Application/"+ assert calls[0]["params"] == {"limit": PAGE_SIZE, "offset": 40}+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(PLIVO_SESSION_PATCH)+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected: bool) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert validate_credentials("MA123", "token") is expected+ assert mock_session.return_value.get.call_args.args[0] == "https://api.plivo.com/v1/Account/MA123/"+++class TestPlivoSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, partition_keys",+ [+ ("messages", ["message_uuid"], ["message_time"]),+ ("calls", ["call_uuid"], ["end_time"]),+ ("recordings", ["recording_id"], ["add_time"]),+ ("applications", ["app_id"], None),+ ],+ )+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_keys) -> None:+ assert endpoint in ENDPOINTS+ response = plivo_source("MA123", "token", endpoint, resumable_source_manager=_make_manager())++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys+ assert response.partition_mode == ("datetime" if partition_keys else None)+ # Plivo lists return newest-first with no sort param, so the watermark must only be+ # persisted after a fully successful run.+ assert response.sort_mode == "desc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo_source.pynew file mode 100644index 000000000000..7c8d89bbb755--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo_source.py@@ -0,0 +1,146 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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.plivo import PlivoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.plivo import PlivoResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.plivo.source import PlivoSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPlivoSource:+ def setup_method(self):+ self.source = PlivoSource()+ self.team_id = 123+ self.config = PlivoSourceConfig(auth_id="MA123", auth_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PLIVO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Plivo"+ assert config.label == "Plivo"+ assert config.category == DataWarehouseSourceCategory.COMMUNICATION+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source must be visible — regressing to the scaffold's hidden state would+ # remove the connector from every user's wizard.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/plivo.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/plivo"++ def test_source_config_fields(self):+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == ["auth_id", "auth_token"]++ auth_token = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "auth_token")+ assert auth_token.type == SourceFieldInputConfigType.PASSWORD+ assert auth_token.secret is True+ assert auth_token.required is True++ def test_get_schemas_incremental_support(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in ("messages", "calls", "recordings"):+ assert schemas[name].supports_incremental is True, name+ assert schemas[name].incremental_fields == INCREMENTAL_FIELDS[name]+ # The application list has no server-side time filter — full refresh only.+ assert schemas["applications"].supports_incremental is False+ assert schemas["applications"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["calls"])] == ["calls"]+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert [t["name"] for t in documented] == list(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error, is_non_retryable",+ [+ ("401 Client Error: Unauthorized for url: https://api.plivo.com/v1/Account/MA123/Message/", True),+ ("403 Client Error: Forbidden for url: https://api.plivo.com/v1/Account/MA123/Call/", True),+ ("500 Server Error: Internal Server Error for url: https://api.plivo.com/v1/Account/MA123/Call/", False),+ ("429 Client Error: Too Many Requests for url: https://api.plivo.com/v1/Account/MA123/Message/", False),+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers", False),+ ],+ )+ def test_non_retryable_errors(self, observed_error, is_non_retryable):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors) is is_non_retryable++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Plivo Auth ID or Auth Token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.plivo.source.validate_plivo_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("MA123", "token")++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PlivoResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.plivo.source.plivo_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_plivo_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "messages"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-01 00:00:00"+ inputs.incremental_field = "message_time"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_plivo_source.call_args.kwargs+ assert kwargs["auth_id"] == "MA123"+ assert kwargs["auth_token"] == "token"+ assert kwargs["endpoint"] == "messages"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01 00:00:00"+ assert kwargs["incremental_field"] == "message_time"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.plivo.source.plivo_source")+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_plivo_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "messages"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-07-01 00:00:00"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ # A stale cursor must not narrow a full refresh to a partial window.+ assert mock_plivo_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_keyed_by_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)