Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: simplify speed limiter

NTFSvolumecd81b1020cf7
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 3599968cb..c91604d2c 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -197,10 +197,11 @@ class DownloadClient:
media_item.partial_file.touch()
async with aiofiles.open(media_item.partial_file, mode="ab") as f: # type: ignore
async for chunk, _ in content.iter_chunks():
- await self.client_manager.check_bucket(chunk)
- await asyncio.sleep(0)
- await f.write(chunk)
- update_progress(len(chunk))
+ chunk_size = len(chunk)
+ async with self.client_manager.speed_limiter(chunk_size):
+ await asyncio.sleep(0)
+ await f.write(chunk)
+ update_progress(chunk_size)
if not content.total_bytes and not media_item.partial_file.stat().st_size:
media_item.partial_file.unlink()
raise DownloadError(status=HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index e8c7a1902..b2ba70085 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -16,7 +16,7 @@ from yarl import URL
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.clients.errors import DDOSGuardError, DownloadError, ScrapeError
from cyberdrop_dl.clients.scraper_client import ScraperClient
-from cyberdrop_dl.managers.leaky import LeakyBucket
+from cyberdrop_dl.managers.leaky import DownloadSpeedLimiter
from cyberdrop_dl.utils.constants import CustomHTTPStatus
from cyberdrop_dl.utils.logger import log
@@ -91,7 +91,7 @@ class ClientManager:
self.scraper_session = ScraperClient(self)
self.downloader_session = DownloadClient(manager, self)
- self._leaky_bucket = LeakyBucket(manager)
+ self.speed_limiter = DownloadSpeedLimiter(manager)
self.flaresolverr = Flaresolverr(self)
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
@@ -154,9 +154,6 @@ class ClientManager:
if headers.get("Content-Length") == "322509" and headers.get("Content-Type") == "video/mp4":
raise DownloadError(status="Bunkr Maintenance", message="Bunkr under maintenance")
- async def check_bucket(self, size: float) -> None:
- await self._leaky_bucket.acquire(size)
-
@staticmethod
def check_ddos_guard(soup: BeautifulSoup) -> bool:
if soup.title:
diff --git a/cyberdrop_dl/managers/leaky.py b/cyberdrop_dl/managers/leaky.py
index 38a323b35..714b0c9a4 100644
--- a/cyberdrop_dl/managers/leaky.py
+++ b/cyberdrop_dl/managers/leaky.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-import asyncio
-import contextlib
from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
@@ -10,52 +8,14 @@ if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
-class LeakyBucket(AsyncLimiter):
+class DownloadSpeedLimiter(AsyncLimiter):
def __init__(self, manager: Manager) -> None:
self.download_speed_limit = (
manager.config_manager.global_settings_data.rate_limiting_options.download_speed_limit
)
-
- self.max_amount = 1024 * 1024 * 10
super().__init__(self.download_speed_limit, 1)
async def acquire(self, amount: float = 1) -> None:
if self.download_speed_limit <= 0:
return
- if not isinstance(amount, int):
- amount = len(amount)
- loop = asyncio.get_running_loop()
- task = asyncio.current_task(loop)
- assert task is not None
- while not self.has_capacity(amount):
- # wait for the next drip to have left the bucket
- # add a future to the _waiters map to be notified
- # 'early' if capacity has come up
- fut = loop.create_future()
- self._waiters[task] = fut
- with contextlib.suppress(TimeoutError):
- await asyncio.wait_for(asyncio.shield(fut), 1 / self._rate_per_sec * amount)
- fut.cancel()
- self._waiters.pop(task, None)
- self._level += amount
-
- def has_capacity(self, amount: float = 1) -> bool:
- """Check if there is enough capacity remaining in the limiter.
-
- :param amount: How much capacity you need to be available.
-
- """
- self._leak()
- requested = self._level + amount
- # if there are tasks waiting for capacity, signal to the first
- # there there may be some now (they won't wake up until this task
- # yields with an await)
- if requested < self.max_rate:
- for fut in self._waiters.values():
- if not fut.done():
- fut.set_result(True)
- break
- # allows for one packet to be received until bucket empties
- if self._level > self.max_rate:
- return False
- return self._level + amount <= self.max_amount
+ await super().acquire(amount)