: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): add Telnyx source (#73204)
Tom Owers647b6b77357f
diff --git a/frontend/public/services/telnyx.png b/frontend/public/services/telnyx.pngindex ea0e350d34ab..49da0091f99b 100644Binary files a/frontend/public/services/telnyx.png and b/frontend/public/services/telnyx.png differdiff --git a/posthog/test/base.py b/posthog/test/base.pyindex d33ccc3bc47a..108cc7040af2 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -1571,6 +1571,13 @@ class BaseTestMigrations(QueryMatchingTest):assert hasattr(self, "migrate_from") and hasattr(self, "migrate_to"), ("TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__))+ # The setUpClass guard only runs once per class, so a connection dropped after it (or a+ # pytest-rerunfailures in-process rerun, which reuses the same dead wrapper without calling+ # setUpClass again) still reaches the migration executor below with a closed connection and+ # fails "the connection is closed". Reset unusable connections here too, right before first use.+ for conn in connections.all():+ if conn.connection is not None and not conn.is_usable():+ conn.close()migrate_from = [(self.app, self.migrate_from)]migrate_to = [(self.app, self.migrate_to)]executor = MigrationExecutor(connection)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d8649456e781..5bb771a74a55 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -558,6 +558,7 @@ the row lists both.| teamcity | HTTP | requests | ✅ || teamtailor | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ |+| telnyx | HTTP | requests + `rest_source.RESTClient` | ✅ || tempo | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tenable_vulnerability_management | HTTP (async export flow) | requests | ✅ |@@ -1312,7 +1313,6 @@ doesn't conflict with concurrent PRs.- teamup_fitness- tebra- telli-- telnyx- tempo- ternary- terra_apidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/telnyx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/telnyx.pyindex 15fa51da903e..381487984bfe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/telnyx.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/telnyx.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TelnyxSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/canonical_descriptions.pynew file mode 100644index 000000000000..89ff6c57c564--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/canonical_descriptions.py@@ -0,0 +1,171 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DETAIL_RECORD_SEARCH_DOCS_URL = "https://developers.telnyx.com/docs/api/v2/detail-records/detail-record-search"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "MessagingDetailRecords": {+ "description": "Per-message detail records (MDRs) for SMS/MMS sent or received through Telnyx Messaging.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "uuid": "Unique identifier of the message.",+ "user_id": "Identifier of the Telnyx account who owns the message.",+ "completed_at": "Message completion time.",+ "created_at": "Message creation time.",+ "updated_at": "Message updated time.",+ "sent_at": "Time when the message was sent.",+ "carrier": "Country-specific carrier used to send or receive the message.",+ "carrier_fee": "Fee charged by certain carriers to deliver certain message types.",+ "cld": "The recipient of the message (the `to` parameter in the Messaging API).",+ "cli": "The sender of the message (the `from` parameter in the Messaging API).",+ "country_code": "Two-letter ISO 3166-1 alpha-2 country of the `cld` property.",+ "delivery_status": "Final webhook delivery status.",+ "direction": "Logical direction of the message from the Telnyx customer's perspective.",+ "fteu": "Whether this is a Free-To-End-User (FTEU) short code message.",+ "mcc": "Mobile country code, for certain products such as Global Outbound.",+ "mnc": "Mobile network code, for certain products such as Global Outbound.",+ "message_type": "The Messaging service used to send the message (e.g. SMS, MMS).",+ "on_net": "Whether both sender and recipient numbers are Telnyx-managed.",+ "profile_id": "Unique identifier of the Messaging Profile used to send or receive the message.",+ "profile_name": "Name of the Messaging Profile used to send or receive the message.",+ "status": "Final status of the message after the delivery attempt.",+ "tags": "Comma-separated tags assigned to the Telnyx number associated with the message.",+ "rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "cost": "Amount, in the account currency, for the Telnyx billing cost.",+ "parts": "Number of message parts the message was broken into.",+ "record_type": "Identifies the record schema.",+ },+ },+ "VerifyDetailRecords": {+ "description": "Detail records for Telnyx Verify (2FA) verification attempts.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Unique ID of the verification.",+ "verify_profile_id": "Identifier of the Verify profile used for this verification.",+ "delivery_status": "Delivery status of the verification message.",+ "verification_status": "Outcome status of the verification attempt.",+ "destination_phone_number": "E.164 formatted destination phone number.",+ "verify_channel_type": "Channel used for the verification (e.g. SMS, call, flash call).",+ "verify_channel_id": "Identifier of the specific channel resource used.",+ "created_at": "Verification creation time.",+ "updated_at": "Verification updated time.",+ "rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "verify_usage_fee": "Currency amount for the Verify usage fee.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "record_type": "Identifies the record schema.",+ },+ },+ "WirelessUsageDetailRecords": {+ "description": "SIM card data usage events for Telnyx Wireless.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Unique identifier for this SIM card usage event.",+ "created_at": "Event creation time.",+ "closed_at": "Event close time.",+ "ip_address": "IP address that generated the event.",+ "downlink_data": "Number of megabytes downloaded.",+ "uplink_data": "Number of megabytes uploaded.",+ "imsi": "International Mobile Subscriber Identity.",+ "mcc": "Mobile country code.",+ "mnc": "Mobile network code.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "data_unit": "Unit of wireless link consumption.",+ "data_rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "data_cost": "Data cost for this usage event.",+ "sim_group_name": "SIM group name for the SIM card.",+ "sim_group_id": "Unique identifier for the SIM group.",+ "sim_card_id": "Unique identifier for the SIM card.",+ "sim_card_tags": "User-provided tags on the SIM card.",+ "phone_number": "Telephone number associated with the SIM card.",+ "record_type": "Identifies the record schema.",+ },+ },+ "MediaStorageDetailRecords": {+ "description": "Events for Telnyx Media Storage API actions (uploads, downloads, links).",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Unique identifier for the Media Storage event.",+ "created_at": "Event creation time.",+ "asset_id": "Identifier of the stored asset.",+ "user_id": "Identifier of the Telnyx user who owns the asset.",+ "org_id": "Identifier of the organization that owns the asset.",+ "action_type": "Type of action performed against the Media Storage API.",+ "link_channel_type": "Channel type of the sharing link, if any.",+ "link_channel_id": "Identifier of the sharing link channel, if any.",+ "status": "Status of the request.",+ "webhook_id": "Identifier of the webhook associated with this event, if any.",+ "rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "cost": "Currency amount for the Telnyx billing cost.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "record_type": "Identifies the record schema.",+ },+ },+ "ConferenceDetailRecords": {+ "description": "Detail records for Telnyx Call Control conferences.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Conference id.",+ "name": "Conference name.",+ "user_id": "Identifier of the Telnyx user who owns the conference.",+ "started_at": "Conference start time.",+ "ended_at": "Conference end time.",+ "expires_at": "Conference expiry time.",+ "region": "Region where the conference is hosted.",+ "call_leg_id": "Telnyx UUID that identifies the conference call leg.",+ "call_session_id": "Telnyx UUID that identifies the conference call session.",+ "connection_id": "Identifier of the Call Control connection used.",+ "call_sec": "Duration of the conference call in seconds.",+ "participant_count": "Number of participants that joined the conference call.",+ "participant_call_sec": "Sum of the conference call duration for all participants, in seconds.",+ "is_telnyx_billable": "Whether Telnyx billing charges might be applicable.",+ "record_type": "Identifies the record schema.",+ },+ },+ "ConferenceParticipantDetailRecords": {+ "description": "Detail records for individual participants of a Telnyx Call Control conference.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Participant id.",+ "user_id": "Identifier of the Telnyx user who owns the conference.",+ "conference_id": "Identifier of the conference this participant joined.",+ "joined_at": "Participant join time.",+ "left_at": "Participant leave time.",+ "destination_number": "Number called by the participant to join the conference.",+ "originating_number": "Participant's origin number used in the conference call.",+ "call_leg_id": "Telnyx UUID that identifies the conference call leg.",+ "call_session_id": "Telnyx UUID that identifies the conference call session.",+ "call_sec": "Duration of the conference call in seconds.",+ "billed_sec": "Duration of the conference call for billing purposes.",+ "is_telnyx_billable": "Whether Telnyx billing charges might be applicable.",+ "rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "rate_measured_in": "Billing unit used to calculate the Telnyx billing cost.",+ "cost": "Currency amount for the Telnyx billing cost.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "record_type": "Identifies the record schema.",+ },+ },+ "AmdDetailRecords": {+ "description": "Detail records for Telnyx Answering Machine Detection (AMD) feature invocations.",+ "docs_url": DETAIL_RECORD_SEARCH_DOCS_URL,+ "columns": {+ "id": "Feature invocation id.",+ "invoked_at": "Feature invocation time.",+ "feature": "Feature name.",+ "tags": "User-provided tags.",+ "billing_group_id": "Identifier of the billing group.",+ "billing_group_name": "Name of the billing group specified in `billing_group_id`.",+ "connection_id": "Identifier of the Call Control connection used.",+ "connection_name": "Name of the Call Control connection used.",+ "call_leg_id": "Telnyx UUID that identifies the related call leg.",+ "call_session_id": "Telnyx UUID that identifies the related call session.",+ "is_telnyx_billable": "Whether Telnyx billing charges might be applicable.",+ "rate": "Currency amount per billing unit used to calculate the Telnyx billing cost.",+ "rate_measured_in": "Billing unit used to calculate the Telnyx billing cost.",+ "cost": "Currency amount for the Telnyx billing cost.",+ "currency": "Telnyx account currency used to describe monetary values.",+ "record_type": "Identifies the record schema.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/settings.pynew file mode 100644index 000000000000..43df357d4f2b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/settings.py@@ -0,0 +1,94 @@+import dataclasses++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++[email protected](frozen=True)+class TelnyxEndpoint:+ """Declarative metadata for one Telnyx Detail Record Search `record_type`.++ Every record type shares the same physical endpoint (`GET /v2/detail_records`) and is+ distinguished only by `filter[record_type]`, so each entry here maps to a distinct table.+ """++ name: str+ table_name: str+ record_type: str+ primary_key: list[str]+ # A stable timestamp field used for datetime partitioning (and, when set, as the+ # `filter[<field>][gte]` incremental cursor). Never `updated_at`-like fields.+ partition_key: str+ # Set only when the record's own response schema documents this field AND Telnyx's docs+ # demonstrate a `filter[<field>][gte]`/`[lt]` server-side filter for it. Record types+ # without a documented `created_at`-equivalent stay full refresh rather than guessing that+ # the generic attribute filter also windows time reliably for them.+ incremental_field: str | None = None+++TELNYX_ENDPOINTS: dict[str, TelnyxEndpoint] = {+ "MessagingDetailRecords": TelnyxEndpoint(+ name="MessagingDetailRecords",+ table_name="messaging_detail_records",+ record_type="messaging",+ primary_key=["uuid"],+ partition_key="created_at",+ incremental_field="created_at",+ ),+ "VerifyDetailRecords": TelnyxEndpoint(+ name="VerifyDetailRecords",+ table_name="verify_detail_records",+ record_type="verify",+ primary_key=["id"],+ partition_key="created_at",+ incremental_field="created_at",+ ),+ "WirelessUsageDetailRecords": TelnyxEndpoint(+ name="WirelessUsageDetailRecords",+ table_name="wireless_usage_detail_records",+ record_type="wireless",+ primary_key=["id"],+ partition_key="created_at",+ incremental_field="created_at",+ ),+ "MediaStorageDetailRecords": TelnyxEndpoint(+ name="MediaStorageDetailRecords",+ table_name="media_storage_detail_records",+ record_type="media_storage",+ primary_key=["id"],+ partition_key="created_at",+ incremental_field="created_at",+ ),+ # Conference/participant/AMD records have no documented `created_at`-equivalent filter, only+ # their own start/join/invocation timestamp — Telnyx's docs only demonstrate the+ # `filter[created_at]` example against messaging records, so these ship full refresh.+ "ConferenceDetailRecords": TelnyxEndpoint(+ name="ConferenceDetailRecords",+ table_name="conference_detail_records",+ record_type="conference",+ primary_key=["id"],+ partition_key="started_at",+ ),+ "ConferenceParticipantDetailRecords": TelnyxEndpoint(+ name="ConferenceParticipantDetailRecords",+ table_name="conference_participant_detail_records",+ record_type="conference-participant",+ primary_key=["id"],+ partition_key="joined_at",+ ),+ "AmdDetailRecords": TelnyxEndpoint(+ name="AmdDetailRecords",+ table_name="amd_detail_records",+ record_type="amd",+ primary_key=["id"],+ partition_key="invoked_at",+ ),+}++ENDPOINTS: tuple[str, ...] = tuple(TELNYX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ endpoint.name: [incremental_field(endpoint.incremental_field)]+ for endpoint in TELNYX_ENDPOINTS.values()+ if endpoint.incremental_field+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/source.pyindex 5d76ebc2a043..aa79459b79ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/source.py@@ -1,30 +1,146 @@-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.telnyx import TelnyxSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TELNYX_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx import (+ TelnyxResumeConfig,+ telnyx_source,+ validate_credentials as validate_telnyx_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TelnyxSource(SimpleSource[TelnyxSourceConfig]):+class TelnyxSource(ResumableSource[TelnyxSourceConfig, TelnyxResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://developers.telnyx.com/docs/api/v2/detail-records/detail-record-search"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TELNYX+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Telnyx API key is invalid or has expired. Generate a new key from the Telnyx portal and reconnect.",+ "403 Client Error: Forbidden": "Your Telnyx API key doesn't have permission for this request. Check the key's scopes in the Telnyx portal and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TelnyxSourceConfig,+ 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: TelnyxSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_telnyx_credentials(config.api_key):+ return True, None++ return False, "Invalid Telnyx API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TelnyxResumeConfig]:+ return ResumableSourceManager[TelnyxResumeConfig](inputs, TelnyxResumeConfig)++ def source_for_pipeline(+ self,+ config: TelnyxSourceConfig,+ resumable_source_manager: ResumableSourceManager[TelnyxResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint = TELNYX_ENDPOINTS[inputs.schema_name]+ resource = telnyx_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+ if inputs.should_use_incremental_field+ else None,+ )+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=endpoint.primary_key,+ column_hints=resource.column_hints,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint.partition_key],+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TELNYX,category=DataWarehouseSourceCategory.COMMUNICATION,label="Telnyx",+ keywords=["cpaas", "sms", "voice"],+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Enter your Telnyx API v2 key to pull messaging, voice, verify, wireless, and media "+ "storage detail records into the PostHog Data warehouse. Generate a key from "+ "**API Keys** in the Telnyx portal."+ ),iconPath="/static/services/telnyx.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/telnyx",+ 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/telnyx/telnyx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/telnyx.pynew file mode 100644index 000000000000..1754715fc104--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/telnyx.py@@ -0,0 +1,143 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++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 (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.settings import TELNYX_ENDPOINTS++TELNYX_BASE_URL = "https://api.telnyx.com"+# Detail Record Search caps `page[size]` at 50 (general list endpoints allow up to 250).+PAGE_SIZE = 50+++class TelnyxResumeConfig:+ next_page: int+++def _format_created_at(value: Any) -> str:+ """Format a datetime/date as an RFC 3339 UTC timestamp for `filter[<field>][gte]`.++ Telnyx's docs only show a bare date (`2021-06-22`) in examples; a full timestamp is a+ superset of that format and lets incremental syncs re-run within the same day.+ """+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ endpoint = TELNYX_ENDPOINTS[name]+ params: dict[str, Any] = {+ "filter[record_type]": endpoint.record_type,+ "page[size]": PAGE_SIZE,+ }++ use_incremental = should_use_incremental_field and endpoint.incremental_field is not None+ if use_incremental and endpoint.incremental_field is not None:+ params[f"filter[{endpoint.incremental_field}][gte]"] = {+ "type": "incremental",+ "cursor_path": endpoint.incremental_field,+ "initial_value": "1970-01-01T00:00:00Z",+ "convert": _format_created_at,+ }+ # Explicit ascending sort on the same field that's being windowed, so the pipeline's+ # incremental watermark advances in the order rows actually arrive.+ params["sort"] = endpoint.incremental_field+ else:+ # Full refresh: an explicit stable sort still prevents page-boundary skips/duplicates+ # if the API's implicit default ordering shifts as rows are inserted mid-sync.+ params["sort"] = endpoint.partition_key++ return {+ "name": endpoint.name,+ "table_name": endpoint.table_name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if use_incremental+ else "replace",+ "endpoint": {+ "data_selector": "data",+ "data_selector_required": True,+ "path": "/v2/detail_records",+ "params": params,+ },+ "table_format": "delta",+ }+++def telnyx_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TelnyxResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+ should_use_incremental_field: bool = False,+):+ config: RESTAPIConfig = {+ "client": {+ "base_url": TELNYX_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "paginator": PageNumberPaginator(base_page=1, page_param="page[number]", total_path="meta.total_pages"),+ # Detail records carry customer-defined tags, profile names, call metadata, and billing+ # details the name-based sample scrubbers don't recognise, so keep response bodies out of+ # shared HTTP sample storage. Requests are still metered and logged (with the key redacted).+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; Redis TTL handles cleanup once+ # the sync completes. Saving AFTER each yielded batch means a crash re-yields the last+ # page rather than skipping it (the merge dedupes on primary key).+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(TelnyxResumeConfig(next_page=int(state["page"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(api_key: str) -> bool:+ probe_params: dict[str, str | int] = {"filter[record_type]": "messaging", "page[size]": 1}+ # capture=False: the probe returns a real detail record (customer content) the name-based+ # scrubbers can't reliably redact, so keep it out of shared HTTP sample storage.+ res = make_tracked_session(redact_values=(api_key,), capture=False).get(+ f"{TELNYX_BASE_URL}/v2/detail_records",+ params=probe_params,+ headers={"Authorization": f"Bearer {api_key}"},+ )+ return res.status_code == 200diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx.pynew file mode 100644index 000000000000..d9aacf651112--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx.py@@ -0,0 +1,221 @@+import json+from collections.abc import Iterable+from datetime import date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.settings import ENDPOINTS, TELNYX_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx import (+ PAGE_SIZE,+ TelnyxResumeConfig,+ _format_created_at,+ get_resource,+ telnyx_source,+ validate_credentials,+)++INCREMENTAL_ENDPOINTS = sorted(name for name, endpoint in TELNYX_ENDPOINTS.items() if endpoint.incremental_field)+FULL_REFRESH_ENDPOINTS = sorted(set(ENDPOINTS) - set(INCREMENTAL_ENDPOINTS))+++class TestFormatCreatedAt:+ def test_naive_datetime_treated_as_utc(self) -> None:+ assert _format_created_at(datetime(2024, 1, 2, 3, 4, 5)) == "2024-01-02T03:04:05Z"++ def test_aware_datetime_converted_to_utc(self) -> None:+ from datetime import timedelta, timezone++ tz = timezone(timedelta(hours=5))+ assert _format_created_at(datetime(2024, 1, 2, 8, 4, 5, tzinfo=tz)) == "2024-01-02T03:04:05Z"++ def test_date_becomes_midnight_utc(self) -> None:+ assert _format_created_at(date(2024, 1, 2)) == "2024-01-02T00:00:00Z"++ def test_string_passthrough(self) -> None:+ assert _format_created_at("1970-01-01T00:00:00Z") == "1970-01-01T00:00:00Z"+++class TestGetResource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_resource_shape(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ config = TELNYX_ENDPOINTS[endpoint]++ assert resource["name"] == endpoint+ assert resource["table_name"] == config.table_name+ assert resource["table_format"] == "delta"+ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ assert endpoint_config["path"] == "/v2/detail_records"+ assert endpoint_config["data_selector"] == "data"+ assert endpoint_config["data_selector_required"] is True++ params = cast(dict[str, Any], endpoint_config["params"])+ assert params["filter[record_type]"] == config.record_type+ assert params["page[size]"] == PAGE_SIZE++ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)+ def test_full_refresh_endpoints_always_replace(self, endpoint: str) -> None:+ for should_use_incremental_field in (False, True):+ resource = get_resource(endpoint, should_use_incremental_field=should_use_incremental_field)+ assert resource["write_disposition"] == "replace"+ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ params = cast(dict[str, Any], endpoint_config["params"])+ assert params["sort"] == TELNYX_ENDPOINTS[endpoint].partition_key+ assert not any(key.startswith("filter[") and key != "filter[record_type]" for key in params)++ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)+ def test_incremental_endpoints_full_refresh_when_disabled(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ assert resource["write_disposition"] == "replace"+ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ params = cast(dict[str, Any], endpoint_config["params"])+ assert params["sort"] == TELNYX_ENDPOINTS[endpoint].partition_key+ incremental_field = TELNYX_ENDPOINTS[endpoint].incremental_field+ assert f"filter[{incremental_field}][gte]" not in params++ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)+ def test_incremental_endpoints_merge_when_enabled(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=True)+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ incremental_field = TELNYX_ENDPOINTS[endpoint].incremental_field+ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ params = cast(dict[str, Any], endpoint_config["params"])+ assert params["sort"] == incremental_field++ filter_config = params[f"filter[{incremental_field}][gte]"]+ assert filter_config["type"] == "incremental"+ assert filter_config["cursor_path"] == incremental_field+ assert filter_config["convert"] is _format_created_at+++def _make_http_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestTelnyxSourceResumeBehavior:+ """End-to-end pagination/resume behaviour of ``telnyx_source`` via ``rest_api_resource``."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False+ ) -> tuple[MagicMock, list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = telnyx_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ should_use_incremental_field=should_use_incremental_field,+ )+ list(cast(Iterable[Any], resource))+ return mock_session, sent_params++ def test_fresh_run_walks_pages_until_total_pages(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"data": [{"uuid": "1"}], "meta": {"total_pages": 3}}),+ _make_http_response({"data": [{"uuid": "2"}], "meta": {"total_pages": 3}}),+ _make_http_response({"data": [{"uuid": "3"}], "meta": {"total_pages": 3}}),+ ]+ _, sent_params = self._drive("MessagingDetailRecords", manager, responses)++ assert [p.get("page[number]") for p in sent_params] == [1, 2, 3]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [TelnyxResumeConfig(next_page=2), TelnyxResumeConfig(next_page=3)]++ def test_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"uuid": "1"}], "meta": {"total_pages": 1}})]+ self._drive("MessagingDetailRecords", manager, responses)++ manager.save_state.assert_not_called()++ def test_resume_seeds_paginator_with_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = TelnyxResumeConfig(next_page=2)++ responses = [+ _make_http_response({"data": [{"uuid": "2"}], "meta": {"total_pages": 2}}),+ ]+ _, sent_params = self._drive("MessagingDetailRecords", manager, responses)++ assert [p.get("page[number]") for p in sent_params] == [2]+ manager.load_state.assert_called_once()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [], "meta": {"total_pages": 1}})]+ self._drive("MessagingDetailRecords", manager, responses)++ manager.load_state.assert_not_called()++ def test_incremental_run_filters_by_created_at(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"data": [{"uuid": "1"}], "meta": {"total_pages": 1}})]+ _, sent_params = self._drive("VerifyDetailRecords", manager, responses, should_use_incremental_field=True)++ assert sent_params[0]["filter[created_at][gte]"] == "1970-01-01T00:00:00Z"+ assert sent_params[0]["sort"] == "created_at"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx.make_tracked_session")+ def test_status_maps_to_validity(self, mock_session_factory: MagicMock, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ mock_session_factory.return_value.get.return_value = response++ assert validate_credentials("api-key") is expected++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx.make_tracked_session")+ def test_probes_detail_records_with_bearer_auth(self, mock_session_factory: MagicMock) -> None:+ mock_get = mock_session_factory.return_value.get+ mock_get.return_value = MagicMock(status_code=200)++ validate_credentials("api-key")++ mock_session_factory.assert_called_once_with(redact_values=("api-key",), capture=False)+ called_url = mock_get.call_args.args[0]+ called_kwargs = mock_get.call_args.kwargs+ assert called_url == "https://api.telnyx.com/v2/detail_records"+ assert called_kwargs["headers"] == {"Authorization": "Bearer api-key"}+ assert called_kwargs["params"] == {"filter[record_type]": "messaging", "page[size]": 1}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx_source.pynew file mode 100644index 000000000000..32eff5603875--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/telnyx/tests/test_telnyx_source.py@@ -0,0 +1,176 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.telnyx import TelnyxSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.settings import ENDPOINTS, TELNYX_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.source import TelnyxSource+from products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.telnyx import TelnyxResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {name for name, endpoint in TELNYX_ENDPOINTS.items() if endpoint.incremental_field}+FULL_REFRESH_ENDPOINTS = set(ENDPOINTS) - INCREMENTAL_ENDPOINTS+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "MessagingDetailRecords",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestTelnyxSource:+ def setup_method(self) -> None:+ self.source = TelnyxSource()+ self.team_id = 123+ self.config = TelnyxSourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TELNYX++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs table list can render.+ assert self.source.lists_tables_without_credentials is True++ def test_api_version_metadata(self) -> None:+ assert self.source.supported_versions == ("v2",)+ assert self.source.default_version == "v2"+ assert self.source.api_docs_url.startswith("https://")++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Telnyx"+ assert config.label == "Telnyx"+ assert config.category == DataWarehouseSourceCategory.COMMUNICATION+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/telnyx"+ assert config.iconPath == "/static/services/telnyx.png"+ assert not config.unreleasedSource++ (api_key_field,) = config.fields+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ def test_get_schemas_returns_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", sorted(INCREMENTAL_ENDPOINTS))+ def test_get_schemas_incremental_endpoints(self, endpoint: str) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert [f["field"] for f in schema.incremental_fields] == [TELNYX_ENDPOINTS[endpoint].incremental_field]++ @pytest.mark.parametrize("endpoint", sorted(FULL_REFRESH_ENDPOINTS))+ def test_get_schemas_full_refresh_endpoints(self, endpoint: str) -> None:+ # No documented server-side timestamp filter for these record types, so they must not+ # falsely advertise incremental support.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["VerifyDetailRecords"])+ assert [s.name for s in schemas] == ["VerifyDetailRecords"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # Every advertised endpoint should have a curated description so the docs and the AI+ # agent get authoritative metadata instead of paying for LLM enrichment.+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ ("creds_valid", "expected_valid", "expected_message"),+ [+ (True, True, None),+ (False, False, "Invalid Telnyx API key"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.source.validate_telnyx_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ creds_valid: bool,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = creds_valid++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TelnyxResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.source.telnyx_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="VerifyDetailRecords", team_id=99, job_id="job-xyz")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-key",+ endpoint="VerifyDetailRecords",+ team_id=99,+ job_id="job-xyz",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert response.primary_keys == TELNYX_ENDPOINTS["VerifyDetailRecords"].primary_key++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_partitions_on_stable_field(self, endpoint: str) -> None:+ # Every partition key is a creation/start/invocation timestamp, never an+ # `updated_at`-like field that would rewrite partitions on every sync.+ with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.telnyx.source.telnyx_source"):+ response = self.source.source_for_pipeline(+ self.config, mock.MagicMock(spec=ResumableSourceManager), _make_inputs(schema_name=endpoint)+ )++ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == [TELNYX_ENDPOINTS[endpoint].partition_key]