Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
25 changes: 13 additions & 12 deletions slack_sdk/audit_logs/v1/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

import json
import logging
from functools import partial
from ssl import SSLContext
from typing import Any, List
from typing import Any, Callable, List
from typing import Dict, Optional

import aiohttp
Expand Down Expand Up @@ -243,7 +244,7 @@ async def _perform_http_request(
)

last_error = None
resp: Optional[AuditLogsResponse] = None
build_response: Optional[Callable[[], AuditLogsResponse]] = None
try:
request_kwargs = {
"headers": headers,
Expand Down Expand Up @@ -323,13 +324,15 @@ async def _perform_http_request(
self.logger.info(f"Going to retry the same request: {http_verb} {url}")
break

build_response = partial(
AuditLogsResponse,
url=url,
status_code=res.status,
raw_body=response_body,
headers=res.headers, # type: ignore[arg-type]
)
if retry_state.next_attempt_requested is False:
resp = AuditLogsResponse(
url=url,
status_code=res.status,
raw_body=response_body,
headers=res.headers, # type: ignore[arg-type]
)
resp = build_response()
_debug_log_response(self.logger, resp)
return resp

Expand Down Expand Up @@ -358,12 +361,10 @@ async def _perform_http_request(
if retry_state.next_attempt_requested is False:
raise last_error

if resp is not None:
return resp
if build_response is not None:
return build_response()
raise last_error # type: ignore[misc]

finally:
if not use_running_session:
await session.close() # type: ignore[union-attr]

return resp
25 changes: 13 additions & 12 deletions slack_sdk/scim/v1/async_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import json
import logging
from functools import partial
from ssl import SSLContext
from typing import Any, Union, List
from typing import Any, Callable, Union, List
from typing import Dict, Optional
from urllib.parse import quote

Expand Down Expand Up @@ -293,7 +294,7 @@ async def _perform_http_request(
)

last_error: Optional[Exception] = None
resp: Optional[SCIMResponse] = None
build_response: Optional[Callable[[], SCIMResponse]] = None
try:
request_kwargs = {
"headers": headers,
Expand Down Expand Up @@ -365,13 +366,15 @@ async def _perform_http_request(
self.logger.info(f"Going to retry the same request: {http_verb} {url}")
break

build_response = partial(
SCIMResponse,
url=url,
status_code=res.status,
raw_body=response_body,
headers=res.headers,
)
if retry_state.next_attempt_requested is False:
resp = SCIMResponse(
url=url,
status_code=res.status,
raw_body=response_body,
headers=res.headers,
)
resp = build_response()
_debug_log_response(self.logger, resp)
return resp

Expand Down Expand Up @@ -400,12 +403,10 @@ async def _perform_http_request(
if retry_state.next_attempt_requested is False:
raise last_error

if resp is not None:
return resp
if build_response is not None:
return build_response()
raise last_error

finally:
if not use_running_session:
await session.close()

return resp
13 changes: 8 additions & 5 deletions slack_sdk/web/async_internal_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ async def _request_with_session(
)

last_error: Optional[Exception] = None
response: Optional[Dict[str, Any]] = None
try:
retry_request = RetryHttpRequest(
method=http_verb,
Expand Down Expand Up @@ -185,12 +186,12 @@ def convert_params(values: dict) -> dict:
logger.info(f"Going to retry the same request: {http_verb} {api_url}")
break

response = {
"data": data,
"headers": res.headers,
"status_code": res.status,
}
if retry_state.next_attempt_requested is False:
response = {
"data": data,
"headers": res.headers,
"status_code": res.status,
}
return response

except Exception as e:
Expand All @@ -216,6 +217,8 @@ def convert_params(values: dict) -> dict:
if retry_state.next_attempt_requested is False:
raise last_error

if response is not None:
return response
raise last_error # type: ignore[misc]

finally:
Expand Down
12 changes: 6 additions & 6 deletions slack_sdk/webhook/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,13 @@ async def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str
self.logger.info(f"Going to retry the same request: POST {self.url}")
break

resp = WebhookResponse(
url=self.url,
status_code=res.status,
body=response_body,
headers=res.headers, # type: ignore[arg-type]
)
if retry_state.next_attempt_requested is False:
resp = WebhookResponse(
url=self.url,
status_code=res.status,
body=response_body,
headers=res.headers, # type: ignore[arg-type]
)
_debug_log_response(self.logger, resp)
return resp

Expand Down
3 changes: 2 additions & 1 deletion tests/slack_sdk/audit_logs/mock_web_api_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ def do_GET(self):
self.send_response(429)
self.send_header("retry-after", 1)
self.set_common_headers()
self.wfile.write("""{"ok": false, "error": "ratelimited"}""".encode("utf-8"))
body = "{" if "malformed" in pattern else """{"ok": false, "error": "ratelimited"}"""
self.wfile.write(body.encode("utf-8"))
return

try:
Expand Down
3 changes: 2 additions & 1 deletion tests/slack_sdk/scim/mock_web_api_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ def _handle(self):
self.send_response(429)
self.send_header("retry-after", 1)
self.set_common_headers()
self.wfile.write("""{"ok": false, "error": "ratelimited"}""".encode("utf-8"))
body = "{" if "malformed" in pattern else """{"ok": false, "error": "ratelimited"}"""
self.wfile.write(body.encode("utf-8"))
return
if "server_error" in pattern:
self.send_response(HTTPStatus.INTERNAL_SERVER_ERROR)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import unittest

from slack_sdk.audit_logs.async_client import AsyncAuditLogsClient
Expand All @@ -10,6 +11,7 @@
setup_mock_web_api_server_async,
)
from ..my_retry_handler import MyRetryHandler
from ..rate_limited_retry_handler import RateLimitedRetryHandler
from ..error_recording_retry_handler import ErrorRecordingRetryHandler, error_statuses


Expand Down Expand Up @@ -73,3 +75,30 @@ async def test_server_error_passes_the_status_error_to_handlers(self):

self.assertEqual([500], error_statuses(retry_handler.can_retry_errors))
self.assertEqual([500], error_statuses(retry_handler.prepare_errors))

@async_test
async def test_ratelimited_returns_the_last_response_when_retries_run_out(self):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 suggestion (non-blocking): Could we add a retried 429 with a malformed { body for audit logs and SCIM? Nothing pins why the response is built lazily, so a later eager build would re-run the retry handlers with a JSONDecodeError and no test would catch it.

retry_handler = RateLimitedRetryHandler(max_retry_count=100)
client = AsyncAuditLogsClient(
token="xoxp-ratelimited",
base_url="http://localhost:8888/",
retry_handlers=[retry_handler],
)

response = await client.actions()

self.assertEqual(429, response.status_code)
self.assertEqual(100, retry_handler.retry_count)

@async_test
async def test_ratelimited_retries_a_malformed_body_without_parsing_it(self):
client = AsyncAuditLogsClient(
token="xoxp-ratelimited_malformed",
base_url="http://localhost:8888/",
retry_handlers=[RateLimitedRetryHandler(max_retry_count=2)],
)

with self.assertRaises(json.JSONDecodeError):
await client.actions()

await assert_received_request_count_async(self, "/actions", 3)
34 changes: 34 additions & 0 deletions tests/slack_sdk_async/rate_limited_retry_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import Optional

from slack_sdk.http_retry.async_handler import AsyncRetryHandler
from slack_sdk.http_retry.builtin_interval_calculators import FixedValueRetryIntervalCalculator
from slack_sdk.http_retry.request import HttpRequest
from slack_sdk.http_retry.response import HttpResponse
from slack_sdk.http_retry.state import RetryState


class RateLimitedRetryHandler(AsyncRetryHandler):
def __init__(self, max_retry_count: int):
super().__init__(max_retry_count, FixedValueRetryIntervalCalculator(0))
self.retry_count = 0

async def _can_retry_async(
self,
*,
state: RetryState,
request: HttpRequest,
response: Optional[HttpResponse] = None,
error: Optional[Exception] = None,
) -> bool:
return response is not None and response.status_code == 429

async def prepare_for_next_attempt_async(
self,
*,
state: RetryState,
request: HttpRequest,
response: Optional[HttpResponse] = None,
error: Optional[Exception] = None,
) -> None:
self.retry_count += 1
await super().prepare_for_next_attempt_async(state=state, request=request, response=response, error=error)
29 changes: 29 additions & 0 deletions tests/slack_sdk_async/scim/test_async_client_http_retry.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import unittest

from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler, AsyncServerErrorRetryHandler
Expand All @@ -10,6 +11,7 @@
setup_mock_web_api_server_async,
)
from ..my_retry_handler import MyRetryHandler
from ..rate_limited_retry_handler import RateLimitedRetryHandler
from ..error_recording_retry_handler import ErrorRecordingRetryHandler, error_statuses


Expand Down Expand Up @@ -74,3 +76,30 @@ async def test_server_error_passes_the_status_error_to_handlers(self):

self.assertEqual([500], error_statuses(retry_handler.can_retry_errors))
self.assertEqual([500], error_statuses(retry_handler.prepare_errors))

@async_test
async def test_ratelimited_returns_the_last_response_when_retries_run_out(self):
retry_handler = RateLimitedRetryHandler(max_retry_count=100)
client = AsyncSCIMClient(
base_url="http://localhost:8888/",
token="xoxp-ratelimited",
retry_handlers=[retry_handler],
)

response = await client.search_users(start_index=0, count=1)

self.assertEqual(429, response.status_code)
self.assertEqual(100, retry_handler.retry_count)

@async_test
async def test_ratelimited_retries_a_malformed_body_without_parsing_it(self):
client = AsyncSCIMClient(
base_url="http://localhost:8888/",
token="xoxp-ratelimited_malformed",
retry_handlers=[RateLimitedRetryHandler(max_retry_count=2)],
)

with self.assertRaises(json.JSONDecodeError):
await client.api_call(http_verb="GET", path="Users")

await assert_received_request_count_async(self, "/Users", 3)
17 changes: 17 additions & 0 deletions tests/slack_sdk_async/web/test_async_web_client_http_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async
from ..fatal_error_retry_handler import FatalErrorRetryHandler
from ..my_retry_handler import MyRetryHandler
from ..rate_limited_retry_handler import RateLimitedRetryHandler
from ..error_recording_retry_handler import ErrorRecordingRetryHandler, error_statuses


Expand Down Expand Up @@ -164,3 +165,19 @@ async def test_ratelimited_retry_is_logged_at_info(self):
f"INFO:{parent.name}.client:Going to retry the same request: POST http://localhost:8888/auth.test",
],
)

@async_test
async def test_ratelimited_returns_the_last_response_when_retries_run_out(self):
retry_handler = RateLimitedRetryHandler(max_retry_count=100)
client = AsyncWebClient(
base_url="http://localhost:8888",
token="xoxb-ratelimited",
team_id="T111",
retry_handlers=[retry_handler],
)

with self.assertRaises(err.SlackApiError) as context:
await client.auth_test()

self.assertEqual(429, context.exception.response.status_code)
self.assertEqual(100, retry_handler.retry_count)
14 changes: 14 additions & 0 deletions tests/slack_sdk_async/webhook/test_async_webhook_http_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
setup_mock_web_api_server_async,
)
from ..my_retry_handler import MyRetryHandler
from ..rate_limited_retry_handler import RateLimitedRetryHandler
from ..error_recording_retry_handler import ErrorRecordingRetryHandler, error_statuses


Expand Down Expand Up @@ -68,3 +69,16 @@ async def test_server_error_passes_the_status_error_to_handlers(self):

self.assertEqual([500], error_statuses(retry_handler.can_retry_errors))
self.assertEqual([500], error_statuses(retry_handler.prepare_errors))

@async_test
async def test_ratelimited_returns_the_last_response_when_retries_run_out(self):
retry_handler = RateLimitedRetryHandler(max_retry_count=100)
client = AsyncWebhookClient(
"http://localhost:8888/ratelimited",
retry_handlers=[retry_handler],
)

response = await client.send(text="hello!")

self.assertEqual(429, response.status_code)
self.assertEqual(100, retry_handler.retry_count)
Loading