|
1 | 1 | # Copyright (c) Microsoft Corporation. |
2 | 2 | # Licensed under the MIT License. |
3 | 3 |
|
| 4 | +import asyncio |
4 | 5 | import unittest |
5 | 6 | from concurrent import futures |
6 | 7 | from datetime import datetime, timedelta, timezone |
|
13 | 14 | from azure.core.credentials import AccessToken |
14 | 15 |
|
15 | 16 | from durabletask.azuremanaged.client import DurableTaskSchedulerClient |
16 | | -from durabletask.azuremanaged.internal.access_token_manager import AccessTokenManager |
| 17 | +from durabletask.azuremanaged.internal.access_token_manager import ( |
| 18 | + AccessTokenManager, |
| 19 | + AsyncAccessTokenManager, |
| 20 | +) |
17 | 21 | from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker |
18 | 22 | from durabletask.internal.grpc_interceptor import DefaultClientInterceptorImpl |
19 | 23 | from durabletask.internal import orchestrator_service_pb2 as pb |
@@ -230,5 +234,108 @@ def test_concurrent_refresh_performs_single_refresh(self): |
230 | 234 | self.assertEqual(2, credential.calls) |
231 | 235 |
|
232 | 236 |
|
| 237 | +class _CredentialError(Exception): |
| 238 | + pass |
| 239 | + |
| 240 | + |
| 241 | +class _TestAsyncTokenCredential: |
| 242 | + def __init__(self, delay: float = 0.02): |
| 243 | + self.calls = 0 |
| 244 | + self._delay = delay |
| 245 | + |
| 246 | + async def get_token(self, _scope): |
| 247 | + # Counting before the await means every coroutine that reaches the credential |
| 248 | + # is recorded, which is what makes a thundering herd observable. |
| 249 | + self.calls += 1 |
| 250 | + call_number = self.calls |
| 251 | + await asyncio.sleep(self._delay) |
| 252 | + return AccessToken(f"token-{call_number}", int(time.time()) + 3600) |
| 253 | + |
| 254 | + |
| 255 | +class _FlakyAsyncTokenCredential: |
| 256 | + def __init__(self): |
| 257 | + self.calls = 0 |
| 258 | + self.fail = True |
| 259 | + |
| 260 | + async def get_token(self, _scope): |
| 261 | + self.calls += 1 |
| 262 | + await asyncio.sleep(0) |
| 263 | + if self.fail: |
| 264 | + raise _CredentialError("credential unavailable") |
| 265 | + return AccessToken("token-recovered", int(time.time()) + 3600) |
| 266 | + |
| 267 | + |
| 268 | +class TestAsyncAccessTokenManagerSingleFlight(unittest.IsolatedAsyncioTestCase): |
| 269 | + async def test_deferred_first_acquisition_performs_single_acquisition(self): |
| 270 | + credential = _TestAsyncTokenCredential() |
| 271 | + manager = AsyncAccessTokenManager(credential) |
| 272 | + |
| 273 | + self.assertEqual(0, credential.calls, "Constructing the manager must not acquire a token") |
| 274 | + |
| 275 | + # The async manager has always deferred the first acquisition (a constructor |
| 276 | + # cannot await), so the cold-start burst goes through the same refresh guard |
| 277 | + # as a later refresh and must likewise be single-flight. |
| 278 | + tokens = await asyncio.gather(*(manager.get_access_token() for _ in range(16))) |
| 279 | + |
| 280 | + self.assertEqual(1, credential.calls) |
| 281 | + self.assertEqual({"token-1"}, {token.token for token in tokens}) |
| 282 | + |
| 283 | + async def test_concurrent_refresh_performs_single_refresh(self): |
| 284 | + credential = _TestAsyncTokenCredential() |
| 285 | + manager = AsyncAccessTokenManager(credential) |
| 286 | + await manager.get_access_token() |
| 287 | + self.assertEqual(1, credential.calls) |
| 288 | + |
| 289 | + manager.expiry_time = datetime.now(timezone.utc) - timedelta(seconds=1) |
| 290 | + |
| 291 | + tokens = await asyncio.gather(*(manager.get_access_token() for _ in range(16))) |
| 292 | + |
| 293 | + self.assertEqual(2, credential.calls) |
| 294 | + self.assertEqual({"token-2"}, {token.token for token in tokens}) |
| 295 | + |
| 296 | + async def test_valid_token_is_returned_without_contacting_credential(self): |
| 297 | + credential = _TestAsyncTokenCredential() |
| 298 | + manager = AsyncAccessTokenManager(credential) |
| 299 | + |
| 300 | + first = await manager.get_access_token() |
| 301 | + second = await manager.get_access_token() |
| 302 | + |
| 303 | + self.assertEqual(1, credential.calls) |
| 304 | + self.assertIs(first, second) |
| 305 | + |
| 306 | + async def test_credential_failure_propagates_and_does_not_deadlock(self): |
| 307 | + credential = _FlakyAsyncTokenCredential() |
| 308 | + manager = AsyncAccessTokenManager(credential) |
| 309 | + |
| 310 | + results = await asyncio.gather( |
| 311 | + *(manager.get_access_token() for _ in range(4)), return_exceptions=True) |
| 312 | + |
| 313 | + self.assertTrue(all(isinstance(result, _CredentialError) for result in results)) |
| 314 | + |
| 315 | + # The guard must have been released on failure so a later attempt can succeed. |
| 316 | + credential.fail = False |
| 317 | + token = await manager.get_access_token() |
| 318 | + self.assertIsNotNone(token) |
| 319 | + self.assertEqual("token-recovered", token.token) |
| 320 | + |
| 321 | + |
| 322 | +class TestAsyncAccessTokenManagerEventLoopBinding(unittest.TestCase): |
| 323 | + def test_manager_is_reusable_across_event_loops(self): |
| 324 | + credential = _TestAsyncTokenCredential(delay=0) |
| 325 | + manager = AsyncAccessTokenManager(credential) |
| 326 | + |
| 327 | + first = asyncio.run(manager.get_access_token()) |
| 328 | + |
| 329 | + manager.expiry_time = datetime.now(timezone.utc) - timedelta(seconds=1) |
| 330 | + |
| 331 | + # The second run uses a distinct event loop; the refresh guard must not stay |
| 332 | + # bound to the first, now-closed loop. |
| 333 | + second = asyncio.run(manager.get_access_token()) |
| 334 | + |
| 335 | + self.assertIsNotNone(first) |
| 336 | + self.assertIsNotNone(second) |
| 337 | + self.assertEqual(2, credential.calls) |
| 338 | + |
| 339 | + |
233 | 340 | if __name__ == "__main__": |
234 | 341 | unittest.main() |
0 commit comments