Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: use dedicated threadpool for hashing (#2098)

NTFSvolume20b158314a02
diff --git a/cyberdrop_dl/commands/hash.py b/cyberdrop_dl/commands/hash.py
index 54fe16a8f..365f61efb 100644
--- a/cyberdrop_dl/commands/hash.py
+++ b/cyberdrop_dl/commands/hash.py
@@ -24,9 +24,9 @@ async def compute_hashes(
db_file = cli.database_file if cli else None
extra_hashes = _choose_hash_algos(hashes, cli)
database = Database(db_file or AppData.default().db_file)
- hasher = Hasher(extra_hashes, database, folder) # pyright: ignore[reportArgumentType]
- hash_stats = await hash_directory(hasher)
- stats.print(hash_stats)
+ with Hasher(extra_hashes, database, folder) as hasher: # pyright: ignore[reportArgumentType]
+ hash_stats = await hash_directory(hasher)
+ stats.print(hash_stats)
def _choose_hash_algos(
diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.py
index bf1cbd371..9aad102d5 100644
--- a/cyberdrop_dl/hasher.py
+++ b/cyberdrop_dl/hasher.py
@@ -1,12 +1,13 @@
from __future__ import annotations
import asyncio
-import dataclasses
import hashlib
import logging
from collections import defaultdict
+from concurrent.futures import ThreadPoolExecutor
+from enum import StrEnum
from pathlib import Path
-from typing import TYPE_CHECKING, Final, Literal, Self
+from typing import TYPE_CHECKING, Final, Literal, Self, final
import xxhash
@@ -14,6 +15,7 @@ from cyberdrop_dl import aio
from cyberdrop_dl.constants import TempExt
from cyberdrop_dl.progress.hashing import HashingStats, HashingUI
from cyberdrop_dl.progress.scraping import show_msg
+from cyberdrop_dl.signature import simple_repr
if TYPE_CHECKING:
from collections.abc import Iterable
@@ -22,20 +24,27 @@ if TYPE_CHECKING:
from cyberdrop_dl.database._db import Database
from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem
+logger = logging.getLogger(__name__)
+
FileHashes = dict[str, dict[int, set[Path]]]
+
+class HashAlgo(StrEnum):
+ MD5 = "md5"
+ XXH128 = "xxh128"
+ SHA256 = "sha256"
+
+
_HASHERS: Final = {
- "md5": hashlib.md5,
- "xxh128": xxhash.xxh128,
- "sha256": hashlib.sha256,
+ HashAlgo.MD5: hashlib.md5,
+ HashAlgo.XXH128: xxhash.xxh128,
+ HashAlgo.SHA256: hashlib.sha256,
}
_CHUNK_SIZE: Final = 1024 * 1024 # 1MB
+_CONCURRENCY: Final = 10
-logger = logging.getLogger(__name__)
-
-
-def _compute_hash(file: Path, algorithm: Literal["xxh128", "md5", "sha256"]) -> str:
+def _compute_hash(file: Path, algorithm: HashAlgo) -> str:
with file.open("rb") as fp:
hasher = _HASHERS[algorithm]()
buffer = bytearray(_CHUNK_SIZE)
@@ -59,32 +68,29 @@ async def hash_directory(hasher: Hasher) -> HashingStats:
return hasher.stats
[email protected](slots=True)
+@final
class Hasher:
- extra_hashes: tuple[Literal["md5", "sha256"], ...]
- database: Database
- path: Path
- tui: HashingUI = dataclasses.field(init=False, repr=False)
-
- _cwd: Path = dataclasses.field(init=False, default_factory=Path.cwd)
- _hashes_map: FileHashes = dataclasses.field(
- init=False,
- repr=False,
- default_factory=lambda: defaultdict(lambda: defaultdict(set)),
- )
- _sem: asyncio.BoundedSemaphore = dataclasses.field(
- init=False,
- repr=False,
- default_factory=lambda: asyncio.BoundedSemaphore(20),
- )
- _hashed_items: set[tuple[str, ...]] = dataclasses.field(
- init=False,
- repr=False,
- default_factory=set,
- )
-
- def __post_init__(self) -> None:
- self.tui = HashingUI(self.path)
+ def __init__(self, hashes: Iterable[Literal["md5", "sha256", "xxh128"]], database: Database, path: Path) -> None:
+ self.path = path
+ self.hashes: tuple[HashAlgo, ...] = tuple(sorted(set(map(HashAlgo, hashes)) | {HashAlgo.XXH128}))
+ self.database = database
+ self.tui = HashingUI(path)
+ self._cwd = Path.cwd().resolve()
+ self._hashes_map: FileHashes = defaultdict(lambda: defaultdict(set))
+ self._sem = asyncio.BoundedSemaphore(_CONCURRENCY)
+ self._hashed_items: set[tuple[str, ...]] = set()
+ self._pool: ThreadPoolExecutor = ThreadPoolExecutor(
+ max_workers=_CONCURRENCY * len(self.hashes),
+ thread_name_prefix="hashing",
+ )
+
+ __repr__ = simple_repr("path", "hashes", "database")
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(self, *_) -> None:
+ self._pool.shutdown(wait=True)
@classmethod
def create(cls, config: Config, db: Database, path: Path | None = None) -> Self:
@@ -100,7 +106,12 @@ class Hasher:
async def hash_file(self, filename: Path | str, hash_type: Literal["xxh128", "md5", "sha256"]) -> str:
file_path = self._cwd / filename
- return await asyncio.to_thread(_compute_hash, file_path, hash_type)
+ return await asyncio.get_running_loop().run_in_executor(
+ self._pool,
+ _compute_hash,
+ file_path,
+ HashAlgo(hash_type),
+ )
async def hash_item(self, media_item: MediaItem) -> None:
if media_item.is_segment:
@@ -129,29 +140,26 @@ class Hasher:
except IsADirectoryError:
return None
- hashes: dict[str, asyncio.Task[str | None]] = {}
-
- def compute_hash(algo: Literal["xxh128", "md5", "sha256"]) -> asyncio.Task[str | None]:
- hashes[algo] = task = tg.create_task(
- self._update_db_and_retrive_hash(file, original_filename, referer, algo)
- )
- return task
-
async with self._sem:
with self.tui.new_file(file):
async with asyncio.TaskGroup() as tg:
logger.info("Computing hashes of '%s'", file)
- xxxhash = compute_hash("xxh128")
- for algo in self.extra_hashes:
- _ = compute_hash(algo)
-
- logger.debug(
- "hashes of '%s'\n%s",
- file,
- {algo: result for algo, task in hashes.items() if (result := task.result()) is not None},
- )
-
- return xxxhash.result()
+ task_map = {
+ algo: tg.create_task(
+ self._update_db_and_retrive_hash(
+ file,
+ original_filename,
+ referer,
+ algo, # pyright: ignore[reportArgumentType]
+ )
+ )
+ for algo in self.hashes
+ }
+
+ hashes = {algo: result for algo, task in task_map.items() if (result := task.result()) is not None}
+ logger.debug("hashes of '%s'\n%s", file, hashes)
+
+ return hashes.get(HashAlgo.XXH128)
async def _update_db_and_retrive_hash(
self,
diff --git a/cyberdrop_dl/manager.py b/cyberdrop_dl/manager.py
index 9c87bd708..747aa536a 100644
--- a/cyberdrop_dl/manager.py
+++ b/cyberdrop_dl/manager.py
@@ -61,13 +61,14 @@ class Manager:
self.database: Database
self.deduper: Czkawka
self.sorter: Sorter
+ self.exit_stack: contextlib.ExitStack = contextlib.ExitStack()
__repr__ = simple_repr("cli_args", "_config", "http_client", "download_client")
@property
def hasher(self) -> Hasher:
if self._hasher is None:
- self._hasher = Hasher.create(self.config, self.database)
+ self._hasher = self.exit_stack.enter_context(Hasher.create(self.config, self.database))
return self._hasher
@property
@@ -93,6 +94,7 @@ class Manager:
self.deduper = Czkawka.from_manager(self)
self.sorter = Sorter.from_config(self.config)
with (
+ self.exit_stack,
cache_context(self.appdata.cache_file, self.cache),
enter_context(REFRESH_RATE, self.config.ui.refresh_rate),
enter_context(TUI_DISABLED, self.config.ui.mode.is_disabled),
diff --git a/cyberdrop_dl/program_ui.py b/cyberdrop_dl/program_ui.py
index 573b1fc20..fd906a6b9 100644
--- a/cyberdrop_dl/program_ui.py
+++ b/cyberdrop_dl/program_ui.py
@@ -64,10 +64,10 @@ def run(manager: Manager, input_file: Path) -> RetrySource | Path:
def _scan_and_create_hashes(manager: Manager) -> None:
path = ask_dir("Select the directory to scan", default=manager.config.download_folder)
- hasher = Hasher.create(manager.config, manager.database, path)
- hash_stats = aio.run(hash_directory(hasher))
- stats.print(hash_stats)
- enter_to_continue()
+ with Hasher.create(manager.config, manager.database, path) as hasher:
+ hash_stats = aio.run(hash_directory(hasher))
+ stats.print(hash_stats)
+ enter_to_continue()
def _sort_files(manager: Manager) -> None:
diff --git a/tests/next_js/test_next_js.py b/tests/next_js/test_next_js.py
index 62c86b00d..2a6f36c25 100644
--- a/tests/next_js/test_next_js.py
+++ b/tests/next_js/test_next_js.py
@@ -55,12 +55,14 @@ def test_parse() -> None:
assert value != next_js._Magic.ERROR
[email protected](reason="IP blocked in CI")
def test_next_js_parser(next_data: next_js.NextJSFlight) -> None:
assert isinstance(next_data, dict)
assert next_data["1"] == "Sreact.fragment"
assert len(next_data) > 10
[email protected](reason="IP blocked in CI")
def test_next_js_find(next_data: next_js.NextJSFlight) -> None:
episode_keys = "slug", "title", "playlistGroups"
ep = next_js.find(next_data, *episode_keys)
diff --git a/tests/test_hashing.py b/tests/test_hashing.py
index 8ec37f250..b6752d3ed 100644
--- a/tests/test_hashing.py
+++ b/tests/test_hashing.py
@@ -59,10 +59,12 @@ async def test_hash_directory_scanner(manager: Manager, expected_results: set[tu
manager.config.download_folder.mkdir(parents=True)
db_path = manager.appdata.db_file
- await hash_directory(Hasher.create(manager.config, manager.database))
+ with Hasher.create(manager.config, manager.database) as hasher:
+ await hash_directory(hasher)
assert not get_hashes(db_path)
create_files(manager.config.download_folder, n_files)
- await hash_directory(Hasher.create(manager.config, manager.database))
+ with Hasher.create(manager.config, manager.database) as hasher:
+ await hash_directory(hasher)
results = get_hashes(db_path)
assert len(results) == len(expected_results)
assert results == expected_results
@@ -79,7 +81,8 @@ async def test_hash_directory_does_not_crash_with_subfolders(tmp_cwd: Path, mana
for file in files:
file.parent.mkdir(parents=True, exist_ok=True)
file.touch()
- await hash_directory(Hasher.create(manager.config, manager.database, hash_folder))
+ with Hasher.create(manager.config, manager.database, hash_folder) as hasher:
+ await hash_directory(hasher)
@pytest.mark.parametrize(