Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# network_manager.py
import asyncio
from contextlib import asynccontextmanager
from logging import getLogger
from typing import Callable, Awaitable, Optional, AsyncIterator, Any
import httpx
from aiolimiter import AsyncLimiter
from httpx import AsyncClient
from configs.misc_config import HEADERS
ProgressCB = Callable[[float], Awaitable[None] | None]
logger_local = getLogger(__name__)
class NetworkManager:
# ---------- 初期化 ----------
def __init__(
self,
rate_limiter: AsyncLimiter | None = None,
byte_limiter: AsyncLimiter | None = None,
) -> None:
self.rate_limiter = rate_limiter or AsyncLimiter(max_rate=4, time_period=1)
self.byte_limiter = byte_limiter or AsyncLimiter(max_rate=3 * 1024 * 1024, time_period=1)
self._client: Optional[AsyncClient] = None # 実体
self._ready = asyncio.Event() # 生成完了通知
self._creating_lock = asyncio.Lock() # 生成は 1 並列だけ
# すぐに生成を開始(でも待たない)
asyncio.create_task(self._spawn_client())
logger_local.info("NetworkManager created (client spawning in background)")
# ---------- AsyncClient 生成 ----------
@staticmethod
def _make_default_client_sync() -> AsyncClient:
"""ブロッキング作業なので sync 関数で定義"""
return httpx.AsyncClient(http2=True, timeout=60.0, headers=HEADERS)
async def _spawn_client(self) -> None:
"""別タスクで呼ばれる。完了したら Event を set。"""
async with self._creating_lock:
if self._client is not None: # すでに誰かが作った
return
self._client = await asyncio.to_thread(
self._make_default_client_sync
)
self._ready.set()
logger_local.info("AsyncClient ready")
async def _ensure_client(self) -> AsyncClient:
"""呼び出し側が必ず最初に叩く"""
if not self._ready.is_set():
await self._ready.wait()
return self._client # type: ignore[return-value]
# ---------- 手動クローズ ----------
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()
logger_local.info("NetworkManager closed")
self._client = None
# 以後呼ばれたら再生成できるよう初期化をリセット
self._ready.clear()
asyncio.get_running_loop().create_task(self._spawn_client())
# ---------- 低レベル GET API ----------
@asynccontextmanager
async def get(
self,
url: str,
params: Optional[dict[str, Any]] = None,
rate_limiter: Optional[AsyncLimiter] = None,
**kwargs,
) -> AsyncIterator[httpx.Response]:
"""
レート制限付き GET
kwargs に stream=True を渡すと .stream() を使用
"""
client = await self._ensure_client() # ← ここで待機する可能性あり
_rate_limiter = rate_limiter or self.rate_limiter
stream = kwargs.pop("stream", False)
async with _rate_limiter:
if stream:
resp_cm = client.stream("GET", url, params=params,
follow_redirects=True, **kwargs)
response = await resp_cm.__aenter__()
else:
response = await client.get(url, params=params,
follow_redirects=True, **kwargs)
response.raise_for_status()
try:
yield response
finally:
await response.aclose()
# download_service.py
import asyncio
import inspect
import os
from pathlib import Path
from typing import Optional
import aiofiles
from aiolimiter import AsyncLimiter
from configs.path_config import CACHE_DIR
from debug.timer import timer
from network_manager import NetworkManager, ProgressCB
class DownloadService:
def __init__(
self,
net: NetworkManager,
rate_limiter: Optional[AsyncLimiter] = None,
byte_limiter: Optional[AsyncLimiter] = None,
):
self.net = net
self.rate_limiter = rate_limiter or net.rate_limiter
self.byte_limiter = byte_limiter or net.byte_limiter
async def fetch(self, url: str, **kwargs):
async with self.net.get(url, rate_limiter=self.rate_limiter, stream=True, **kwargs) as resp:
return await resp.aread() # 読み切って bytes を返す例
def fetch_sync(self, url: str):
pass
async def save(
self,
url: str,
save_dir: Path,
overwrite: bool = False,
return_cache: bool = True,
*,
on_progress: ProgressCB | None = None,
chunk_size: int = 64 * 1024,
) -> Path:
save_dir.mkdir(parents=True, exist_ok=True)
filename = Path(url).name or "download.bin"
dest = save_dir / filename
tmp = save_dir / f"{filename}.tmp"
# 既存ファイルの扱い
if dest.exists() and not overwrite:
if return_cache:
return dest
raise FileExistsError(f"File already exists: {dest}")
try:
async with self.net.get(url, stream=True) as resp:
total = int(resp.headers.get("content-length", 0))
downloaded = 0
# 途中で落ちた残骸を消してから開始
tmp.unlink(missing_ok=True)
async with aiofiles.open(tmp, "wb") as fp:
async for chunk in resp.aiter_bytes(chunk_size):
await self.byte_limiter.acquire(len(chunk))
await fp.write(chunk)
downloaded += len(chunk)
if on_progress and total:
if inspect.isawaitable(r := on_progress(downloaded / total)):
await r
# 100% 通知
if on_progress and total:
if inspect.isawaitable(r := on_progress(1.0)):
await r
os.replace(tmp, dest) # 完了 → atomic rename
return dest
except BaseException: # Ctrl-C, CancelledError など含めて全捕捉
tmp.unlink(missing_ok=True) # 失敗や割り込み時は残骸を掃除
raise # もとの例外を再送出
async def main():
net = NetworkManager()
d_serv = DownloadService(net=net)
with timer(prefix="download: "):
result = await d_serv.save(
url=r"https://www3.nhk.or.jp/news/html/20250618/K10014838111_2506181222_0618123632_01_02.jpg",
save_dir=CACHE_DIR, overwrite=True)
print(f"result: {result}")
await net.close()
if __name__ == "__main__":
asyncio.run(main())
クリーンアーキテクチャに則って再設計して。リングごとにフォルダを分け、更に抽象と実装で分けて。
リクエストに基づいて、クリーンアーキテクチャに則った再設計を行います。クリーンアーキテクチャでは、依存関係が内側(ドメイン)から外側(インフラ)に向かうように設計し、各レイヤーを明確に分離します。
以下のようなフォルダ構造で再設計します:
src/
├── domain/ # エンティティ、ユースケース(内側のリング)
│ ├── entities/ # ビジネスエンティティ
│ └── usecases/ # ビジネスロジック
├── application/ # アプリケーションサービス(中間リング)
│ ├── interfaces/ # 抽象インターフェース
│ └── services/ # アプリケーションサービス実装
├── infrastructure/ # 外部サービス、フレームワーク(外側のリング)
│ ├── interfaces/ # インフラ層の抽象インターフェース
│ └── implementations/ # 具体的な実装
└── presentation/ # UI、コントローラー(最も外側のリング)
├── cli/ # コマンドラインインターフェース
└── api/ # APIエンドポイント
それでは、各ファイルの実装を示します:
src/domain/entities/download_entity.py
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@dataclass
class DownloadRequest:
url: str
save_dir: Path
overwrite: bool = False
return_cache: bool = True
chunk_size: int = 64 * 1024
@dataclass
class DownloadResult:
file_path: Path
total_bytes: int
success: bool
error: Optional[Exception] = None
src/domain/usecases/download_usecase.py
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Callable, Awaitable, Optional, Protocol
from domain.entities.download_entity import DownloadRequest, DownloadResult
class ProgressCallback(Protocol):
def __call__(self, progress: float) -> Awaitable[None] | None: ...
class DownloadUseCase(ABC):
@abstractmethod
async def download_file(
self,
request: DownloadRequest,
on_progress: Optional[ProgressCallback] = None
) -> DownloadResult:
"""ファイルをダウンロードして保存する"""
pass
@abstractmethod
async def fetch_content(self, url: str) -> bytes:
"""URLからコンテンツを取得する"""
pass
src/application/interfaces/network_gateway.py
from abc import ABC, abstractmethod
from typing import AsyncIterator, Any, Optional, Dict
from application.interfaces.rate_limiter import RateLimiter
class Response(ABC):
@abstractmethod
async def aread(self) -> bytes:
"""レスポンスの内容を全て読み込む"""
pass
@abstractmethod
async def aiter_bytes(self, chunk_size: int) -> AsyncIterator[bytes]:
"""レスポンスの内容をチャンク単位で読み込む"""
pass
@abstractmethod
async def aclose(self) -> None:
"""レスポンスをクローズする"""
pass
@property
@abstractmethod
def headers(self) -> Dict[str, str]:
"""レスポンスヘッダーを取得する"""
pass
@abstractmethod
def raise_for_status(self) -> None:
"""エラーステータスの場合に例外を発生させる"""
pass
class NetworkGateway(ABC):
@abstractmethod
async def get(
self,
url: str,
params: Optional[Dict[str, Any]] = None,
rate_limiter: Optional[RateLimiter] = None,
stream: bool = False,
**kwargs
) -> Response:
"""HTTPリクエストを実行する"""
pass
@abstractmethod
async def close(self) -> None:
"""ネットワークリソースを解放する"""
pass
src/application/interfaces/file_gateway.py
from abc import ABC, abstractmethod
from pathlib import Path
from typing import AsyncIterator
class FileGateway(ABC):
@abstractmethod
async def open_for_write(self, path: Path) -> AsyncIterator:
"""ファイルを書き込みモードで開く"""
pass
@abstractmethod
def ensure_directory(self, directory: Path) -> None:
"""ディレクトリが存在することを確認し、必要なら作成する"""
pass
@abstractmethod
def delete_file(self, path: Path) -> None:
"""ファイルを削除する"""
pass
@abstractmethod
def rename_file(self, source: Path, destination: Path) -> None:
"""ファイルをリネームする"""
pass
@abstractmethod
def file_exists(self, path: Path) -> bool:
"""ファイルが存在するかチェックする"""
pass
src/application/interfaces/rate_limiter.py
from abc import ABC, abstractmethod
class RateLimiter(ABC):
@abstractmethod
async def acquire(self, amount: int = 1) -> None:
"""リソースを取得する"""
pass
@abstractmethod
async def __aenter__(self) -> None:
"""コンテキストマネージャーとして使用する場合のエントリーポイント"""
pass
@abstractmethod
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
"""コンテキストマネージャーとして使用する場合の終了処理"""
pass
src/application/services/download_service.py
import inspect
from pathlib import Path
from typing import Optional
from domain.entities.download_entity import DownloadRequest, DownloadResult
from domain.usecases.download_usecase import DownloadUseCase, ProgressCallback
from application.interfaces.network_gateway import NetworkGateway
from application.interfaces.file_gateway import FileGateway
from application.interfaces.rate_limiter import RateLimiter
class DownloadService(DownloadUseCase):
def __init__(
self,
network_gateway: NetworkGateway,
file_gateway: FileGateway,
request_rate_limiter: RateLimiter,
byte_rate_limiter: RateLimiter,
):
self.network_gateway = network_gateway
self.file_gateway = file_gateway
self.request_rate_limiter = request_rate_limiter
self.byte_rate_limiter = byte_rate_limiter
async def fetch_content(self, url: str) -> bytes:
response = await self.network_gateway.get(
url,
rate_limiter=self.request_rate_limiter,
stream=True
)
try:
return await response.aread()
finally:
await response.aclose()
async def download_file(
self,
request: DownloadRequest,
on_progress: Optional[ProgressCallback] = None
) -> DownloadResult:
self.file_gateway.ensure_directory(request.save_dir)
filename = Path(request.url).name or "download.bin"
dest = request.save_dir / filename
tmp = request.save_dir / f"{filename}.tmp"
# 既存ファイルの扱い
if self.file_gateway.file_exists(dest) and not request.overwrite:
if request.return_cache:
return DownloadResult(file_path=dest, total_bytes=0, success=True)
raise FileExistsError(f"File already exists: {dest}")
total_bytes = 0
try:
response = await self.network_gateway.get(
request.url,
rate_limiter=self.request_rate_limiter,
stream=True
)
try:
response.raise_for_status()
total = int(response.headers.get("content-length", 0))
downloaded = 0
# 途中で落ちた残骸を消してから開始
self.file_gateway.delete_file(tmp)
async with self.file_gateway.open_for_write(tmp) as fp:
async for chunk in response.aiter_bytes(request.chunk_size):
await self.byte_rate_limiter.acquire(len(chunk))
await fp.write(chunk)
downloaded += len(chunk)
if on_progress and total:
if inspect.isawaitable(r := on_progress(downloaded / total)):
await r
# 100% 通知
if on_progress and total:
if inspect.isawaitable(r := on_progress(1.0)):
await r
self.file_gateway.rename_file(tmp, dest) # 完了 → atomic rename
return DownloadResult(file_path=dest, total_bytes=downloaded, success=True)
finally:
await response.aclose()
except Exception as e:
self.file_gateway.delete_file(tmp) # 失敗や割り込み時は残骸を掃除
return DownloadResult(file_path=dest, total_bytes=total_bytes, success=False, error=e)
src/infrastructure/interfaces/http_client.py
from abc import ABC, abstractmethod
from typing import AsyncIterator, Dict, Any, Optional
class HttpClient(ABC):
@abstractmethod
async def get(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
"""同期的なGETリクエスト"""
pass
@abstractmethod
async def stream(self, method: str, url: str, **kwargs) -> AsyncIterator:
"""ストリーミングリクエスト"""
pass
@abstractmethod
async def aclose(self) -> None:
"""クライアントをクローズする"""
pass
src/infrastructure/implementations/httpx_adapter.py
import asyncio
from contextlib import asynccontextmanager
from logging import getLogger
from typing import Dict, Any, Optional, AsyncIterator
import httpx
from httpx import AsyncClient
from application.interfaces.network_gateway import NetworkGateway, Response
from application.interfaces.rate_limiter import RateLimiter
from infrastructure.interfaces.http_client import HttpClient
logger = getLogger(__name__)
class HttpxResponse(Response):
def __init__(self, response: httpx.Response):
self._response = response
async def aread(self) -> bytes:
return await self._response.aread()
async def aiter_bytes(self, chunk_size: int) -> AsyncIterator[bytes]:
async for chunk in self._response.aiter_bytes(chunk_size):
yield chunk
async def aclose(self) -> None:
await self._response.aclose()
@property
def headers(self) -> Dict[str, str]:
return dict(self._response.headers)
def raise_for_status(self) -> None:
self._response.raise_for_status()
class HttpxClient(HttpClient):
def __init__(self, http2: bool = True, timeout: float = 60.0, headers: Optional[Dict[str, str]] = None):
self.http2 = http2
self.timeout = timeout
self.headers = headers or {}
self._client = None
async def _ensure_client(self) -> AsyncClient:
if self._client is None:
self._client = httpx.AsyncClient(
http2=self.http2,
timeout=self.timeout,
headers=self.headers
)
return self._client
async def get(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs) -> httpx.Response:
client = await self._ensure_client()
return await client.get(url, params=params, follow_redirects=True, **kwargs)
async def stream(self, method: str, url: str, **kwargs) -> AsyncIterator:
client = await self._ensure_client()
return client.stream(method, url, follow_redirects=True, **kwargs)
async def aclose(self) -> None:
if self._client is not None:
await self._client.aclose()
self._client = None
class HttpxNetworkGateway(NetworkGateway):
def __init__(self, http_client: HttpClient, default_headers: Optional[Dict[str, str]] = None):
self.http_client = http_client
self.default_headers = default_headers or {}
self._ready = asyncio.Event()
self._ready.set() # 初期状態では準備完了
@asynccontextmanager
async def get(
self,
url: str,
params: Optional[Dict[str, Any]] = None,
rate_limiter: Optional[RateLimiter] = None,
stream: bool = False,
**kwargs
) -> AsyncIterator[Response]:
if not self._ready.is_set():
await self._ready.wait()
headers = {**self.default_headers, **(kwargs.pop("headers", {}))}
if rate_limiter:
async with rate_limiter:
if stream:
resp_cm = await self.http_client.stream("GET", url, params=params, headers=headers, **kwargs)
response = await resp_cm.__aenter__()
else:
response = await self.http_client.get(url, params=params, headers=headers, **kwargs)
else:
if stream:
resp_cm = await self.http_client.stream("GET", url, params=params, headers=headers, **kwargs)
response = await resp_cm.__aenter__()
else:
response = await self.http_client.get(url, params=params, headers=headers, **kwargs)
wrapped_response = HttpxResponse(response)
try:
yield wrapped_response
finally:
await wrapped_response.aclose()
async def close(self) -> None:
self._ready.clear()
await self.http_client.aclose()
logger.info("HttpxNetworkGateway closed")
self._ready.set() # 再利用可能にする
src/infrastructure/implementations/aiofiles_adapter.py
import os
from pathlib import Path
from typing import AsyncIterator
import aiofiles
from application.interfaces.file_gateway import FileGateway
class AioFilesGateway(FileGateway):
async def open_for_write(self, path: Path) -> AsyncIterator:
return aiofiles.open(path, "wb")
def ensure_directory(self, directory: Path) -> None:
directory.mkdir(parents=True, exist_ok=True)
def delete_file(self, path: Path) -> None:
path.unlink(missing_ok=True)
def rename_file(self, source: Path, destination: Path) -> None:
os.replace(source, destination) # atomic rename
def file_exists(self, path: Path) -> bool: