Skip to content
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

Rate limit API requests #214

Merged
merged 4 commits into from
Nov 14, 2022
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
13 changes: 10 additions & 3 deletions custom_components/candy/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@
import backoff
from aiohttp import ClientSession

from aiolimiter import AsyncLimiter

from .decryption import decrypt, Encryption, find_key
from .model import WashingMachineStatus, TumbleDryerStatus, DishwasherStatus, OvenStatus

_LOGGER = logging.getLogger(__name__)

# Some devices reportedly can't handle too frequent requests and respond with BAD_REQUEST
# This global limiter makes sure we don't call the API too fast
# https://github.com/ofalvai/home-assistant-candy/issues/61
_LIMITER = AsyncLimiter(max_rate=1, time_period=3)


class CandyClient:

Expand All @@ -28,7 +35,7 @@ async def status_with_retry(self) -> Union[WashingMachineStatus, TumbleDryerStat

async def status(self) -> Union[WashingMachineStatus, TumbleDryerStatus, DishwasherStatus, OvenStatus]:
url = _status_url(self.device_ip, self.use_encryption)
async with self.session.get(url) as resp:
async with _LIMITER, self.session.get(url) as resp:
if self.use_encryption:
resp_hex = await resp.text() # Response is hex encoded, either encrypted or not
if self.encryption_key != "":
Expand Down Expand Up @@ -61,7 +68,7 @@ async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> (
try:
_LOGGER.info("Trying to get a response without encryption (encrypted=0)...")
url = _status_url(device_ip, use_encryption=False)
async with session.get(url) as resp:
async with _LIMITER, session.get(url) as resp:
resp_json = await resp.json(content_type="text/html")
assert resp_json.get("response") != "BAD REQUEST"
_LOGGER.info("Received unencrypted JSON response, no need to use key for decryption")
Expand All @@ -70,7 +77,7 @@ async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> (
_LOGGER.debug(e)
_LOGGER.info("Failed to get a valid response without encryption, let's try with encrypted=1...")
url = _status_url(device_ip, use_encryption=True)
async with session.get(url) as resp:
async with _LIMITER, session.get(url) as resp:
resp_hex = await resp.text() # Response is hex encoded encrypted data
try:
json.loads(bytes.fromhex(resp_hex))
Expand Down
3 changes: 2 additions & 1 deletion custom_components/candy/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"documentation": "https://github.com/ofalvai/home-assistant-candy",
"issue_tracker": "https://github.com/ofalvai/home-assistant-candy/issues",
"requirements": [
"backoff>=2.0"
"backoff~=2.0",
"aiolimiter~=1.0"
],
"ssdp": [],
"zeroconf": [],
Expand Down
3 changes: 2 additions & 1 deletion requirements_test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ pytest~=7.1
pytest-homeassistant-custom-component==0.12.18

# Component dependencies
backoff==2.2.1
backoff~=2.0
aiolimiter~=1.0
6 changes: 6 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# See here for more info: https://docs.pytest.org/en/latest/fixture.html (note that
# pytest includes fixtures OOB which you can use as defined on this page)
from unittest.mock import patch
from aiolimiter import AsyncLimiter

import pytest

Expand All @@ -38,3 +39,8 @@ def skip_notifications_fixture():
"homeassistant.components.persistent_notification.async_dismiss"
):
yield

@pytest.fixture(name="disable_api_rate_limiter", autouse=True)
def disable_api_rate_limiter():
with patch("custom_components.candy.client._LIMITER"):
yield AsyncLimiter(max_rate=1000, time_period=1)