: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 tyntec_sms import source (#72638)
Tom Owersa8af12a204d9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ade9f0659c92..75f61172d0b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -541,6 +541,7 @@ the row lists both.| trigger_dev | HTTP | requests | ✅ || twelve_labs | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ |+| tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ || unleash | HTTP | requests | ✅ |@@ -975,7 +976,6 @@ doesn't conflict with concurrent PRs.- twenty- twitter_ads-- tyntec_sms- uppromote- uptick- us_censusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tyntecsms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tyntecsms.pyindex 9cae1a405eff..61584dcedb02 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tyntecsms.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tyntecsms.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TyntecSMSSourceConfig(config.Config):- pass+ api_key: str+ request_ids: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/canonical_descriptions.pynew file mode 100644index 000000000000..dca4910d881f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/canonical_descriptions.py@@ -0,0 +1,65 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://api.tyntec.com/reference/sms/current.html"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "MessageStatus": {+ "description": "Delivery status of a sent SMS message, looked up by its request ID. tyntec retains statuses for 3 months after a final delivery state is reached.",+ "docs_url": _DOCS_URL,+ "columns": {+ "requestId": "The unique identifier provided for each messaging request.",+ "from": "The phone number of the sending party in international format, if available.",+ "to": "The number provided by tyntec that received the respective message, in international format.",+ "status": "The message status, e.g. DELIVERED.",+ "submitDate": "The date when the message was sent out by tyntec for delivery.",+ "doneDate": "The timestamp when the message was successfully delivered.",+ "errorCode": "The GSM error code for an unsuccessful attempt.",+ "errorReason": "The reason for an unsuccessful attempt.",+ "mccmnc": "Representative IMSI prefix of the target network.",+ "parts": "Per-part delivery details (delivery state, part ID, price, status text) for concatenated messages.",+ "overallPrice": "The overall sum of prices for all parts of this message.",+ "priceEffective": "The date when the price became active.",+ "reference": "Custom reference that marks the delivery report.",+ "size": "The number of concatenated SMS parts.",+ "href": "The URL of the accepted message.",+ "ttid": "The tyntec operator's ID.",+ },+ },+ "Contacts": {+ "description": "A contact registered with tyntec's BYON (bring-your-own-number) contact service.",+ "docs_url": _DOCS_URL,+ "columns": {+ "companyAddress": "Company's postal address.",+ "companyName": "Company's name.",+ "contactEmail": "E-mail address.",+ "contactName": "Requestor's name.",+ "contactPhone": "Requestor's phone number.",+ "contactTitle": "Requestor's title.",+ "friendlyName": "Friendly name of the contact.",+ },+ },+ "PhoneNumbers": {+ "description": "A phone number registered in tyntec's BYON phone book (capped at 3000 entries per account).",+ "docs_url": _DOCS_URL,+ "columns": {+ "accountId": "The account that created this entry.",+ "contactId": "Contact ID of this entry.",+ "friendlyName": "Friendly name of this entry.",+ "requestId": "Request ID of this entry.",+ "status": "Status of this entry.",+ },+ },+ "PhoneRegistrations": {+ "description": "A phone number provisioning request in tyntec's BYON number service.",+ "docs_url": _DOCS_URL,+ "columns": {+ "accountId": "The account that created this entry.",+ "contactId": "Contact ID of this entry.",+ "friendlyName": "Friendly name of this entry.",+ "requestId": "Request ID of this entry.",+ "status": "Status of this entry.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/settings.pynew file mode 100644index 000000000000..45e190b6756d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/settings.py@@ -0,0 +1,68 @@+from products.warehouse_sources.backend.types import IncrementalField++MESSAGE_STATUS = "MessageStatus"+CONTACTS = "Contacts"+PHONE_NUMBERS = "PhoneNumbers"+PHONE_REGISTRATIONS = "PhoneRegistrations"++ENDPOINTS = (+ MESSAGE_STATUS,+ CONTACTS,+ PHONE_NUMBERS,+ PHONE_REGISTRATIONS,+)++# tyntec's SMS API exposes no server-side timestamp filter on any endpoint, so every table+# is full-refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}++# Path + the response-body key wrapping the row list for each BYON list endpoint. Responses+# are single wrapper objects, e.g. {"contacts": [...], "size": 2}.+LIST_ENDPOINTS: dict[str, tuple[str, str]] = {+ CONTACTS: ("/byon/contacts/v1", "contacts"),+ PHONE_NUMBERS: ("/byon/phonebook/v1/numbers", "provisioningRequests"),+ PHONE_REGISTRATIONS: ("/byon/provisioning/v1", "provisioningRequests"),+}++# Message statuses are fetched one request id at a time — tyntec has no bulk message-list+# endpoint (see https://api.tyntec.com/reference/sms/current.html).+MESSAGE_STATUS_PATH = "/messaging/v1/messages/{request_id}"++PRIMARY_KEYS: dict[str, list[str]] = {+ MESSAGE_STATUS: ["requestId"],+ # The OpenAPI schemas omit the id fields on the BYON list entities, but the read/edit/delete+ # endpoints key on contactId / phoneNumber, so live rows carry them. These tables are+ # full-refresh only (replace), so the keys never drive a Delta merge.+ CONTACTS: ["contactId"],+ PHONE_NUMBERS: ["phoneNumber"],+ PHONE_REGISTRATIONS: ["requestId"],+}++# Documented hard cap on the phonebook listing. We request the whole cap in one page rather+# than paginating: the API documents `page`/`size` params only on this endpoint, without+# defining the base page or whether `page` is honored, so paginating risks re-fetching the+# same rows forever.+PHONEBOOK_MAX_SIZE = 3000++# Each configured request id costs one serial HTTP request per sync, so cap the list to keep+# a single source from occupying an import worker with unbounded work.+MAX_REQUEST_IDS = 1000++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ MESSAGE_STATUS: "Delivery status of sent SMS messages, fetched per request ID configured on the source.",+ CONTACTS: "Contacts registered with tyntec's BYON (bring-your-own-number) contact service.",+ PHONE_NUMBERS: "Phone numbers registered in tyntec's BYON phone book.",+ PHONE_REGISTRATIONS: "Phone number provisioning requests in tyntec's BYON number service.",+}++# The BYON endpoints are in tyntec's official SMS API spec, but the live gateway answered+# 404 ("no Route matched") to authenticated and unauthenticated probes at implementation+# time — they appear to require the BYON service on the account (or have been sunset+# upstream). Default them to unselected so a fresh source doesn't fail its first sync on+# tables the account can't reach.+SHOULD_SYNC_DEFAULT: dict[str, bool] = {+ MESSAGE_STATUS: True,+ CONTACTS: False,+ PHONE_NUMBERS: False,+ PHONE_REGISTRATIONS: False,+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/source.pyindex 5c5b609ff83c..76dac043126e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/source.py@@ -1,32 +1,132 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tyntecsms import (TyntecSMSSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.tyntec_sms import (+ tyntec_sms_source,+ validate_credentials as validate_tyntec_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass TyntecSMSSource(SimpleSource[TyntecSMSSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://api.tyntec.com/reference/sms/current.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TYNTECSMS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.tyntec.com": "tyntec authentication failed. Please check your API key.",+ "403 Client Error: Forbidden for url: https://api.tyntec.com": "tyntec rejected your API key. Please check the key and its permissions in the tyntec Business Center.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TyntecSMSSourceConfig,+ 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,+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )++ def validate_credentials(+ self, config: TyntecSMSSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not config.api_key:+ return False, "tyntec API key is required"++ if validate_tyntec_credentials(config.api_key):+ return True, None++ return False, "Invalid tyntec API key"++ def source_for_pipeline(self, config: TyntecSMSSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return tyntec_sms_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ request_ids=config.request_ids,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TYNTEC_SMS,category=DataWarehouseSourceCategory.COMMUNICATION,label="Tyntec SMS",+ caption="Import SMS delivery statuses and BYON phone book data from tyntec. Get your API key from the [tyntec Business Center](https://my.tyntec.com/).",+ keywords=["sms", "cpaas"],+ docsUrl="https://posthog.com/docs/cdp/sources/tyntec-sms",iconPath="/static/services/tyntec_sms.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="request_ids",+ label="SMS request IDs",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="e74db8d4-77ad-4671-8feb-9bc76b0df188, 57d2a198-cbdf-478c-8da0-c164b4ce5ac5",+ secret=False,+ caption="Request IDs of sent SMS messages to import statuses for, separated by commas or new lines. tyntec has no bulk message list, so the MessageStatus table only contains the messages listed here.",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms.pynew file mode 100644index 000000000000..5366221528cd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms.py@@ -0,0 +1,225 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import patch++from requests import HTTPError, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.settings import (+ CONTACTS,+ MAX_REQUEST_IDS,+ MESSAGE_STATUS,+ PHONE_NUMBERS,+ PHONE_REGISTRATIONS,+ PHONEBOOK_MAX_SIZE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.tyntec_sms import (+ parse_request_ids,+ tyntec_sms_source,+ validate_credentials,+)+++def _make_http_response(body: dict[str, Any], status_code: int = 200, reason: str = "OK") -> Response:+ resp = Response()+ resp.status_code = status_code+ resp.reason = reason+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ resp.url = "https://api.tyntec.com/"+ return resp+++def _drive(endpoint: str, responses: list[Response], request_ids: str | None = None) -> tuple[list[Any], list[dict]]:+ """Run ``tyntec_sms_source`` against a mocked HTTP session.++ Returns ``(rows, sent_requests)`` where each sent request is captured as+ ``{"url": ..., "params": ...}`` at send time (the Request object is mutated+ between pages, so call_args_list can't be trusted).+ """+ sent: list[dict] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **kwargs: Any) -> Response:+ sent.append(+ {+ "url": request.url,+ "params": dict(request.params or {}),+ "allow_redirects": kwargs.get("allow_redirects"),+ }+ )+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.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++ source_response = tyntec_sms_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ request_ids=request_ids,+ )+ rows: list[Any] = []+ for page in cast(Iterable[Any], source_response.items()):+ if isinstance(page, list):+ rows.extend(page)+ else:+ rows.append(page)+ return rows, sent+++class TestParseRequestIds:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ (None, []),+ ("", []),+ (" \n ", []),+ ("id-1", ["id-1"]),+ ("id-1,id-2", ["id-1", "id-2"]),+ ("id-1, id-2\nid-3", ["id-1", "id-2", "id-3"]),+ ("id-1,,id-1 ,\n,id-2", ["id-1", "id-2"]),+ ],+ )+ def test_parses_and_dedupes(self, raw: str | None, expected: list[str]) -> None:+ assert parse_request_ids(raw) == expected++ def test_caps_list_to_bound_worker_time(self) -> None:+ # Each id is one serial HTTP request per sync; an unbounded list would let a single+ # source occupy an import worker indefinitely.+ raw = ",".join(f"id-{i}" for i in range(MAX_REQUEST_IDS + 5))++ parsed = parse_request_ids(raw)++ assert len(parsed) == MAX_REQUEST_IDS+ assert parsed[0] == "id-0"+ assert parsed[-1] == f"id-{MAX_REQUEST_IDS - 1}"+++class TestMessageStatus:+ def test_fetches_one_status_per_request_id(self) -> None:+ responses = [+ _make_http_response({"requestId": "id-1", "status": "DELIVERED"}),+ _make_http_response({"requestId": "id-2", "status": "REJECTED"}),+ ]+ rows, sent = _drive(MESSAGE_STATUS, responses, request_ids="id-1, id-2")++ assert [row["requestId"] for row in rows] == ["id-1", "id-2"]+ assert [req["url"] for req in sent] == [+ "https://api.tyntec.com/messaging/v1/messages/id-1",+ "https://api.tyntec.com/messaging/v1/messages/id-2",+ ]+ # Redirects must not be followed: the apikey header would replay to the redirect target.+ assert all(req["allow_redirects"] is False for req in sent)++ def test_request_id_is_url_quoted(self) -> None:+ responses = [_make_http_response({"requestId": "a/b"})]+ _, sent = _drive(MESSAGE_STATUS, responses, request_ids="a/b")++ assert sent[0]["url"] == "https://api.tyntec.com/messaging/v1/messages/a%2Fb"++ def test_expired_request_id_404_is_skipped(self) -> None:+ # tyntec drops statuses ~3 months after delivery; an expired id must not fail the sync.+ responses = [+ _make_http_response({"title": "Not Found"}, status_code=404, reason="Not Found"),+ _make_http_response({"requestId": "id-2", "status": "DELIVERED"}),+ ]+ rows, sent = _drive(MESSAGE_STATUS, responses, request_ids="id-1, id-2")++ assert [row["requestId"] for row in rows] == ["id-2"]+ assert len(sent) == 2++ def test_auth_error_is_not_swallowed_by_404_skip(self) -> None:+ responses = [+ _make_http_response({"message": "No API key found in request"}, status_code=401, reason="Unauthorized")+ ]++ with pytest.raises(HTTPError, match="401 Client Error"):+ _drive(MESSAGE_STATUS, responses, request_ids="id-1")++ def test_no_request_ids_yields_nothing_without_requests(self) -> None:+ rows, sent = _drive(MESSAGE_STATUS, [], request_ids=None)++ assert rows == []+ assert sent == []+++class TestListEndpoints:+ @pytest.mark.parametrize(+ ("endpoint", "path", "body", "expected_rows"),+ [+ (+ CONTACTS,+ "https://api.tyntec.com/byon/contacts/v1",+ {"contacts": [{"contactId": "c-1"}, {"contactId": "c-2"}], "size": 2},+ [{"contactId": "c-1"}, {"contactId": "c-2"}],+ ),+ (+ PHONE_NUMBERS,+ "https://api.tyntec.com/byon/phonebook/v1/numbers",+ {"provisioningRequests": [{"requestId": "r-1"}], "size": 1},+ [{"requestId": "r-1"}],+ ),+ (+ PHONE_REGISTRATIONS,+ "https://api.tyntec.com/byon/provisioning/v1",+ {"provisioningRequests": [{"requestId": "r-2"}], "size": 1},+ [{"requestId": "r-2"}],+ ),+ ],+ )+ def test_unwraps_response_wrapper(+ self, endpoint: str, path: str, body: dict[str, Any], expected_rows: list[dict[str, Any]]+ ) -> None:+ rows, sent = _drive(endpoint, [_make_http_response(body)])++ assert rows == expected_rows+ assert len(sent) == 1+ assert sent[0]["url"] == path+ # Redirects must not be followed: the apikey header would replay to the redirect target.+ assert sent[0]["allow_redirects"] is False++ def test_phone_numbers_requests_full_documented_cap(self) -> None:+ _, sent = _drive(PHONE_NUMBERS, [_make_http_response({"provisioningRequests": [], "size": 0})])++ assert sent[0]["params"] == {"size": PHONEBOOK_MAX_SIZE}++ def test_contacts_empty_list_yields_no_rows(self) -> None:+ rows, _ = _drive(CONTACTS, [_make_http_response({"contacts": [], "size": 0})])++ assert rows == []+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [+ (200, True),+ # Unknown probe id with a valid key answers 404.+ (404, True),+ # Missing key at the gateway.+ (401, False),+ # Invalid key at the gateway.+ (403, False),+ ],+ )+ def test_status_mapping(self, status_code: int, expected: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.tyntec_sms.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.get.return_value = _make_http_response({}, status_code=status_code)++ assert validate_credentials("test-key") is expected++ _, kwargs = mock_session.get.call_args+ assert kwargs["headers"] == {"apikey": "test-key"}+ assert kwargs["allow_redirects"] is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms_source.pynew file mode 100644index 000000000000..693653f59c58--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tests/test_tyntec_sms_source.py@@ -0,0 +1,114 @@+import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tyntecsms import (+ TyntecSMSSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.settings import (+ CONTACTS,+ ENDPOINTS,+ MESSAGE_STATUS,+ PHONE_NUMBERS,+ PHONE_REGISTRATIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.source import TyntecSMSSource+++class TestTyntecSMSSource:+ def setup_method(self) -> None:+ self.source = TyntecSMSSource()++ def test_get_schemas_are_full_refresh_only(self) -> None:+ # tyntec has no server-side timestamp filters, so no table may advertise incremental sync.+ schemas = self.source.get_schemas(TyntecSMSSourceConfig(api_key="key"), team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)++ @pytest.mark.parametrize(+ ("endpoint", "expected_default"),+ [+ (MESSAGE_STATUS, True),+ # BYON tables default off: the live gateway 404s them on accounts without the+ # BYON service, and a default-on table would fail every fresh source's first sync.+ (CONTACTS, False),+ (PHONE_NUMBERS, False),+ (PHONE_REGISTRATIONS, False),+ ],+ )+ def test_should_sync_defaults(self, endpoint: str, expected_default: bool) -> None:+ schemas = self.source.get_schemas(TyntecSMSSourceConfig(api_key="key"), team_id=1)+ schema = next(s for s in schemas if s.name == endpoint)++ assert schema.should_sync_default is expected_default++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(TyntecSMSSourceConfig(api_key="key"), team_id=1, names=[CONTACTS])++ assert [schema.name for schema in schemas] == [CONTACTS]++ def test_validate_credentials_rejects_empty_key_without_network(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.source.validate_tyntec_credentials"+ ) as mock_validate:+ valid, error = self.source.validate_credentials(TyntecSMSSourceConfig(api_key=""), team_id=1)++ assert valid is False+ assert error is not None+ mock_validate.assert_not_called()++ @pytest.mark.parametrize(("api_accepts_key", "expected_valid"), [(True, True), (False, False)])+ def test_validate_credentials_maps_helper_result(self, api_accepts_key: bool, expected_valid: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.source.validate_tyntec_credentials",+ return_value=api_accepts_key,+ ):+ valid, error = self.source.validate_credentials(TyntecSMSSourceConfig(api_key="key"), team_id=1)++ assert valid is expected_valid+ assert (error is None) is expected_valid++ def test_source_for_pipeline_plumbs_config_and_inputs(self) -> None:+ config = TyntecSMSSourceConfig(api_key="key", request_ids="id-1, id-2")+ inputs = MagicMock(spec=SourceInputs)+ inputs.schema_name = MESSAGE_STATUS+ inputs.team_id = 42+ inputs.job_id = "job-1"++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.source.tyntec_sms_source"+ ) as mock_source:+ response = self.source.source_for_pipeline(config, inputs)++ mock_source.assert_called_once_with(+ api_key="key",+ endpoint=MESSAGE_STATUS,+ team_id=42,+ job_id="job-1",+ request_ids="id-1, id-2",+ )+ assert response is mock_source.return_value++ @pytest.mark.parametrize(+ "url",+ [+ "https://api.tyntec.com/messaging/v1/messages/some-id",+ "https://api.tyntec.com/byon/contacts/v1",+ ],+ )+ @pytest.mark.parametrize(("status_code", "reason"), [(401, "Unauthorized"), (403, "Forbidden")])+ def test_auth_http_errors_are_non_retryable(self, status_code: int, reason: str, url: str) -> None:+ # A bad key must permanently fail the job; a message-format mismatch here means endless retries.+ response = requests.Response()+ response.status_code = status_code+ response.url = url+ response.reason = reason++ with pytest.raises(requests.HTTPError) as exc_info:+ response.raise_for_status()++ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in non_retryable_errors)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tyntec_sms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tyntec_sms.pynew file mode 100644index 000000000000..482f53fd606d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tyntec_sms/tyntec_sms.py@@ -0,0 +1,156 @@+import re+from collections.abc import Iterator+from typing import Any+from urllib.parse import quote++import structlog++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 import (+ RESTAPIConfig,+ rest_api_resource,+)+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.rest_source.config_setup import (+ create_response_hooks,+)+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.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.tyntec_sms.settings import (+ LIST_ENDPOINTS,+ MAX_REQUEST_IDS,+ MESSAGE_STATUS,+ MESSAGE_STATUS_PATH,+ PHONE_NUMBERS,+ PHONEBOOK_MAX_SIZE,+ PRIMARY_KEYS,+)++logger = structlog.get_logger(__name__)++BASE_URL = "https://api.tyntec.com"+API_KEY_HEADER = "apikey"++# Syntactically valid request id used only to probe credentials: with a valid key the API+# answers 404 (unknown message) while a missing/invalid key is rejected at the gateway with+# 401/403 — verified against the live API.+_CREDENTIALS_PROBE_REQUEST_ID = "00000000-0000-0000-0000-000000000000"+++def parse_request_ids(raw: str | None) -> list[str]:+ """Split the user-provided request-id blob on commas/whitespace, deduped, order preserved.++ Capped at ``MAX_REQUEST_IDS`` (each id is one HTTP request per sync)."""+ if not raw:+ return []+ seen: set[str] = set()+ request_ids: list[str] = []+ for token in re.split(r"[\s,]+", raw):+ token = token.strip()+ if token and token not in seen:+ seen.add(token)+ request_ids.append(token)+ if len(request_ids) >= MAX_REQUEST_IDS:+ logger.warning(+ "tyntec_sms request id list truncated",+ max_request_ids=MAX_REQUEST_IDS,+ )+ break+ return request_ids+++def _message_status_rows(api_key: str, request_ids: list[str]) -> Iterator[dict[str, Any]]:+ # Host-pinned with redirects rejected: `requests` only strips `Authorization` on a+ # cross-origin redirect, so following a 30x would replay the `apikey` header off-origin.+ client = RESTClient(+ base_url=BASE_URL,+ auth=APIKeyAuth(api_key=api_key, name=API_KEY_HEADER, location="header"),+ allowed_hosts=[],+ allow_redirects=False,+ )+ # tyntec retains message statuses for ~3 months after a final delivery state; expired or+ # unknown ids answer 404 and are skipped instead of failing the sync. Other 4xx (401/403)+ # still raise via the hook's raise_for_status fallback.+ hooks = create_response_hooks([{"status_code": 404, "action": "ignore"}])+ for request_id in request_ids:+ for page in client.paginate(+ path=MESSAGE_STATUS_PATH.format(request_id=quote(request_id, safe="")),+ hooks=hooks,+ ):+ yield from page+++def _list_endpoint_resource(endpoint: str) -> EndpointResource:+ path, data_key = LIST_ENDPOINTS[endpoint]+ params: dict[str, Any] = {}+ if endpoint == PHONE_NUMBERS:+ params["size"] = PHONEBOOK_MAX_SIZE+ return {+ "name": endpoint,+ "table_name": endpoint.lower(),+ "write_disposition": "replace",+ "endpoint": {+ "data_selector": data_key,+ "path": path,+ "params": params,+ },+ "table_format": "delta",+ }+++def tyntec_sms_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ request_ids: str | None = None,+) -> SourceResponse:+ if endpoint == MESSAGE_STATUS:+ parsed_ids = parse_request_ids(request_ids)+ return SourceResponse(+ name=endpoint,+ items=lambda: _message_status_rows(api_key, parsed_ids),+ primary_keys=PRIMARY_KEYS[endpoint],+ )++ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {+ "type": "api_key",+ "name": API_KEY_HEADER,+ "api_key": api_key,+ "location": "header",+ },+ "paginator": "single_page",+ # See _message_status_rows: reject redirects so the apikey header can't leak off-origin.+ "allowed_hosts": [],+ "allow_redirects": False,+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [_list_endpoint_resource(endpoint)],+ }++ resource = rest_api_resource(config, team_id, job_id, None)++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[endpoint],+ )+++def validate_credentials(api_key: str) -> bool:+ session = make_tracked_session(redact_values=(api_key,))+ res = session.get(+ f"{BASE_URL}{MESSAGE_STATUS_PATH.format(request_id=_CREDENTIALS_PROBE_REQUEST_ID)}",+ headers={API_KEY_HEADER: api_key},+ # Don't follow redirects: the apikey header would be replayed to the redirect target.+ allow_redirects=False,+ )+ # 401 = missing/unknown key, 403 = invalid credentials; any other status (typically a 404+ # problem document for the unknown probe id) means the key was accepted.+ return res.status_code not in (401, 403)