Skip to content

Commit

Permalink
Handled request timeout error in async client - Http action. (#1083)
Browse files Browse the repository at this point in the history
* Handled request timeout error in async client - Http action.

* Handled request timeout error in async client - Http action.

* Handled request timeout error in async client - Http action.

* Handled request timeout error in async client - Http action.

---------

Co-authored-by: Nupur Khare <[email protected]>
  • Loading branch information
nupur-khare and Nupur Khare authored Nov 24, 2023
1 parent ee0845d commit c92debf
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 4 deletions.
3 changes: 1 addition & 2 deletions kairon/actions/definitions/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from rasa_sdk import Tracker
from rasa_sdk.executor import CollectingDispatcher

from kairon import Utility
from kairon.actions.definitions.base import ActionsBase
from kairon.shared.actions.data_objects import ActionServerLogs, HttpActionConfig
from kairon.shared.actions.exception import ActionFailure
Expand Down Expand Up @@ -99,7 +98,7 @@ async def execute(self, dispatcher: CollectingDispatcher, tracker: Tracker, doma
filled_slots.update(slot_values)
logger.info("response: " + str(bot_response))
except Exception as e:
exception = f"Request timed out in {Utility.environment['actors']['default_timeout']} seconds, try again!"
exception = str(e)
logger.exception(e)
status = "FAILURE"
bot_response = "I have failed to process your request"
Expand Down
4 changes: 4 additions & 0 deletions kairon/shared/rest_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
from abc import ABC
from typing import Union

Expand Down Expand Up @@ -79,6 +80,9 @@ async def __trigger_request(self, request_method: str, http_url: str, retry_opti
logger.exception(e)
_, _, host, _, _, _, _ = parse_url(http_url)
raise AppException(f"Failed to connect to service: {host}")
except asyncio.TimeoutError as e:
logger.exception(e)
raise AppException(f"Request timed out: {str(e)}")
except Exception as e:
logger.exception(e)
raise AppException(f"Failed to execute the url: {str(e)}")
Expand Down
7 changes: 5 additions & 2 deletions tests/integration_test/action_service_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import json
import os

Expand Down Expand Up @@ -2736,7 +2737,8 @@ def test_http_action_execution_script_evaluation_failure_and_dispatch_2(aiorespo

@patch("kairon.shared.actions.utils.ActionUtility.get_action")
@patch("kairon.actions.definitions.http.ActionHTTP.retrieve_config")
def test_http_action_failed_execution(mock_action_config, mock_action):
@mock.patch("kairon.shared.rest_client.AioRestClient._AioRestClient__trigger", autospec=True)
def test_http_action_failed_execution(mock_trigger_request, mock_action_config, mock_action):
action_name = "test_run_with_get"
action = Actions(name=action_name, type=ActionType.http_action.value, bot="5f50fd0a56b698ca10d35d2e",
user="user")
Expand Down Expand Up @@ -2785,6 +2787,7 @@ def _get_action(*arge, **kwargs):
}
mock_action.side_effect = _get_action
mock_action_config.side_effect = _get_action_config
mock_trigger_request.side_effect = asyncio.TimeoutError('408')
response = client.post("/webhook", json=request_object)
response_json = response.json()
assert response.status_code == 200
Expand All @@ -2801,7 +2804,7 @@ def _get_action(*arge, **kwargs):
assert log == {'type': 'http_action', 'intent': 'test_run', 'action': 'test_run_with_get', 'sender': 'default',
'headers': {}, 'url': 'http://localhost:8082/mock', 'request_method': 'GET', 'request_params': {},
'bot_response': 'I have failed to process your request',
'exception': 'Request timed out in 10 seconds, try again!', 'messages': [],
'exception': 'Request timed out: 408', 'messages': [],
'bot': '5f50fd0a56b698ca10d35d2e', 'status': 'FAILURE', 'user_msg': 'get intents'}


Expand Down
15 changes: 15 additions & 0 deletions tests/unit_test/rest_client_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import asyncio
from unittest import mock

import pytest

from kairon.exceptions import AppException
Expand Down Expand Up @@ -86,3 +89,15 @@ async def test_aio_rest_client_unsupported_request(self):
with pytest.raises(AppException, match="Invalid request method!"):
await AioRestClient().request("options", url, request_body={"name": "udit.pandey", "loc": "blr"},
headers={"Authorization": "Bearer sasdfghjkytrtyui"})

@pytest.mark.asyncio
async def test_aio_rest_client_timeout_error(self, aioresponses):
url = 'http://kairon.com'
aioresponses.get(url, status=200, payload={"data": "hi!"})
with mock.patch("kairon.shared.rest_client.AioRestClient._AioRestClient__trigger", side_effect=asyncio.TimeoutError("Request timed out")):
with pytest.raises(AppException, match="Request timed out: Request timed out"):
await AioRestClient().request("get", url, request_body={"name": "udit.pandey", "loc": "blr"},
headers={"Authorization": "Bearer sasdfghjkytrtyui"})
with pytest.raises(AppException, match="Request timed out: Request timed out"):
await AioRestClient().request("get", url, request_body={"name": "udit.pandey", "loc": "blr"},
headers={"Authorization": "Bearer sasdfghjkytrtyui"}, max_retries=3)

0 comments on commit c92debf

Please sign in to comment.