Debian Codegraph @

conda_package_streaming/lazy_wheel.py

raw
1 """Lazy ZIP over HTTP"""
2
3 from __future__ import annotations
4
5 import logging
6 import zipfile
7 from bisect import bisect_left, bisect_right
8 from collections.abc import Iterator
9 from contextlib import contextmanager
10 from tempfile import NamedTemporaryFile
11 from typing import Any
12 from zipfile import BadZipfile, ZipFile
13
14 from requests import HTTPError, Session
15 from requests.models import CONTENT_CHUNK_SIZE, Response
16
17 # from pip 22.0.3 with fixes & remove imports from pip
18
19
20 log = logging.getLogger(__name__)
21
22 # If-Match (etag) to detect file changed during fetch would also be nice
23 HEADERS = {"Accept-Encoding": "identity"}
24
25
26 class HTTPRangeRequestUnsupported(Exception):
27 pass
28
29
30 class LazyZipOverHTTP:
31 """File-like object mapped to a ZIP file over HTTP.
32
33 This uses HTTP range requests to lazily fetch the file's content,
34 which is supposed to be fed to ZipFile. If such requests are not
35 supported by the server, raise HTTPRangeRequestUnsupported
36 during initialization.
37 """
38
39 def __init__(
40 self,
41 url: str,
42 session: Session,
43 chunk_size: int = CONTENT_CHUNK_SIZE,
44 fall_back_to_full_download: bool = False,
45 ) -> None:
46 """
47 Initialize a LazyZipOverHTTP object.
48
49 :param session: The session to use for web requests.
50 :param chunk_size: The chunk size to use for downloading.
51 :param fall_back_to_full_download: If true, we fall back to downloading
52 the whole file if the server incorrectly responds with 416
53 (Range Not Satisfiable) to an HTTP range request.
54 """
55 # if CONTENT_CHUNK_SIZE is bigger than the file:
56 # In [8]: response.headers["Content-Range"]
57 # Out[8]: 'bytes 0-3133374/3133375'
58
59 self._request_count = 0
60
61 self._session, self._url, self._chunk_size = session, url, chunk_size
62
63 self._fall_back_to_full_download: bool = fall_back_to_full_download
64 self._has_streaming_support: bool = True
65
66 # If the server returns 416 (Range Not Satisfiable) and the fallback is
67 # enabled, we request the whole file and set this to False. Some package
68 # servers incorrectly respond with 416 (Range Not Satisfiable) if the
69 # file is smaller than the range requested.
70
71 # initial range request for the end of the file
72 # if the server does not support range requests, this sets
73 # _has_streaming_support to False
74 tail = self._stream_response(start="", end=CONTENT_CHUNK_SIZE)
75 # e.g. {'accept-ranges': 'bytes', 'content-length': '10240',
76 # 'content-range': 'bytes 12824-23063/23064', 'last-modified': 'Sat, 16
77 # Apr 2022 13:03:02 GMT', 'date': 'Thu, 21 Apr 2022 11:34:04 GMT'}
78
79 if self._has_streaming_support and tail.status_code != 206:
80 raise HTTPRangeRequestUnsupported("range request is not supported")
81
82 if self._has_streaming_support:
83 # lowercase content-range to support s3
84 self._length = int(tail.headers["content-range"].partition("/")[-1])
85 else:
86 # the file is already downloaded
87 self._length = len(tail.content)
88
89 self._file = NamedTemporaryFile()
90 self.truncate(self._length)
91
92 # length is also in Content-Length and Content-Range header
93 with self._stay():
94 if self._has_streaming_support:
95 content_length = int(tail.headers["content-length"])
96 if hasattr(tail, "content"):
97 assert content_length == len(tail.content)
98 else:
99 content_length = len(tail.content)
100 self.seek(self._length - content_length)
101 for chunk in tail.iter_content(self._chunk_size):
102 self._file.write(chunk)
103 self._left: list[int] = [self._length - content_length]
104 self._right: list[int] = [self._length - 1]
105
106 @property
107 def mode(self) -> str:
108 """Opening mode, which is always rb."""
109 return "rb"
110
111 @property
112 def name(self) -> str:
113 """Path to the underlying file."""
114 return self._file.name
115
116 def seekable(self) -> bool:
117 """Return whether random access is supported, which is True."""
118 return True
119
120 def close(self) -> None:
121 """Close the file."""
122 self._file.close()
123
124 @property
125 def closed(self) -> bool:
126 """Whether the file is closed."""
127 return self._file.closed
128
129 def read(self, size: int = -1) -> bytes:
130 """Read up to size bytes from the object and return them.
131
132 As a convenience, if size is unspecified or -1,
133 all bytes until EOF are returned. Fewer than
134 size bytes may be returned if EOF is reached.
135 """
136 # BUG does not download correctly if size is unspecified
137 download_size = size
138 start, length = self.tell(), self._length
139 stop = length if size < 0 else min(start + download_size, length)
140 start = max(0, stop - download_size)
141 self._download(start, stop - 1)
142 return self._file.read(size)
143
144 def readable(self) -> bool:
145 """Return whether the file is readable, which is True."""
146 return True
147
148 def seek(self, offset: int, whence: int = 0) -> int:
149 """Change stream position and return the new absolute position.
150
151 Seek to offset relative position indicated by whence:
152 * 0: Start of stream (the default). pos should be >= 0;
153 * 1: Current position - pos may be negative;
154 * 2: End of stream - pos usually negative.
155 """
156 return self._file.seek(offset, whence)
157
158 def tell(self) -> int:
159 """Return the current position."""
160 return self._file.tell()
161
162 def truncate(self, size: int | None = None) -> int:
163 """Resize the stream to the given size in bytes.
164
165 If size is unspecified resize to the current position.
166 The current stream position isn't changed.
167
168 Return the new file size.
169 """
170 return self._file.truncate(size)
171
172 def writable(self) -> bool:
173 """Return False."""
174 return False
175
176 def __enter__(self) -> LazyZipOverHTTP:
177 self._file.__enter__()
178 return self
179
180 def __exit__(self, *exc: Any) -> bool | None:
181 return self._file.__exit__(*exc)
182
183 @contextmanager
184 def _stay(self) -> Iterator[None]:
185 """Return a context manager keeping the position.
186
187 At the end of the block, seek back to original position.
188 """
189 pos = self.tell()
190 try:
191 yield
192 finally:
193 self.seek(pos)
194
195 def _check_zip(self) -> None:
196 """Check and download until the file is a valid ZIP."""
197 end = self._length - 1
198 for start in reversed(range(0, end, self._chunk_size)):
199 self._download(start, end)
200 with self._stay():
201 try:
202 # For read-only ZIP files, ZipFile only needs
203 # methods read, seek, seekable and tell.
204 ZipFile(self) # type: ignore
205 except BadZipfile:
206 pass
207 else:
208 break
209
210 def _stream_response(
211 self, start: int | str, end: int, base_headers: dict[str, str] = HEADERS
212 ) -> Response:
213 """
214 Return HTTP response to a range request from start to end.
215 If the does not support range requests, the whole file is requested.
216
217 :param start: if "", request `end` bytes from end of file.
218 """
219 headers = base_headers.copy()
220 headers["Range"] = f"bytes={start}-{end}"
221 log.debug("%s", headers["Range"])
222 # TODO: Get range requests to be correctly cached
223 headers["Cache-Control"] = "no-cache"
224 self._request_count += 1
225
226 if self._has_streaming_support:
227 response = self._session.get(self._url, headers=headers, stream=True)
228
229 if response.status_code == 416 and self._fall_back_to_full_download:
230 # Range Not Satisfiable -> enable fallback
231 self._has_streaming_support = False
232 elif response.status_code == 416:
233 # fallback disabled, print helpful error message
234 raise HTTPError(
235 "The server returned 416 (Range Not Satisfiable). "
236 "This can occur on a buggy server if the file is smaller "
237 "than the range requested. Set the fall_back_to_full_download flag "
238 "to work around this issue.",
239 response=response,
240 )
241 else:
242 response.raise_for_status()
243 return response
244
245 # no streaming support, try to get the whole file
246 del headers["Range"]
247 response = self._session.get(self._url, headers=headers, stream=True)
248
249 response.raise_for_status()
250 return response
251
252 def _merge(
253 self, start: int, end: int, left: int, right: int
254 ) -> Iterator[tuple[int, int]]:
255 """Return an iterator of intervals to be fetched.
256
257 Args:
258 start (int): Start of needed interval
259 end (int): End of needed interval
260 left (int): Index of first overlapping downloaded data
261 right (int): Index after last overlapping downloaded data
262 """
263 lslice, rslice = self._left[left:right], self._right[left:right]
264 i = start = min([start] + lslice[:1])
265 end = max([end] + rslice[-1:])
266 for j, k in zip(lslice, rslice):
267 if j > i:
268 yield i, j - 1
269 i = k + 1
270 if i <= end:
271 yield i, end
272 self._left[left:right], self._right[left:right] = [start], [end]
273
274 def _download(self, start: int, end: int) -> None:
275 """
276 Download bytes from start to end inclusively. If the server does not support
277 streaming for this file, this does nothing as the entire file is already
278 downloaded.
279 """
280 # these assertions should hold, but read() violates them
281 # assert 0 <= start <= end
282 # assert end < self._length
283
284 with self._stay():
285 left = bisect_left(self._right, start)
286 right = bisect_right(self._left, end)
287 for start, end in self._merge(start, end, left, right):
288 response = self._stream_response(start, end)
289 self.seek(start)
290 for chunk in response.iter_content(self._chunk_size):
291 self._file.write(chunk)
292
293
294 class LazyConda(LazyZipOverHTTP):
295 def prefetch(self, conda_file_id):
296 """
297 Conda fork specific. Prefetch the `.info` range from the remote archive.
298 Reduces number of Range requests to 2 or 3 (1 or 2 for the directory, 1
299 for the file).
300
301 conda_file_id: name of .conda without path or `.conda` extension
302 """
303 target_file = f"info-{conda_file_id}.tar.zst"
304 with self._stay(): # not strictly necessary
305 # try to read entire conda info in one request
306 zf = zipfile.ZipFile(self)
307 infolist = zf.infolist()
308 for i, info in enumerate(infolist):
309 if info.filename == target_file:
310 # could be incorrect if zipfile was concatenated to another
311 # file (not likely for .conda)
312 start = info.header_offset
313 try:
314 end = infolist[i + 1].header_offset
315 # or info.header_offset
316 # + len(info.filename)
317 # + len(info.extra)
318 # + info.compress_size
319 # (unless Zip64)
320 except IndexError:
321 end = zf.start_dir
322 self.seek(start)
323 self.read(end - start)
324 log.debug(
325 "prefetch %s-%s",
326 info.header_offset,
327 end,
328 )
329 break
330 else:
331 log.debug("no zip prefetch")