lazy_wheel.py 7.5 KB

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