: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
fix(salesforce): retry token refresh through a transient proxy failure (#87436)
Tom Owers47b6406bfc26
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.pyindex 3645e55494c1..f4fecc8ac18b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py@@ -5,7 +5,11 @@ from typing import Any, Optionalfrom django.conf import settingsfrom requests import Response-from requests.exceptions import JSONDecodeError+from requests.exceptions import (+ ConnectionError as RequestsConnectionError,+ JSONDecodeError,+ Timeout as RequestsTimeout,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth@@ -92,15 +96,26 @@ def salesforce_refresh_access_token(refresh_token: str, instance_url: str, *, casession = make_tracked_session(redact_values=(refresh_token,), capture=capture)attempt = 0while True:- res = session.post(- f"{instance_url}/services/oauth2/token",- data={- "grant_type": "refresh_token",- "client_id": settings.SALESFORCE_CONSUMER_KEY,- "client_secret": settings.SALESFORCE_CONSUMER_SECRET,- "refresh_token": refresh_token,- },- )+ try:+ res = session.post(+ f"{instance_url}/services/oauth2/token",+ data={+ "grant_type": "refresh_token",+ "client_id": settings.SALESFORCE_CONSUMER_KEY,+ "client_secret": settings.SALESFORCE_CONSUMER_SECRET,+ "refresh_token": refresh_token,+ },+ )+ except (RequestsConnectionError, RequestsTimeout):+ # A failed connection or timeout reaching the token endpoint — most often PostHog's+ # egress proxy returning a transient 502 on CONNECT — never minted a token, so it's safe+ # to reissue. Without this in-process retry a single proxy blip fails the whole import+ # activity before it reads a row, and the sync restarts from scratch.+ attempt += 1+ if attempt >= _MAX_TOKEN_REFRESH_ATTEMPTS:+ raise+ time.sleep(min(0.5 * attempt, 5))+ continuetry:SalesforceAuthRequestError.raise_from_response(res)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.pyindex 7d25b9c01b81..73e595be3cfb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py@@ -108,6 +108,61 @@ def _session_returning(responses: list[requests.Response]):return type("_S", (), {"post": staticmethod(lambda *a, **k: next(it))})()+def _session_with_side_effects(items: list):+ # Each item is either a Response to return or an Exception to raise, in order.+ it = iter(items)++ def _post(*a, **k):+ item = next(it)+ if isinstance(item, Exception):+ raise item+ return item++ return type("_S", (), {"post": staticmethod(_post)})()+++def test_refresh_retries_transient_transport_error_then_succeeds():+ # PostHog's egress proxy can return a transient 502 on CONNECT, surfaced as a requests+ # ProxyError before any token is minted; retrying should recover instead of failing the sync.+ items = [+ requests.exceptions.ProxyError("Cannot connect to proxy"),+ requests.exceptions.ProxyError("Cannot connect to proxy"),+ _token_response(200, {"access_token": "fresh-token"}),+ ]++ with (+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.make_tracked_session",+ return_value=_session_with_side_effects(items),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ) as mock_sleep,+ ):+ token = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")++ assert token == "fresh-token"+ assert mock_sleep.call_count == 2+++def test_refresh_raises_transport_error_after_exhausting_retries():+ items = [requests.exceptions.ProxyError("Cannot connect to proxy") for _ in range(auth._MAX_TOKEN_REFRESH_ATTEMPTS)]++ with (+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.make_tracked_session",+ return_value=_session_with_side_effects(items),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ) as mock_sleep,+ pytest.raises(requests.exceptions.ProxyError),+ ):+ _ = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")++ assert mock_sleep.call_count == auth._MAX_TOKEN_REFRESH_ATTEMPTS - 1++def test_refresh_retries_transient_token_request_then_succeeds():# Salesforce locks concurrent token requests with a 400 "token request is already being# processed"; the lock clears, so a retry should recover instead of failing the sync.