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/
│ │ └── download.py
│ └── value_objects/
│ └── download_progress.py
│
├── application/ # ユースケース層
│ ├── interfaces/ # 抽象(ポート)
│ │ ├── repositories/
│ │ │ └── download_repository.py
│ │ └── services/
│ │ └── network_service.py
│ └── use_cases/
│ ├── download_file.py
│ └── fetch_content.py
│
├── infrastructure/ # インフラストラクチャ層
│ ├── network/
│ │ ├── http_client_adapter.py
│ │ └── rate_limiter.py
│ ├── repositories/
│ │ └── file_download_repository.py
│ └── services/
│ └── httpx_network_service.py
│
└── presentation/ # プレゼンテーション層
└── cli/
└── download_cli.py
domain/entities/download.py
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from datetime import datetime
@dataclass
class Download:
"""ダウンロードエンティティ"""
url: str
destination: Path
filename: str
size: Optional[int] = None
downloaded_bytes: int = 0
status: str = "pending" # pending, downloading, completed, failed
created_at: datetime = None
completed_at: Optional[datetime] = None
def __post_init__(self):
if self.created_at is None:
self.created_at = datetime.now()
@property
def progress(self) -> float:
if not self.size or self.size == 0:
return 0.0
return min(self.downloaded_bytes / self.size, 1.0)
@property
def is_completed(self) -> bool:
return self.status == "completed"
def mark_completed(self) -> None:
self.status = "completed"
self.completed_at = datetime.now()
domain/value_objects/download_progress.py
from dataclasses import dataclass
@dataclass(frozen=True)
class DownloadProgress:
"""ダウンロード進捗の値オブジェクト"""
total_bytes: int
downloaded_bytes: int
@property
def percentage(self) -> float:
if self.total_bytes == 0:
return 0.0
return (self.downloaded_bytes / self.total_bytes) * 100
@property
def is_complete(self) -> bool:
return self.downloaded_bytes >= self.total_bytes
application/interfaces/repositories/download_repository.py
from abc import ABC, abstractmethod
from pathlib import Path
from typing import AsyncIterator
from domain.entities.download import Download
class DownloadRepository(ABC):
"""ダウンロードリポジトリのインターフェース"""
@abstractmethod
async def save_to_file(
self,
download: Download,
data_stream: AsyncIterator[bytes],
chunk_size: int = 64 * 1024
) -> Path:
"""データストリームをファイルに保存"""
pass
@abstractmethod
async def file_exists(self, path: Path) -> bool:
"""ファイルの存在確認"""
pass
@abstractmethod
async def delete_file(self, path: Path) -> None:
"""ファイルの削除"""
pass
application/interfaces/services/network_service.py
from abc import ABC, abstractmethod
from typing import AsyncIterator, Optional, Dict, Any
class NetworkService(ABC):
"""ネットワークサービスのインターフェース"""
@abstractmethod
async def fetch_bytes(self, url: str, **kwargs) -> bytes:
"""URLからバイトデータを取得"""
pass
@abstractmethod
async def stream_bytes(
self,
url: str,
chunk_size: int = 64 * 1024,
**kwargs
) -> AsyncIterator[bytes]:
"""URLからバイトデータをストリーミング"""
pass
@abstractmethod
async def get_content_info(self, url: str) -> Dict[str, Any]:
"""コンテンツ情報(サイズなど)を取得"""
pass
application/use_cases/download_file.py
from pathlib import Path
from typing import Optional, Callable, Awaitable
import inspect
from domain.entities.download import Download
from domain.value_objects.download_progress import DownloadProgress
from application.interfaces.repositories.download_repository import DownloadRepository
from application.interfaces.services.network_service import NetworkService
ProgressCallback = Callable[[DownloadProgress], Optional[Awaitable[None]]]
class DownloadFileUseCase:
"""ファイルダウンロードのユースケース"""
def __init__(
self,
network_service: NetworkService,
download_repository: DownloadRepository
):
self.network_service = network_service
self.download_repository = download_repository
async def execute(
self,
url: str,
save_dir: Path,
filename: Optional[str] = None,
overwrite: bool = False,
on_progress: Optional[ProgressCallback] = None
) -> Download:
"""ファイルをダウンロードして保存"""
# ファイル名の決定
if not filename:
filename = Path(url).name or "download.bin"
destination = save_dir / filename
# 既存ファイルのチェック
if not overwrite and await self.download_repository.file_exists(destination):
raise FileExistsError(f"File already exists: {destination}")
# コンテンツ情報の取得
content_info = await self.network_service.get_content_info(url)
content_size = content_info.get("size", 0)
# ダウンロードエンティティの作成
download = Download(
url=url,
destination=destination,
filename=filename,
size=content_size,
status="downloading"
)
try:
# ストリーミングダウンロード
downloaded_bytes = 0
async def progress_stream():
nonlocal downloaded_bytes
async for chunk in self.network_service.stream_bytes(url):
yield chunk
downloaded_bytes += len(chunk)
download.downloaded_bytes = downloaded_bytes
if on_progress and content_size:
progress = DownloadProgress(
total_bytes=content_size,
downloaded_bytes=downloaded_bytes
)
callback_result = on_progress(progress)
if inspect.isawaitable(callback_result):
await callback_result
# ファイルに保存
saved_path = await self.download_repository.save_to_file(
download,
progress_stream()
)
download.mark_completed()
return download
except Exception as e:
download.status = "failed"
raise
application/use_cases/fetch_content.py
from application.interfaces.services.network_service import NetworkService
class FetchContentUseCase:
"""コンテンツ取得のユースケース"""
def __init__(self, network_service: NetworkService):
self.network_service = network_service
async def execute(self, url: str, **kwargs) -> bytes:
"""URLからコンテンツを取得"""
return await self.network_service.fetch_bytes(url, **kwargs)
infrastructure/network/http_client_adapter.py
import asyncio
from typing import Optional, AsyncIterator, Dict, Any
from contextlib import asynccontextmanager
import httpx
from httpx import AsyncClient
class HttpClientAdapter:
"""HTTPクライアントのアダプター"""
def __init__(self, headers: Optional[Dict[str, str]] = None):
self._client: Optional[AsyncClient] = None
self._ready = asyncio.Event()
self._creating_lock = asyncio.Lock()
self._headers = headers or {}
# バックグラウンドでクライアント生成
asyncio.create_task(self._spawn_client())
async def _spawn_client(self) -> None:
async with self._creating_lock:
if self._client is not None:
return
self._client = await asyncio.to_thread(
lambda: httpx.AsyncClient(
http2=True,
timeout=60.0,
headers=self._headers
)
)
self._ready.set()
async def _ensure_client(self) -> AsyncClient:
if not self._ready.is_set():
await self._ready.wait()
return self._client
@asynccontextmanager
async def get(self, url: str, **kwargs):
client = await self._ensure_client()
stream = kwargs.pop("stream", False)
if stream:
async with client.stream("GET", url, follow_redirects=True, **kwargs) as response:
response.raise_for_status()
yield response
else:
response = await client.get(url, follow_redirects=True, **kwargs)
response.raise_for_status()
try:
yield response
finally:
await response.aclose()
async def close(self) -> None:
if self._client:
await self._client.aclose()
self._client = None
self._ready.clear()
infrastructure/network/rate_limiter.py
from aiolimiter import AsyncLimiter
class RateLimiterFactory:
"""レート制限の生成"""
@staticmethod
def create_request_limiter(max_rate: int = 4, time_period: float = 1) -> AsyncLimiter:
return AsyncLimiter(max_rate=max_rate, time_period=time_period)
@staticmethod
def create_byte_limiter(max_bytes_per_second: int = 3 * 1024 * 1024) -> AsyncLimiter:
return AsyncLimiter(max_rate=max_bytes_per_second, time_period=1)
infrastructure/services/httpx_network_service.py
from typing import AsyncIterator, Dict, Any, Optional
from aiolimiter import AsyncLimiter
from application.interfaces.services.network_service import NetworkService
from infrastructure.network.http_client_adapter import HttpClientAdapter
from infrastructure.network.rate_limiter import RateLimiterFactory
class HttpxNetworkService(NetworkService):
"""HTTPXを使用したネットワークサービスの実装"""
def __init__(
self,
client_adapter: HttpClientAdapter,
request_limiter: Optional[AsyncLimiter] = None,
byte_limiter: Optional[AsyncLimiter] = None
):
self.client = client_adapter
self.request_limiter = request_limiter or RateLimiterFactory.create_request_limiter()
self.byte_limiter = byte_limiter or RateLimiterFactory.create_byte_limiter()
async def fetch_bytes(self, url: str, **kwargs) -> bytes:
async with self.request_limiter:
async with self.client.get(url, **kwargs) as response:
data = await response.aread()
await self.byte_limiter.acquire(len(data))
return data
async def stream_bytes(
self,
url: str,
chunk_size: int = 64 * 1024,
**kwargs
) -> AsyncIterator[bytes]:
async with self.request_limiter:
async with self.client.get(url, stream=True, **kwargs) as response:
async for chunk in response.aiter_bytes(chunk_size):
await self.byte_limiter.acquire(len(chunk))
yield chunk
async def get_content_info(self, url: str) -> Dict[str, Any]:
async with self.request_limiter:
async with self.client.get(url, stream=True) as response:
return {
"size": int(response.headers.get("content-length", 0)),
"content_type": response.headers.get("content-type", ""),
"status_code": response.status_code
}
infrastructure/repositories/file_download_repository.py
import os
from pathlib import Path
from typing import AsyncIterator
import aiofiles
from domain.entities.download import Download
from application.interfaces.repositories.download_repository import DownloadRepository
class FileDownloadRepository(DownloadRepository):
"""ファイルシステムへのダウンロード保存の実装"""
async def save_to_file(
self,
download: Download,
data_stream: AsyncIterator[bytes],
chunk_size: int = 64 * 1024
) -> Path:
save_dir = download.destination.parent
save_dir.mkdir(parents=True, exist_ok=True)
tmp_path = download.destination.with_suffix(download.destination.suffix + '.tmp')
try:
# 既存の一時ファイルを削除
if tmp_path.exists():
tmp_path.unlink()
# ストリームをファイルに書き込み
async with aiofiles.open(tmp_path, 'wb') as fp:
async for chunk in data_stream:
await fp.write(chunk)
# アトミックな移動
os.replace(tmp_path, download.destination)
return download.destination
except Exception:
# エラー時は一時ファイルを削除
if tmp_path.exists():
tmp_path.unlink()
raise
async def file_exists(self, path: Path) -> bool:
return path.exists()
async def delete_file(self, path: Path) -> None:
if path.exists():
path.unlink()
presentation/cli/download_cli.py
import asyncio
from pathlib import Path
from infrastructure.network.http_client_adapter import HttpClientAdapter
from infrastructure.services.httpx_network_service import HttpxNetworkService
from infrastructure.repositories.file_download_repository import FileDownloadRepository
from application.use_cases.download_file import DownloadFileUseCase
from domain.value_objects.download_progress import DownloadProgress
async def main():
# 依存性の注入
client_adapter = HttpClientAdapter(headers={"User-Agent": "DownloadApp/1.0"})
network_service = HttpxNetworkService