Skip to content

fix: remove false success log & improve retry log #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion _test_unstructured_client/unit/test_custom_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_unit_retry_with_backoff_does_retry(caplog):


@pytest.mark.parametrize("status_code", [500, 503])
def test_unit_backoff_strategy_logs_retries(status_code: int, caplog):
def test_unit_backoff_strategy_logs_retries_5XX(status_code: int, caplog):
caplog.set_level(logging.INFO)
filename = "README.md"
backoff_strategy = BackoffStrategy(
Expand All @@ -64,11 +64,38 @@ def test_unit_backoff_strategy_logs_retries(status_code: int, caplog):
req = shared.PartitionParameters(files=files)
with pytest.raises(Exception):
session.general.partition(req, retries=retries)

pattern = re.compile(f"Failed to process a request due to API server error with status code {status_code}. "
"Attempting retry number 1 after sleep.")
assert bool(pattern.search(caplog.text))


def test_unit_backoff_strategy_logs_retries_connection_error(caplog):
caplog.set_level(logging.INFO)
filename = "README.md"
backoff_strategy = BackoffStrategy(
initial_interval=10, max_interval=100, exponent=1.5, max_elapsed_time=300
)
retries = RetryConfig(
strategy="backoff", backoff=backoff_strategy, retry_connection_errors=True
)
with requests_mock.Mocker() as mock:
# mock a 500/503 status code for POST requests to the api
mock.post("https://api.unstructured.io/general/v0/general", exc=requests.exceptions.ConnectionError)
session = UnstructuredClient(api_key_auth=FAKE_KEY)

with open(filename, "rb") as f:
files = shared.Files(content=f.read(), file_name=filename)

req = shared.PartitionParameters(files=files)
with pytest.raises(Exception):
session.general.partition(req, retries=retries)

pattern = re.compile(f"Failed to process a request due to connection error .*? "
"Attempting retry number 1 after sleep.")
assert bool(pattern.search(caplog.text))


@pytest.mark.parametrize(
"server_url",
[
Expand Down
19 changes: 17 additions & 2 deletions src/unstructured_client/_hooks/custom/logger_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class LoggerHook(AfterErrorHook, SDKInitHook):
def __init__(self) -> None:
self.retries_counter: DefaultDict[str, int] = defaultdict(int)

def log_retries(self, response: Optional[requests.Response], operation_id: str):
def log_retries(self, response: Optional[requests.Response], error: Optional[Exception], operation_id: str,):
"""Log retries to give users visibility into requests."""

if response is not None and response.status_code // 100 == 5:
Expand All @@ -33,6 +33,20 @@ def log_retries(self, response: Optional[requests.Response], operation_id: str):
)
if response.text:
logger.info("Server message - %s", response.text)

elif error is not None and isinstance(error, requests.exceptions.ConnectionError):
logger.info(
"Failed to process a request due to connection error - %s. "
"Attempting retry number %d after sleep.",
error,
self.retries_counter[operation_id],
)
else:
logger.error("Failed to partition the document.")
if response is not None:
logging.error("Server responded with %d - %s", response.status_code, response.text)
if error is not None:
logging.error("Following error occurred - %s", error)

def sdk_init(
self, base_url: str, client: requests.Session
Expand All @@ -44,6 +58,7 @@ def after_success(
self, hook_ctx: AfterSuccessContext, response: requests.Response
) -> Union[requests.Response, Exception]:
del self.retries_counter[hook_ctx.operation_id]
logging.info("Successfully partitioned the document.")
return response

def after_error(
Expand All @@ -54,5 +69,5 @@ def after_error(
) -> Union[Tuple[Optional[requests.Response], Optional[Exception]], Exception]:
"""Concrete implementation for AfterErrorHook."""
self.retries_counter[hook_ctx.operation_id] += 1
self.log_retries(response, hook_ctx.operation_id)
self.log_retries(response, error, hook_ctx.operation_id)
return response, error
6 changes: 0 additions & 6 deletions src/unstructured_client/_hooks/custom/split_pdf_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,6 @@ def after_success(

updated_response = request_utils.create_response(response, elements)
self._clear_operation(operation_id)
logger.info("Successfully processed the request.")
return updated_response

def after_error(
Expand Down Expand Up @@ -332,21 +331,16 @@ def after_error(
successful_responses = self.api_successful_responses.get(operation_id)

if elements is None or successful_responses is None:
logger.info("Successfully processed the request.")
return (response, error)

if len(successful_responses) == 0:
logger.error("Failed to process the request.")
if error is not None:
logger.error(error)
self._clear_operation(operation_id)
return (response, error)

updated_response = request_utils.create_response(
successful_responses[0], elements
)
self._clear_operation(operation_id)
logger.info("Successfully processed the request.")
return (updated_response, None)

def _clear_operation(self, operation_id: str) -> None:
Expand Down
4 changes: 3 additions & 1 deletion src/unstructured_client/_hooks/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ def init_hooks(hooks: Hooks):
# Register After Error hooks
hooks.register_after_error_hook(suggest_defining_url_hook)
hooks.register_after_error_hook(split_pdf_hook)
hooks.register_after_error_hook(logger_hook)
# NOTE: logger_hook should stay registered last as logs the status of
# request and whether it will be retried which can be changed by e.g. split_pdf_hook
hooks.register_after_error_hook(logger_hook)