|
| 1 | +""" |
| 2 | +FileSizeEnrichmentRepository component for adding file size information to project pages. |
| 3 | +
|
| 4 | +This component wraps another repository and automatically enriches file metadata |
| 5 | +with size information by making HTTP HEAD requests to files that don't already |
| 6 | +have size information. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | +from dataclasses import replace |
| 11 | +import logging |
| 12 | +import typing |
| 13 | + |
| 14 | +import httpx |
| 15 | +from simple_repository import SimpleRepository, model |
| 16 | +from simple_repository.components.core import RepositoryContainer |
| 17 | + |
| 18 | +from ._typing_compat import override |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class FileSizeEnrichmentRepository(RepositoryContainer): |
| 24 | + """ |
| 25 | + Repository component that enriches file metadata with size information. |
| 26 | +
|
| 27 | + This component automatically adds size information to files that don't already |
| 28 | + have it by making HTTP HEAD requests. It maintains parallelism for efficiency |
| 29 | + while respecting concurrency limits. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + source: SimpleRepository, |
| 35 | + http_client: httpx.AsyncClient, |
| 36 | + *, |
| 37 | + max_concurrent_requests: int = 10, |
| 38 | + ) -> None: |
| 39 | + """ |
| 40 | + Initialize the FileSizeEnrichmentRepository. |
| 41 | +
|
| 42 | + Parameters |
| 43 | + ---------- |
| 44 | + source: The underlying repository to wrap |
| 45 | +
|
| 46 | + http_client: HTTP client for making HEAD requests |
| 47 | +
|
| 48 | + max_concurrent_requests: Maximum number of concurrent HEAD requests |
| 49 | + """ |
| 50 | + super().__init__(source) |
| 51 | + self.http_client = http_client |
| 52 | + self.semaphore = asyncio.Semaphore(max_concurrent_requests) |
| 53 | + |
| 54 | + @override |
| 55 | + async def get_project_page( |
| 56 | + self, |
| 57 | + project_name: str, |
| 58 | + *, |
| 59 | + request_context: model.RequestContext = model.RequestContext.DEFAULT, |
| 60 | + ) -> model.ProjectDetail: |
| 61 | + """ |
| 62 | + Get project page with file sizes enriched. |
| 63 | +
|
| 64 | + Files that don't have size information will have their sizes fetched |
| 65 | + via HTTP HEAD requests in parallel. |
| 66 | + """ |
| 67 | + project_page = await super().get_project_page( |
| 68 | + project_name, request_context=request_context |
| 69 | + ) |
| 70 | + |
| 71 | + # Identify files that need size information |
| 72 | + files_needing_size = [ |
| 73 | + file for file in project_page.files if not file.size and file.url |
| 74 | + ] |
| 75 | + |
| 76 | + if not files_needing_size: |
| 77 | + # No files need size information, return as-is |
| 78 | + return project_page |
| 79 | + |
| 80 | + # Fetch sizes for files that need them |
| 81 | + size_info = await self._fetch_file_sizes(files_needing_size) |
| 82 | + |
| 83 | + # Create new files with updated size information |
| 84 | + enriched_files = [] |
| 85 | + for file in project_page.files: |
| 86 | + if file.filename in size_info: |
| 87 | + file = replace(file, size=size_info[file.filename]) |
| 88 | + enriched_files.append(file) |
| 89 | + |
| 90 | + return replace(project_page, files=tuple(enriched_files)) |
| 91 | + |
| 92 | + async def _fetch_file_sizes( |
| 93 | + self, files: typing.List[model.File] |
| 94 | + ) -> typing.Dict[str, int]: |
| 95 | + """ |
| 96 | + Fetch file sizes for multiple files in parallel. |
| 97 | +
|
| 98 | + Args: |
| 99 | + files: List of files to fetch sizes for |
| 100 | +
|
| 101 | + Returns: |
| 102 | + Dictionary mapping filename to size in bytes |
| 103 | + """ |
| 104 | + |
| 105 | + async def fetch_single_file_size( |
| 106 | + file: model.File, |
| 107 | + ) -> typing.Tuple[str, typing.Optional[int]]: |
| 108 | + """Fetch size for a single file with semaphore protection.""" |
| 109 | + async with self.semaphore: |
| 110 | + try: |
| 111 | + logger.debug(f"Fetching size for {file.filename} from {file.url}") |
| 112 | + |
| 113 | + # Make HEAD request to get Content-Length |
| 114 | + response = await self.http_client.head( |
| 115 | + file.url, follow_redirects=True, headers={} |
| 116 | + ) |
| 117 | + response.raise_for_status() |
| 118 | + |
| 119 | + content_length = response.headers.get("Content-Length") |
| 120 | + if content_length: |
| 121 | + return file.filename, int(content_length) |
| 122 | + else: |
| 123 | + logger.warning(f"No Content-Length header for {file.filename}") |
| 124 | + return file.filename, None |
| 125 | + |
| 126 | + except BaseException as e: |
| 127 | + logger.warning(f"Failed to get size for {file.filename}: {e}") |
| 128 | + return file.filename, None |
| 129 | + |
| 130 | + # Create tasks for all files |
| 131 | + tasks = [fetch_single_file_size(file) for file in files] |
| 132 | + |
| 133 | + # Wait for all tasks to complete |
| 134 | + results = await asyncio.gather(*tasks, return_exceptions=True) |
| 135 | + |
| 136 | + # Process results, filtering out failures |
| 137 | + size_info = {} |
| 138 | + for result in results: |
| 139 | + if isinstance(result, BaseException): |
| 140 | + logger.warning(f"Exception occurred during size fetching: {result}") |
| 141 | + continue |
| 142 | + |
| 143 | + filename, size = result |
| 144 | + if size is not None: |
| 145 | + size_info[filename] = size |
| 146 | + |
| 147 | + return size_info |
0 commit comments