|
| 1 | +"""Lazy ZIP over HTTP""" |
| 2 | + |
| 3 | +__all__ = ['dist_from_wheel_url'] |
| 4 | + |
| 5 | +from bisect import bisect_left, bisect_right |
| 6 | +from contextlib import contextmanager |
| 7 | +from tempfile import NamedTemporaryFile |
| 8 | +from zipfile import BadZipfile, ZipFile |
| 9 | + |
| 10 | +from pip._vendor.requests.models import CONTENT_CHUNK_SIZE |
| 11 | +from pip._vendor.six.moves import range |
| 12 | + |
| 13 | +from pip._internal.network.utils import HEADERS, response_chunks |
| 14 | +from pip._internal.utils.typing import MYPY_CHECK_RUNNING |
| 15 | +from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel |
| 16 | + |
| 17 | +if MYPY_CHECK_RUNNING: |
| 18 | + from typing import Any, Dict, Iterator, List, Optional, Tuple |
| 19 | + |
| 20 | + from pip._vendor.pkg_resources import Distribution |
| 21 | + from pip._vendor.requests.models import Response |
| 22 | + |
| 23 | + from pip._internal.network.session import PipSession |
| 24 | + |
| 25 | + |
| 26 | +def dist_from_wheel_url(name, url, session): |
| 27 | + # type: (str, str, PipSession) -> Distribution |
| 28 | + """Return a pkg_resources.Distribution from the given wheel URL. |
| 29 | +
|
| 30 | + This uses HTTP range requests to only fetch the potion of the wheel |
| 31 | + containing metadata, just enough for the object to be constructed. |
| 32 | + If such requests are not supported, RuntimeError is raised. |
| 33 | + """ |
| 34 | + with LazyZipOverHTTP(url, session) as wheel: |
| 35 | + # For read-only ZIP files, ZipFile only needs methods read, |
| 36 | + # seek, seekable and tell, not the whole IO protocol. |
| 37 | + zip_file = ZipFile(wheel) # type: ignore |
| 38 | + # After context manager exit, wheel.name |
| 39 | + # is an invalid file by intention. |
| 40 | + return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name) |
| 41 | + |
| 42 | + |
| 43 | +class LazyZipOverHTTP(object): |
| 44 | + """File-like object mapped to a ZIP file over HTTP. |
| 45 | +
|
| 46 | + This uses HTTP range requests to lazily fetch the file's content, |
| 47 | + which is supposed to be fed to ZipFile. If such requests are not |
| 48 | + supported by the server, raise RuntimeError during initialization. |
| 49 | + """ |
| 50 | + |
| 51 | + def __init__(self, url, session, chunk_size=CONTENT_CHUNK_SIZE): |
| 52 | + # type: (str, PipSession, int) -> None |
| 53 | + head = session.head(url, headers=HEADERS) |
| 54 | + head.raise_for_status() |
| 55 | + assert head.status_code == 200 |
| 56 | + self._session, self._url, self._chunk_size = session, url, chunk_size |
| 57 | + self._length = int(head.headers['Content-Length']) |
| 58 | + self._file = NamedTemporaryFile() |
| 59 | + self.truncate(self._length) |
| 60 | + self._left = [] # type: List[int] |
| 61 | + self._right = [] # type: List[int] |
| 62 | + if 'bytes' not in head.headers.get('Accept-Ranges', 'none'): |
| 63 | + raise RuntimeError('range request is not supported') |
| 64 | + self._check_zip() |
| 65 | + |
| 66 | + @property |
| 67 | + def mode(self): |
| 68 | + # type: () -> str |
| 69 | + """Opening mode, which is always rb.""" |
| 70 | + return 'rb' |
| 71 | + |
| 72 | + @property |
| 73 | + def name(self): |
| 74 | + # type: () -> str |
| 75 | + """Path to the underlying file.""" |
| 76 | + return self._file.name |
| 77 | + |
| 78 | + def seekable(self): |
| 79 | + # type: () -> bool |
| 80 | + """Return whether random access is supported, which is True.""" |
| 81 | + return True |
| 82 | + |
| 83 | + def close(self): |
| 84 | + # type: () -> None |
| 85 | + """Close the file.""" |
| 86 | + self._file.close() |
| 87 | + |
| 88 | + @property |
| 89 | + def closed(self): |
| 90 | + # type: () -> bool |
| 91 | + """Whether the file is closed.""" |
| 92 | + return self._file.closed |
| 93 | + |
| 94 | + def read(self, size=-1): |
| 95 | + # type: (int) -> bytes |
| 96 | + """Read up to size bytes from the object and return them. |
| 97 | +
|
| 98 | + As a convenience, if size is unspecified or -1, |
| 99 | + all bytes until EOF are returned. Fewer than |
| 100 | + size bytes may be returned if EOF is reached. |
| 101 | + """ |
| 102 | + start, length = self.tell(), self._length |
| 103 | + stop = start + size if 0 <= size <= length-start else length |
| 104 | + self._download(start, stop-1) |
| 105 | + return self._file.read(size) |
| 106 | + |
| 107 | + def readable(self): |
| 108 | + # type: () -> bool |
| 109 | + """Return whether the file is readable, which is True.""" |
| 110 | + return True |
| 111 | + |
| 112 | + def seek(self, offset, whence=0): |
| 113 | + # type: (int, int) -> int |
| 114 | + """Change stream position and return the new absolute position. |
| 115 | +
|
| 116 | + Seek to offset relative position indicated by whence: |
| 117 | + * 0: Start of stream (the default). pos should be >= 0; |
| 118 | + * 1: Current position - pos may be negative; |
| 119 | + * 2: End of stream - pos usually negative. |
| 120 | + """ |
| 121 | + return self._file.seek(offset, whence) |
| 122 | + |
| 123 | + def tell(self): |
| 124 | + # type: () -> int |
| 125 | + """Return the current possition.""" |
| 126 | + return self._file.tell() |
| 127 | + |
| 128 | + def truncate(self, size=None): |
| 129 | + # type: (Optional[int]) -> int |
| 130 | + """Resize the stream to the given size in bytes. |
| 131 | +
|
| 132 | + If size is unspecified resize to the current position. |
| 133 | + The current stream position isn't changed. |
| 134 | +
|
| 135 | + Return the new file size. |
| 136 | + """ |
| 137 | + return self._file.truncate(size) |
| 138 | + |
| 139 | + def writable(self): |
| 140 | + # type: () -> bool |
| 141 | + """Return False.""" |
| 142 | + return False |
| 143 | + |
| 144 | + def __enter__(self): |
| 145 | + # type: () -> LazyZipOverHTTP |
| 146 | + self._file.__enter__() |
| 147 | + return self |
| 148 | + |
| 149 | + def __exit__(self, *exc): |
| 150 | + # type: (*Any) -> Optional[bool] |
| 151 | + return self._file.__exit__(*exc) |
| 152 | + |
| 153 | + @contextmanager |
| 154 | + def _stay(self): |
| 155 | + # type: ()-> Iterator[None] |
| 156 | + """Return a context manager keeping the position. |
| 157 | +
|
| 158 | + At the end of the block, seek back to original position. |
| 159 | + """ |
| 160 | + pos = self.tell() |
| 161 | + try: |
| 162 | + yield |
| 163 | + finally: |
| 164 | + self.seek(pos) |
| 165 | + |
| 166 | + def _check_zip(self): |
| 167 | + # type: () -> None |
| 168 | + """Check and download until the file is a valid ZIP.""" |
| 169 | + end = self._length - 1 |
| 170 | + for start in reversed(range(0, end, self._chunk_size)): |
| 171 | + self._download(start, end) |
| 172 | + with self._stay(): |
| 173 | + try: |
| 174 | + # For read-only ZIP files, ZipFile only needs |
| 175 | + # methods read, seek, seekable and tell. |
| 176 | + ZipFile(self) # type: ignore |
| 177 | + except BadZipfile: |
| 178 | + pass |
| 179 | + else: |
| 180 | + break |
| 181 | + |
| 182 | + def _stream_response(self, start, end, base_headers=HEADERS): |
| 183 | + # type: (int, int, Dict[str, str]) -> Response |
| 184 | + """Return HTTP response to a range request from start to end.""" |
| 185 | + headers = {'Range': 'bytes={}-{}'.format(start, end)} |
| 186 | + headers.update(base_headers) |
| 187 | + return self._session.get(self._url, headers=headers, stream=True) |
| 188 | + |
| 189 | + def _merge(self, start, end, left, right): |
| 190 | + # type: (int, int, int, int) -> Iterator[Tuple[int, int]] |
| 191 | + """Return an iterator of intervals to be fetched. |
| 192 | +
|
| 193 | + Args: |
| 194 | + start (int): Start of needed interval |
| 195 | + end (int): End of needed interval |
| 196 | + left (int): Index of first overlapping downloaded data |
| 197 | + right (int): Index after last overlapping downloaded data |
| 198 | + """ |
| 199 | + lslice, rslice = self._left[left:right], self._right[left:right] |
| 200 | + i = start = min([start]+lslice[:1]) |
| 201 | + end = max([end]+rslice[-1:]) |
| 202 | + for j, k in zip(lslice, rslice): |
| 203 | + if j > i: |
| 204 | + yield i, j-1 |
| 205 | + i = k + 1 |
| 206 | + if i <= end: |
| 207 | + yield i, end |
| 208 | + self._left[left:right], self._right[left:right] = [start], [end] |
| 209 | + |
| 210 | + def _download(self, start, end): |
| 211 | + # type: (int, int) -> None |
| 212 | + """Download bytes from start to end inclusively.""" |
| 213 | + with self._stay(): |
| 214 | + left = bisect_left(self._right, start) |
| 215 | + right = bisect_right(self._left, end) |
| 216 | + for start, end in self._merge(start, end, left, right): |
| 217 | + response = self._stream_response(start, end) |
| 218 | + response.raise_for_status() |
| 219 | + self.seek(start) |
| 220 | + for chunk in response_chunks(response, self._chunk_size): |
| 221 | + self._file.write(chunk) |
0 commit comments