Debian Codegraph @

_transport_rs/src/http/client.rs

raw
1 //! Python bindings for `dromedary::http::client`.
2 //!
3 //! Exposes `HttpClient` as a `#[pyclass]`. The Python `HttpTransport`
4 //! in `dromedary/http/urllib.py` uses this instead of the legacy
5 //! urllib.request handler stack.
6 //!
7 //! The returned `HttpResponse` pyclass mirrors the shape the Python
8 //! code previously got from its `Urllib3LikeResponse` adapter —
9 //! `.status`, `.reason`, `.getheader()`, `.getheaders()`, `.data`,
10 //! `.text`, `.read()`, `.readline()`, `.readlines()` — so existing
11 //! callers (and the still-Python `HttpTransport.request` wrapper) see
12 //! no breaking change.
13
14 use std::path::PathBuf;
15 use std::sync::Mutex;
16 use std::time::Duration;
17
18 use dromedary::http::client::{
19 ActivityCallback, ActivityDirection, ClientError, CredentialProvider,
20 HttpClient as RsHttpClient, HttpClientConfig, HttpResponse as RsHttpResponse,
21 NegotiateProvider, RequestOptions, TokenProvider,
22 };
23 use pyo3::exceptions::{PyIOError, PyValueError};
24 use pyo3::import_exception;
25 use pyo3::prelude::*;
26 use pyo3::types::{PyBytes, PyList, PyString, PyTuple};
27
28 import_exception!(dromedary.errors, ConnectionError);
29 import_exception!(dromedary.errors, InvalidHttpResponse);
30
31 /// Turn a [`ClientError`] into an appropriate Python exception.
32 ///
33 /// Transport-level failures (DNS, TCP, TLS) become
34 /// `dromedary.errors.ConnectionError`; malformed URLs / methods
35 /// become `ValueError`; IO errors after the response started
36 /// become `OSError`. This matches how the Python urllib-handler
37 /// stack used to funnel errors.
38 pub(super) fn client_err_to_py(err: ClientError) -> PyErr {
39 match err {
40 ClientError::InvalidRequest(msg) => PyValueError::new_err(msg),
41 ClientError::Io(e) => PyIOError::new_err(e.to_string()),
42 ClientError::Transport(e) => {
43 // `ureq::Error`'s Display carries the useful context
44 // (hostname, port, TLS reason). Wrap as ConnectionError
45 // so breezy's retry loop triggers on it the way it did
46 // for the old handler-layer errors.
47 ConnectionError::new_err(e.to_string())
48 }
49 }
50 }
51
52 /// CredentialProvider impl that delegates to the Python callback
53 /// registered via `set_credential_lookup`. All state lives in the
54 /// parent module's `CREDENTIAL_LOOKUP` so multiple clients share
55 /// the same callback.
56 pub(crate) struct PythonCredentialProvider;
57
58 impl CredentialProvider for PythonCredentialProvider {
59 fn lookup(
60 &self,
61 protocol: &str,
62 host: &str,
63 port: Option<u16>,
64 realm: Option<&str>,
65 user_hint: Option<&str>,
66 is_proxy: bool,
67 ) -> (Option<String>, Option<String>) {
68 super::invoke_credential_lookup(protocol, host, port, realm, user_hint, is_proxy)
69 }
70 }
71
72 /// NegotiateProvider that delegates to the Python callback
73 /// registered via `set_negotiate_provider`. Dromedary ships a
74 /// default implementation in `dromedary.http` that uses the
75 /// Python `kerberos` module.
76 pub(crate) struct PythonNegotiateProvider;
77
78 impl NegotiateProvider for PythonNegotiateProvider {
79 fn initial_token(&self, host: &str) -> Option<String> {
80 super::invoke_negotiate_provider(host)
81 }
82 }
83
84 /// TokenProvider that delegates to the Python callback registered
85 /// via `set_token_provider`. Breezy installs one that pulls
86 /// preemptive bearer tokens from `authentication.conf`.
87 pub(crate) struct PythonTokenProvider;
88
89 impl TokenProvider for PythonTokenProvider {
90 fn lookup(
91 &self,
92 protocol: &str,
93 host: &str,
94 port: Option<u16>,
95 path: Option<&str>,
96 ) -> Option<(String, String)> {
97 super::invoke_token_provider(protocol, host, port, path)
98 }
99 }
100
101 #[pyclass(module = "dromedary._transport_rs.http", frozen)]
102 pub(crate) struct HttpClient {
103 inner: RsHttpClient,
104 // Default options applied when Python callers don't pass an
105 // override. Wrapped in a Mutex because pyclass(frozen) forbids
106 // &mut self; callers interact via dedicated setters below.
107 defaults: Mutex<RequestOptions>,
108 }
109
110 #[pymethods]
111 impl HttpClient {
112 /// Construct a new client.
113 ///
114 /// `ca_certs` — optional path to a PEM bundle.
115 /// `disable_verification` — matches Python's `ssl.CERT_NONE`.
116 /// `user_agent` — if omitted, inherits the module-level default.
117 /// `read_timeout_ms` — 0 or negative means "no timeout".
118 #[new]
119 #[pyo3(signature = (
120 ca_certs=None,
121 disable_verification=false,
122 user_agent=None,
123 read_timeout_ms=0,
124 ))]
125 fn new(
126 ca_certs: Option<PathBuf>,
127 disable_verification: bool,
128 user_agent: Option<String>,
129 read_timeout_ms: i64,
130 ) -> PyResult<Self> {
131 let timeout = if read_timeout_ms > 0 {
132 Some(Duration::from_millis(read_timeout_ms as u64))
133 } else {
134 None
135 };
136 let cfg = HttpClientConfig {
137 ca_certs_path: ca_certs,
138 disable_verification,
139 user_agent,
140 read_timeout: timeout,
141 };
142 let mut inner = RsHttpClient::with_full_providers(
143 cfg,
144 Box::new(PythonCredentialProvider),
145 Box::new(PythonNegotiateProvider),
146 Box::new(PythonTokenProvider),
147 )
148 .map_err(client_err_to_py)?;
149 inner.set_auth_trace(Some(std::sync::Arc::new(|header: &str| {
150 super::invoke_auth_header_trace(header);
151 })));
152 Ok(Self {
153 inner,
154 defaults: Mutex::new(RequestOptions::default()),
155 })
156 }
157
158 /// Set the default `follow_redirects` flag for subsequent calls
159 /// that don't pass an explicit `follow_redirects` argument.
160 ///
161 /// Exposed so breezy's `HttpTransport.request(..., retries=N)`
162 /// can toggle following once per transport rather than threading
163 /// the flag through every call site.
164 fn set_default_follow_redirects(&self, follow: bool) {
165 self.defaults.lock().unwrap().follow_redirects = follow;
166 }
167
168 /// Issue an HTTP request.
169 ///
170 /// `headers` is an iterable of `(name, value)` pairs (matching
171 /// the stdlib pattern). `report_activity`, when provided, is a
172 /// callable invoked as `report_activity(byte_count, direction)`
173 /// where direction is `"read"` or `"write"` — matches the Python
174 /// `Transport._report_activity` signature so breezy's progress
175 /// bar integration works unchanged.
176 #[pyo3(signature = (
177 method,
178 url,
179 headers=None,
180 body=None,
181 follow_redirects=None,
182 report_activity=None,
183 ))]
184 fn request(
185 &self,
186 py: Python,
187 method: &str,
188 url: &str,
189 headers: Option<Py<PyAny>>,
190 body: Option<Py<PyAny>>,
191 follow_redirects: Option<bool>,
192 report_activity: Option<Py<PyAny>>,
193 ) -> PyResult<HttpResponse> {
194 let header_pairs = match headers {
195 Some(h) => extract_headers(py, &h)?,
196 None => Vec::new(),
197 };
198 let body_bytes = match body {
199 Some(b) => extract_body(py, &b)?,
200 None => Vec::new(),
201 };
202 let opts = {
203 let mut o = self.defaults.lock().unwrap().clone();
204 if let Some(f) = follow_redirects {
205 o.follow_redirects = f;
206 }
207 o
208 };
209 let activity: Option<ActivityCallback> = report_activity.map(make_activity_callback);
210
211 // `Python::detach` releases the GIL while the HTTP call is
212 // in flight so other Python threads can run (matching the
213 // behaviour of the old urllib-based transport, which did the
214 // actual socket read under the GIL-released `ssl` module).
215 //
216 // The activity callback reacquires the GIL inside its
217 // closure body — safe because we're handing ownership of
218 // the callback to `request_with` via a reference.
219 let resp = py.detach(|| {
220 self.inner.request_with(
221 method,
222 url,
223 &header_pairs,
224 &body_bytes,
225 &opts,
226 activity.as_ref(),
227 )
228 });
229 let resp = resp.map_err(client_err_to_py)?;
230 Ok(HttpResponse::new(resp))
231 }
232 }
233
234 /// Wrap a Python callable as an [`ActivityCallback`]. The Python
235 /// callable receives `(byte_count, direction_str)` where direction
236 /// is `"read"` or `"write"` — matching the
237 /// `Transport._report_activity` signature breezy's UI expects.
238 ///
239 /// Errors inside the callback are silently swallowed. Activity
240 /// reporting is advisory; a broken progress-bar hook shouldn't fail
241 /// the actual HTTP request.
242 pub(super) fn make_activity_callback(cb: Py<PyAny>) -> ActivityCallback {
243 std::sync::Arc::new(move |bytes: usize, dir: ActivityDirection| {
244 Python::attach(|py| {
245 // `call1` can raise; ignore the result so a buggy hook
246 // doesn't propagate into the HTTP path.
247 let _ = cb.bind(py).call1((bytes, dir.as_str()));
248 });
249 })
250 }
251
252 /// Urllib3-shaped response returned by [`HttpClient::request`].
253 ///
254 /// Intentionally offers both the Python-file protocol (`read`,
255 /// `readline`, `readlines`) and the urllib3 property set (`status`,
256 /// `reason`, `data`, `text`, `getheader`, `getheaders`) so existing
257 /// callers pulled from `Urllib3LikeResponse` work unchanged.
258 ///
259 /// The body is streamed on demand from ureq rather than buffered
260 /// eagerly: `status` / `reason` / `getheader` / `getheaders` read
261 /// purely from metadata, `data` / `text` / `read(None)` force a
262 /// full drain, and `read(n)` / `readline()` pull incrementally.
263 /// First call to a "full drain" method transitions the underlying
264 /// body to a Buffered state so repeat reads are cheap.
265 #[pyclass(module = "dromedary._transport_rs.http")]
266 pub(crate) struct HttpResponse {
267 inner: Mutex<RsHttpResponse>,
268 }
269
270 impl HttpResponse {
271 pub(super) fn new(raw: RsHttpResponse) -> Self {
272 Self {
273 inner: Mutex::new(raw),
274 }
275 }
276 }
277
278 #[pymethods]
279 impl HttpResponse {
280 #[getter]
281 fn status(&self) -> u16 {
282 self.inner.lock().unwrap().status
283 }
284
285 #[getter]
286 fn reason(&self) -> String {
287 self.inner.lock().unwrap().reason.clone()
288 }
289
290 /// Final URL after any redirect following. For requests that
291 /// weren't redirected this equals the request URL.
292 #[getter]
293 fn final_url(&self) -> String {
294 self.inner.lock().unwrap().final_url.clone()
295 }
296
297 /// Set when the server returned a 3xx that the client didn't
298 /// auto-follow (`follow_redirects=False`). Callers use this to
299 /// raise `RedirectRequested`.
300 #[getter]
301 fn redirected_to(&self) -> Option<String> {
302 self.inner.lock().unwrap().redirected_to.clone()
303 }
304
305 /// Case-insensitive header lookup. `default` is returned if
306 /// no header matches.
307 #[pyo3(signature = (name, default=None))]
308 fn getheader(&self, py: Python, name: &str, default: Option<Py<PyAny>>) -> Py<PyAny> {
309 let inner = self.inner.lock().unwrap();
310 match inner.header(name) {
311 Some(v) => PyString::new(py, v).into(),
312 None => default.unwrap_or_else(|| py.None()),
313 }
314 }
315
316 /// Return all headers as a list of `(name, value)` tuples.
317 fn getheaders<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
318 let inner = self.inner.lock().unwrap();
319 let items: Vec<Bound<'py, PyAny>> = inner
320 .headers
321 .iter()
322 .map(|(k, v)| {
323 let tup = PyTuple::new(py, [PyString::new(py, k), PyString::new(py, v)])?;
324 Ok::<_, PyErr>(tup.into_any())
325 })
326 .collect::<PyResult<Vec<_>>>()?;
327 PyList::new(py, items)
328 }
329
330 /// Full response body as bytes. Forces a drain on first access;
331 /// subsequent reads through this property return the same
332 /// buffer without re-reading.
333 #[getter]
334 fn data<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
335 let mut inner = self.inner.lock().unwrap();
336 let body = inner.body().map_err(py_io_err)?;
337 Ok(PyBytes::new(py, body))
338 }
339
340 /// Decoded body as str, using the Content-Type charset when
341 /// present. Matches the Python `Urllib3LikeResponse.text` shim —
342 /// returns `None` on a 204 No Content response.
343 #[getter]
344 fn text(&self, py: Python) -> PyResult<Py<PyAny>> {
345 let mut inner = self.inner.lock().unwrap();
346 if inner.status == 204 {
347 return Ok(py.None());
348 }
349 // Read the charset out of the Content-Type header before
350 // borrowing the body; the two &self borrows otherwise
351 // overlap because `body()` takes &mut.
352 let _charset = inner
353 .header("content-type")
354 .and_then(|v| {
355 v.split(';').find_map(|piece| {
356 let piece = piece.trim();
357 piece
358 .strip_prefix("charset=")
359 .map(|c| c.trim_matches('"').to_string())
360 })
361 })
362 .unwrap_or_else(|| "utf-8".to_string());
363
364 // Only UTF-8 is handled natively; everything else falls back
365 // to replacing invalid bytes. Real non-UTF-8 payloads are
366 // vanishingly rare on the Bazaar smart-protocol path this
367 // is aimed at, and breezy didn't support them either.
368 let body = inner.body().map_err(py_io_err)?;
369 let text = String::from_utf8_lossy(body).into_owned();
370 Ok(PyString::new(py, &text).into())
371 }
372
373 /// File-like read. `size=None` (or negative) reads all remaining
374 /// bytes — forces a full drain. Positive `size` pulls up to that
375 /// many bytes from the current position (streamed), leaving the
376 /// rest available for subsequent reads.
377 #[pyo3(signature = (size=None))]
378 fn read<'py>(&self, py: Python<'py>, size: Option<i64>) -> PyResult<Bound<'py, PyBytes>> {
379 let mut inner = self.inner.lock().unwrap();
380 let n = match size {
381 None | Some(-1) => None,
382 Some(n) if n < 0 => None,
383 Some(n) => Some(n as usize),
384 };
385 let data = inner.read(n).map_err(py_io_err)?;
386 Ok(PyBytes::new(py, &data))
387 }
388
389 /// Read up to the next newline (inclusive) or EOF. Forces the
390 /// body to be buffered on first call — line splitting across a
391 /// live stream would require a BufRead wrapper we don't have
392 /// yet, and the callers that use readline() (handle_response
393 /// for multipart responses) typically consume the whole body
394 /// anyway.
395 #[pyo3(signature = (_size=-1))]
396 fn readline<'py>(&self, py: Python<'py>, _size: i64) -> PyResult<Bound<'py, PyBytes>> {
397 let mut inner = self.inner.lock().unwrap();
398 // Drain the body into the buffer so we can scan for '\n'
399 // without losing the rest of the stream.
400 let _ = inner.body().map_err(py_io_err)?;
401 // Now read one byte at a time until '\n' or EOF. This works
402 // because the BodyState is Buffered after body().
403 let mut line: Vec<u8> = Vec::new();
404 loop {
405 let chunk = inner.read(Some(1)).map_err(py_io_err)?;
406 if chunk.is_empty() {
407 break;
408 }
409 let b = chunk[0];
410 line.push(b);
411 if b == b'\n' {
412 break;
413 }
414 }
415 Ok(PyBytes::new(py, &line))
416 }
417
418 fn readlines<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
419 let mut out: Vec<Bound<'py, PyBytes>> = Vec::new();
420 loop {
421 let line = self.readline(py, -1)?;
422 if line.as_bytes().is_empty() {
423 break;
424 }
425 out.push(line);
426 }
427 PyList::new(py, out)
428 }
429
430 /// Close the response by discarding any unread body, returning
431 /// the underlying socket to ureq's pool. Mirrors the file-like
432 /// `close()` contract.
433 fn close(&self) -> PyResult<()> {
434 self.inner.lock().unwrap().discard_body().map_err(py_io_err)
435 }
436 }
437
438 /// Map an `io::Error` from the streaming body read into `OSError`.
439 fn py_io_err(e: std::io::Error) -> PyErr {
440 PyIOError::new_err(e.to_string())
441 }
442
443 /// Coerce whatever Python hands us into `(name, value)` pairs. We
444 /// accept either a dict or any iterable of two-tuples, matching the
445 /// old `request` signature where callers could pass either.
446 pub(super) fn extract_headers(py: Python, obj: &Py<PyAny>) -> PyResult<Vec<(String, String)>> {
447 let bound = obj.bind(py);
448 if let Ok(d) = bound.cast::<pyo3::types::PyDict>() {
449 let mut out = Vec::with_capacity(d.len());
450 for (k, v) in d.iter() {
451 out.push((k.extract::<String>()?, v.extract::<String>()?));
452 }
453 return Ok(out);
454 }
455 let mut out = Vec::new();
456 for item in bound.try_iter()? {
457 let pair = item?;
458 let tup = pair.cast::<PyTuple>().map_err(|_| {
459 PyValueError::new_err("headers must be a dict or iterable of (name, value) tuples")
460 })?;
461 if tup.len() != 2 {
462 return Err(PyValueError::new_err(
463 "header tuples must have exactly two elements",
464 ));
465 }
466 let k: String = tup.get_item(0)?.extract()?;
467 let v: String = tup.get_item(1)?.extract()?;
468 out.push((k, v));
469 }
470 Ok(out)
471 }
472
473 /// Accept `bytes`, `bytearray`, `memoryview`, or `str` (encoded as
474 /// UTF-8) as the request body. Matches how the Python side
475 /// previously passed data to `connection._send_request`.
476 pub(super) fn extract_body(py: Python, obj: &Py<PyAny>) -> PyResult<Vec<u8>> {
477 let bound = obj.bind(py);
478 if let Ok(b) = bound.cast::<PyBytes>() {
479 return Ok(b.as_bytes().to_vec());
480 }
481 if let Ok(s) = bound.extract::<String>() {
482 return Ok(s.into_bytes());
483 }
484 // Fallback: coerce via `bytes()` (handles bytearray, memoryview).
485 let as_bytes = py
486 .get_type::<PyBytes>()
487 .call1((bound.clone(),))
488 .map_err(|e| PyValueError::new_err(format!("can't interpret body as bytes: {}", e)))?;
489 let b = as_bytes
490 .cast::<PyBytes>()
491 .map_err(|e| PyValueError::new_err(format!("body coercion failed: {}", e)))?;
492 Ok(b.as_bytes().to_vec())
493 }
494
495 pub(crate) fn register(m: &Bound<PyModule>) -> PyResult<()> {
496 m.add_class::<HttpClient>()?;
497 m.add_class::<HttpResponse>()?;
498 Ok(())
499 }