diff --git a/src/conductor/client/http/api_client.py b/src/conductor/client/http/api_client.py index c753da008..fef632403 100644 --- a/src/conductor/client/http/api_client.py +++ b/src/conductor/client/http/api_client.py @@ -7,6 +7,7 @@ import os import re import tempfile +import threading import time from typing import Dict, Optional, TYPE_CHECKING import uuid @@ -68,6 +69,9 @@ def __init__( self._token_refresh_failures = 0 self._last_token_refresh_attempt = 0 self._max_token_refresh_failures = 5 # Stop after 5 consecutive failures + # Serializes token renewal so threads that need a new token together fetch it once. + # RLock because the token fetch itself goes through call_api. + self._token_lock = threading.RLock() # Metrics collector for API request tracking self.metrics_collector = metrics_collector @@ -95,7 +99,7 @@ def __call_api( logger.info( f'Authentication token is {token_status}, renewing token... (request: {method} {resource_path})') # if the token has expired or is invalid, lets refresh the token - success = self.__force_refresh_auth_token() + success = self.__refresh_auth_token_if_stale(getattr(ae, 'rejected_token', None)) if success: logger.debug('Authentication token successfully renewed') # and now retry the same request @@ -176,13 +180,18 @@ def __call_api_no_retry( url = self.configuration.host + resource_path # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - metric_uri=metric_uri, - metric_context=metric_context) + try: + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + metric_uri=metric_uri, + metric_context=metric_context) + except AuthorizationException as ae: + # The token this request carried, so a refresh can tell whether another thread already replaced it. + ae.rejected_token = auth_headers['header']['X-Authorization'] if auth_headers else None + raise return_data = response_data if _preload_content: @@ -793,12 +802,15 @@ def __get_authentication_headers(self): time_since_last_update = now - self.configuration.token_update_time if time_since_last_update > self.configuration.auth_token_ttl_msec: - # time to refresh the token - skip backoff for legitimate renewal - logger.info('Authentication token TTL expired, renewing token...') - token = self.__get_new_token(skip_backoff=True) - self.configuration.update_token(token) - if token: - logger.debug('Authentication token successfully renewed') + with self._token_lock: + # Threads that found the token expired together queue here; only the first renews it. + if now - self.configuration.token_update_time > self.configuration.auth_token_ttl_msec: + # time to refresh the token - skip backoff for legitimate renewal + logger.info('Authentication token TTL expired, renewing token...') + token = self.__get_new_token(skip_backoff=True) + self.configuration.update_token(token) + if token: + logger.debug('Authentication token successfully renewed') return { 'header': { @@ -840,6 +852,20 @@ def __force_refresh_auth_token(self) -> bool: """Deprecated: Use force_refresh_auth_token() instead""" return self.force_refresh_auth_token() + def __refresh_auth_token_if_stale(self, stale_token) -> bool: + """ + Replaces stale_token, the token the server rejected, unless another thread already has. + After a failover every in-flight request is rejected at once, and they should share one new token. + """ + if stale_token is None: + # The request carried no token (such as /token itself), so there is nothing to compare. + return self.__force_refresh_auth_token() + with self._token_lock: + current = self.configuration.AUTH_TOKEN + if current is not None and current != stale_token: + return True + return self.__force_refresh_auth_token() + def __get_new_token(self, skip_backoff: bool = False) -> str: """ Get a new authentication token from the server. diff --git a/src/conductor/client/http/async_api_client.py b/src/conductor/client/http/async_api_client.py index 543ec026d..4d1d2855e 100644 --- a/src/conductor/client/http/async_api_client.py +++ b/src/conductor/client/http/async_api_client.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import base64 import datetime import logging @@ -70,6 +71,8 @@ def __init__( self._token_refresh_failures = 0 self._last_token_refresh_attempt = 0 self._max_token_refresh_failures = 5 # Stop after 5 consecutive failures + # Serializes token renewal so coroutines that need a new token together fetch it once. + self._token_lock = asyncio.Lock() # Metrics collector for API request tracking self.metrics_collector = metrics_collector @@ -106,7 +109,7 @@ async def __call_api( logger.info( f'Authentication token is {token_status}, renewing token... (request: {method} {resource_path})') # if the token has expired or is invalid, lets refresh the token - success = await self.__force_refresh_auth_token() + success = await self.__refresh_auth_token_if_stale(getattr(ae, 'rejected_token', None)) if success: logger.debug('Authentication token successfully renewed') # and now retry the same request @@ -186,12 +189,17 @@ async def __call_api_no_retry( url = self.configuration.host + resource_path # perform request and return response - response_data = await self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - metric_uri=metric_uri) + try: + response_data = await self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + metric_uri=metric_uri) + except AuthorizationException as ae: + # The token this request carried, so a refresh can tell whether another coroutine already replaced it. + ae.rejected_token = auth_headers['header']['X-Authorization'] if auth_headers else None + raise return_data = response_data if _preload_content: @@ -755,11 +763,14 @@ async def __get_authentication_headers(self): if self.configuration.AUTH_TOKEN is None: if self.configuration.authentication_settings is None: return None - # Initial token generation - apply backoff if there were previous failures - logger.debug('No auth token found, requesting initial token...') - token = await self.__get_new_token(skip_backoff=False) - self.configuration.update_token(token) - if not token: + async with self._token_lock: + # Coroutines that start together queue here; only the first fetches the initial token. + if self.configuration.AUTH_TOKEN is None: + # Initial token generation - apply backoff if there were previous failures + logger.debug('No auth token found, requesting initial token...') + token = await self.__get_new_token(skip_backoff=False) + self.configuration.update_token(token) + if not self.configuration.AUTH_TOKEN: # Failed to get initial token return None @@ -767,12 +778,15 @@ async def __get_authentication_headers(self): time_since_last_update = now - self.configuration.token_update_time if time_since_last_update > self.configuration.auth_token_ttl_msec: - # time to refresh the token - skip backoff for legitimate renewal - logger.info('Authentication token TTL expired, renewing token...') - token = await self.__get_new_token(skip_backoff=True) - self.configuration.update_token(token) - if token: - logger.debug('Authentication token successfully renewed') + async with self._token_lock: + # Coroutines that found the token expired together queue here; only the first renews it. + if now - self.configuration.token_update_time > self.configuration.auth_token_ttl_msec: + # time to refresh the token - skip backoff for legitimate renewal + logger.info('Authentication token TTL expired, renewing token...') + token = await self.__get_new_token(skip_backoff=True) + self.configuration.update_token(token) + if token: + logger.debug('Authentication token successfully renewed') return { 'header': { @@ -799,6 +813,20 @@ async def __force_refresh_auth_token(self) -> bool: """Deprecated: Use force_refresh_auth_token() instead""" return await self.force_refresh_auth_token() + async def __refresh_auth_token_if_stale(self, stale_token) -> bool: + """ + Replaces stale_token, the token the server rejected, unless another coroutine already has. + After a failover every in-flight request is rejected at once, and they should share one new token. + """ + if stale_token is None: + # The request carried no token (such as /token itself), so there is nothing to compare. + return await self.__force_refresh_auth_token() + async with self._token_lock: + current = self.configuration.AUTH_TOKEN + if current is not None and current != stale_token: + return True + return await self.__force_refresh_auth_token() + async def __get_new_token(self, skip_backoff: bool = False) -> str: """ Get a new authentication token from the server. diff --git a/tests/unit/api_client/test_token_refresh.py b/tests/unit/api_client/test_token_refresh.py new file mode 100644 index 000000000..c8be3b444 --- /dev/null +++ b/tests/unit/api_client/test_token_refresh.py @@ -0,0 +1,132 @@ +import asyncio +import threading +import time +import unittest +from concurrent.futures import ThreadPoolExecutor + +import httpx + +from conductor.client.configuration.configuration import Configuration +from conductor.client.configuration.settings.authentication_settings import AuthenticationSettings +from conductor.client.http.api_client import ApiClient +from conductor.client.http.async_api_client import AsyncApiClient +from conductor.client.http.async_rest import AsyncRESTClientObject + +SERVER_URL = 'http://server/api' +INVALID_TOKEN = {'error': 'INVALID_TOKEN', 'message': 'Not a valid token'} +N = 20 + + +def _configuration(): + return Configuration( + server_api_url=SERVER_URL, + authentication_settings=AuthenticationSettings(key_id='key', key_secret='secret'), + ) + + +def _is_token_request(request): + return request.url.path.endswith('/token') + + +class TestTokenRefresh(unittest.TestCase): + """After a failover every in-flight request is rejected at once; together they must fetch one new token.""" + + def _run(self, coro): + loop = asyncio.new_event_loop() + try: + return loop.run_until_complete(coro) + finally: + loop.close() + + def test_concurrent_rejections_fetch_one_new_token(self): + issued = [] + rejected = [] + failed_over = threading.Event() + all_rejected = threading.Barrier(N, timeout=5) + lock = threading.Lock() + + def handler(request): + if _is_token_request(request): + # Hold the fetch open so the other requests' refreshes overlap it. + time.sleep(0.05) + with lock: + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + if failed_over.is_set() and request.headers.get('X-Authorization') == 't1': + with lock: + rejected.append(None) + try: + all_rejected.wait() + except threading.BrokenBarrierError: + pass + return httpx.Response(401, json=INVALID_TOKEN) + return httpx.Response(200, json={}) + + configuration = _configuration() + configuration.http_connection = httpx.Client(transport=httpx.MockTransport(handler)) + client = ApiClient(configuration) # fetches t1 + failed_over.set() + + with ThreadPoolExecutor(max_workers=N) as pool: + futures = [pool.submit(client.call_api, '/thing', 'GET', _return_http_data_only=True) for _ in range(N)] + for future in futures: + future.result() + + self.assertEqual(N, len(rejected)) + self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry + + def test_concurrent_rejections_fetch_one_new_token_async(self): + issued = [] + rejected = [] + state = {'failed_over': False} + + async def scenario(): + all_rejected = asyncio.Event() + + async def handler(request): + if _is_token_request(request): + await asyncio.sleep(0.05) + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + if state['failed_over'] and request.headers.get('X-Authorization') == 't1': + rejected.append(None) + if len(rejected) == N: + all_rejected.set() + try: + await asyncio.wait_for(all_rejected.wait(), timeout=5) + except asyncio.TimeoutError: + pass + return httpx.Response(401, json=INVALID_TOKEN) + return httpx.Response(200, json={}) + + client = AsyncApiClient(_configuration()) + client.async_rest_client = AsyncRESTClientObject( + connection=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + await client.call_api('/thing', 'GET', _return_http_data_only=True) # fetches t1 + state['failed_over'] = True + await asyncio.gather(*(client.call_api('/thing', 'GET', _return_http_data_only=True) for _ in range(N))) + + self._run(scenario()) + + self.assertEqual(N, len(rejected)) + self.assertEqual(2, len(issued)) # t1 before the failover, t2 shared by every retry + + def test_concurrent_first_calls_fetch_one_token_async(self): + issued = [] + + async def scenario(): + async def handler(request): + if _is_token_request(request): + await asyncio.sleep(0.05) + issued.append(None) + return httpx.Response(200, json={'token': f't{len(issued)}'}) + return httpx.Response(200, json={}) + + client = AsyncApiClient(_configuration()) + client.async_rest_client = AsyncRESTClientObject( + connection=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + await asyncio.gather(*(client.call_api('/thing', 'GET', _return_http_data_only=True) for _ in range(N))) + + self._run(scenario()) + + self.assertEqual(1, len(issued))