Skip to content

Commit 2d608d5

Browse files
authored
Retry logic when granting authz to new tasks (#79)
This should avoid failures when creating a task due to temporary unavailability of the authz service
1 parent 356290f commit 2d608d5

1 file changed

Lines changed: 30 additions & 3 deletions

File tree

agentex/src/domain/use_cases/agents_acp_use_case.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
import asyncio
12
import json
3+
import random
24
from collections.abc import AsyncIterator, Callable
35
from typing import Annotated, Any
46

57
from fastapi import Depends
68

9+
from src.adapters.authentication.exceptions import (
10+
AuthenticationServiceUnavailableError,
11+
)
712
from src.adapters.crud_store.exceptions import ItemDoesNotExist
813
from src.api.schemas.authorization_types import (
914
AgentexResource,
@@ -227,6 +232,30 @@ async def _execute_with_error_handling(
227232
await self.task_service.fail_task(task, str(e))
228233
raise e
229234

235+
async def grant_with_retry(self, task: TaskEntity, attempts: int = 0) -> None:
236+
"""Grant authorization for a task with retry"""
237+
try:
238+
await self.authorization_service.grant(
239+
resource=AgentexResource.task(task.id),
240+
)
241+
except AuthenticationServiceUnavailableError as e:
242+
if attempts < 3:
243+
delay = 0.2 * (2**attempts) + random.uniform(0, 0.1)
244+
logger.error(
245+
f"Authentication service unavailable: {e}. Retrying in {delay}s..."
246+
)
247+
await asyncio.sleep(delay)
248+
return await self.grant_with_retry(task, attempts + 1)
249+
else:
250+
logger.error(
251+
f"Authentication service unavailable: {e}. Max retries reached."
252+
)
253+
raise e from e
254+
except Exception as e:
255+
logger.error(f"Error granting authorization for task {task.id}: {e}")
256+
await self.task_service.fail_task(task, str(e))
257+
raise e from e
258+
230259
async def _get_or_create_task(
231260
self,
232261
*,
@@ -273,9 +302,7 @@ async def _get_or_create_task(
273302
agent=agent, task_name=task_name, task_params=task_params
274303
)
275304
logger.info(f"[agent_id={agent.id}] Created task {task.id}")
276-
await self.authorization_service.grant(
277-
resource=AgentexResource.task(task.id),
278-
)
305+
await self.grant_with_retry(task)
279306
return task
280307

281308
async def handle_rpc_request(

0 commit comments

Comments
 (0)