lazy_wheel.py 7.7 KB

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