Debian Codegraph @

src/urllib3/contrib/emscripten/response.py

raw
1 from __future__ import annotations
2
3 import json as _json
4 import logging
5 import typing
6 from contextlib import contextmanager
7 from dataclasses import dataclass
8 from http.client import HTTPException as HTTPException
9 from io import BytesIO, IOBase
10
11 from ...exceptions import InvalidHeader, TimeoutError
12 from ...response import BaseHTTPResponse
13 from ...util.retry import Retry
14 from .request import EmscriptenRequest
15
16 if typing.TYPE_CHECKING:
17 from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection
18
19 log = logging.getLogger(__name__)
20
21
22 @dataclass
23 class EmscriptenResponse:
24 status_code: int
25 headers: dict[str, str]
26 body: IOBase | bytes
27 request: EmscriptenRequest
28
29
30 class EmscriptenHttpResponseWrapper(BaseHTTPResponse):
31 def __init__(
32 self,
33 internal_response: EmscriptenResponse,
34 url: str | None = None,
35 connection: BaseHTTPConnection | BaseHTTPSConnection | None = None,
36 ):
37 self._pool = None # set by pool class
38 self._body = None
39 self._uncached_read_occurred = False
40 self._response = internal_response
41 self._url = url
42 self._connection = connection
43 self._closed = False
44 super().__init__(
45 headers=internal_response.headers,
46 status=internal_response.status_code,
47 request_url=url,
48 version=0,
49 version_string="HTTP/?",
50 reason="",
51 decode_content=True,
52 )
53 self.length_remaining = self._init_length(self._response.request.method)
54 self.length_is_certain = False
55
56 @property
57 def url(self) -> str | None:
58 return self._url
59
60 @url.setter
61 def url(self, url: str | None) -> None:
62 self._url = url
63
64 @property
65 def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None:
66 return self._connection
67
68 @property
69 def retries(self) -> Retry | None:
70 return self._retries
71
72 @retries.setter
73 def retries(self, retries: Retry | None) -> None:
74 # Override the request_url if retries has a redirect location.
75 self._retries = retries
76
77 def stream(
78 self, amt: int | None = 2**16, decode_content: bool | None = None
79 ) -> typing.Generator[bytes]:
80 """
81 A generator wrapper for the read() method. A call will block until
82 ``amt`` bytes have been read from the connection or until the
83 connection is closed.
84
85 :param amt:
86 How much of the content to read. The generator will return up to
87 much data per iteration, but may return less. This is particularly
88 likely when using compressed data. However, the empty string will
89 never be returned.
90
91 :param decode_content:
92 If True, will attempt to decode the body based on the
93 'content-encoding' header.
94 """
95 while True:
96 data = self.read(amt=amt, decode_content=decode_content)
97
98 if data:
99 yield data
100 else:
101 break
102
103 def _init_length(self, request_method: str | None) -> int | None:
104 length: int | None
105 content_length: str | None = self.headers.get("content-length")
106
107 if content_length is not None:
108 try:
109 # RFC 7230 section 3.3.2 specifies multiple content lengths can
110 # be sent in a single Content-Length header
111 # (e.g. Content-Length: 42, 42). This line ensures the values
112 # are all valid ints and that as long as the `set` length is 1,
113 # all values are the same. Otherwise, the header is invalid.
114 lengths = {int(val) for val in content_length.split(",")}
115 if len(lengths) > 1:
116 raise InvalidHeader(
117 "Content-Length contained multiple "
118 "unmatching values (%s)" % content_length
119 )
120 length = lengths.pop()
121 except ValueError:
122 length = None
123 else:
124 if length < 0:
125 length = None
126
127 else: # if content_length is None
128 length = None
129
130 # Check for responses that shouldn't include a body
131 if (
132 self.status in (204, 304)
133 or 100 <= self.status < 200
134 or request_method == "HEAD"
135 ):
136 length = 0
137
138 return length
139
140 def read(
141 self,
142 amt: int | None = None,
143 decode_content: bool | None = None, # ignored because browser decodes always
144 cache_content: bool = False,
145 ) -> bytes:
146 if (
147 self._closed
148 or self._response is None
149 or (isinstance(self._response.body, IOBase) and self._response.body.closed)
150 ):
151 return b""
152
153 with self._error_catcher():
154 # body has been preloaded as a string by XmlHttpRequest
155 if not isinstance(self._response.body, IOBase):
156 self.length_remaining = len(self._response.body)
157 self.length_is_certain = True
158 # wrap body in IOStream
159 self._response.body = BytesIO(self._response.body)
160 if amt is not None and amt >= 0:
161 # don't cache partial content
162 cache_content = False
163 data = self._response.body.read(amt)
164 self._uncached_read_occurred = True
165 else: # read all we can (and cache it)
166 data = self._response.body.read()
167 if cache_content and not self._uncached_read_occurred:
168 self._body = data
169 else:
170 self._uncached_read_occurred = True
171 if self.length_remaining is not None:
172 self.length_remaining = max(self.length_remaining - len(data), 0)
173 if len(data) == 0 or (
174 self.length_is_certain and self.length_remaining == 0
175 ):
176 # definitely finished reading, close response stream
177 self._response.body.close()
178 return typing.cast(bytes, data)
179
180 def read_chunked(
181 self,
182 amt: int | None = None,
183 decode_content: bool | None = None,
184 ) -> typing.Generator[bytes]:
185 # chunked is handled by browser
186 while True:
187 bytes = self.read(amt, decode_content)
188 if not bytes:
189 break
190 yield bytes
191
192 def release_conn(self) -> None:
193 if not self._pool or not self._connection:
194 return None
195
196 self._pool._put_conn(self._connection)
197 self._connection = None
198
199 def drain_conn(self) -> None:
200 self.close()
201
202 @property
203 def data(self) -> bytes:
204 if self._body:
205 return self._body
206 else:
207 return self.read(cache_content=True)
208
209 def json(self) -> typing.Any:
210 """
211 Deserializes the body of the HTTP response as a Python object.
212
213 The body of the HTTP response must be encoded using UTF-8, as per
214 `RFC 8529 Section 8.1 <https://www.rfc-editor.org/rfc/rfc8259#section-8.1>`_.
215
216 To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
217 your custom decoder instead.
218
219 If the body of the HTTP response is not decodable to UTF-8, a
220 `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
221 valid JSON document, a `json.JSONDecodeError` will be raised.
222
223 Read more :ref:`here <json_content>`.
224
225 :returns: The body of the HTTP response as a Python object.
226 """
227 data = self.data.decode("utf-8")
228 return _json.loads(data)
229
230 def close(self) -> None:
231 if not self._closed:
232 if isinstance(self._response.body, IOBase):
233 self._response.body.close()
234 if self._connection:
235 self._connection.close()
236 self._connection = None
237 self._closed = True
238
239 @contextmanager
240 def _error_catcher(self) -> typing.Generator[None]:
241 """
242 Catch Emscripten specific exceptions thrown by fetch.py,
243 instead re-raising urllib3 variants, so that low-level exceptions
244 are not leaked in the high-level api.
245
246 On exit, release the connection back to the pool.
247 """
248 from .fetch import _RequestError, _TimeoutError # avoid circular import
249
250 clean_exit = False
251
252 try:
253 yield
254 # If no exception is thrown, we should avoid cleaning up
255 # unnecessarily.
256 clean_exit = True
257 except _TimeoutError as e:
258 raise TimeoutError(str(e))
259 except _RequestError as e:
260 raise HTTPException(str(e))
261 finally:
262 # If we didn't terminate cleanly, we need to throw away our
263 # connection.
264 if not clean_exit:
265 # The response may not be closed but we're not going to use it
266 # anymore so close it now
267 if (
268 isinstance(self._response.body, IOBase)
269 and not self._response.body.closed
270 ):
271 self._response.body.close()
272 # release the connection back to the pool
273 self.release_conn()
274 else:
275 # If we have read everything from the response stream,
276 # return the connection back to the pool.
277 if (
278 isinstance(self._response.body, IOBase)
279 and self._response.body.closed
280 ):
281 self.release_conn()