| 1 |
//! Python bindings for `dromedary::http::transport::HttpTransport`. |
| 2 |
//! |
| 3 |
//! Exposes the Rust HTTP transport as |
| 4 |
//! `dromedary._transport_rs.http.HttpTransport`, a pyclass that |
| 5 |
//! extends `Transport`. The Python `HttpTransport` in |
| 6 |
//! `dromedary/http/urllib.py` becomes a thin subclass that adds |
| 7 |
//! breezy-side hooks (`_medium`, `_report_activity` override, |
| 8 |
//! ssl-config resolution, redirect fix-up) without re-implementing |
| 9 |
//! the transport itself. |
| 10 |
|
| 11 |
use std::path::PathBuf; |
| 12 |
use std::sync::Arc; |
| 13 |
use std::time::Duration; |
| 14 |
|
| 15 |
use dromedary::http::client::{ |
| 16 |
ActivityCallback, HttpClientConfig, NegotiateProvider, RequestOptions, |
| 17 |
}; |
| 18 |
use dromedary::http::{HttpClient, HttpTransport as RsHttpTransport}; |
| 19 |
use dromedary::Transport as RsTransport; |
| 20 |
use pyo3::prelude::*; |
| 21 |
use pyo3::types::PyBytes; |
| 22 |
|
| 23 |
use crate::map_transport_err_to_py_err; |
| 24 |
use crate::{ConnectedTransport, Transport}; |
| 25 |
|
| 26 |
use super::client::{ |
| 27 |
client_err_to_py, extract_body, extract_headers, make_activity_callback, HttpResponse, |
| 28 |
PythonCredentialProvider, PythonNegotiateProvider, PythonTokenProvider, |
| 29 |
}; |
| 30 |
|
| 31 |
/// Python-bound Rust HTTP transport. |
| 32 |
/// |
| 33 |
/// Constructor: `HttpTransport(base, ca_certs=None, |
| 34 |
/// disable_verification=False, user_agent=None, |
| 35 |
/// read_timeout_ms=0)`. Each construction builds a fresh |
| 36 |
/// `HttpClient`; call `clone()` to get a sibling transport that |
| 37 |
/// shares the underlying agent and auth cache. |
| 38 |
/// |
| 39 |
/// We stash a concrete `Arc<RsHttpTransport>` alongside the base |
| 40 |
/// `Transport` so helper methods like `_post` can reach the |
| 41 |
/// HttpTransport-specific API without going through a |
| 42 |
/// `dyn Transport` downcast. |
| 43 |
#[pyclass(extends=ConnectedTransport, subclass, module = "dromedary._transport_rs.http")] |
| 44 |
pub(crate) struct HttpTransport { |
| 45 |
// `pub(crate)` rather than private so sibling modules (notably |
| 46 |
// `webdav`) can construct an HttpTransport pyclass parent that |
| 47 |
// points at their own transport's embedded HttpTransport — |
| 48 |
// necessary for `extends=HttpTransport` pyclasses to share the |
| 49 |
// inherited `request` / `_post` / ... methods. |
| 50 |
pub(crate) inner: Arc<RsHttpTransport>, |
| 51 |
} |
| 52 |
|
| 53 |
#[pymethods] |
| 54 |
impl HttpTransport { |
| 55 |
#[new] |
| 56 |
#[pyo3(signature = ( |
| 57 |
base, |
| 58 |
ca_certs=None, |
| 59 |
disable_verification=false, |
| 60 |
user_agent=None, |
| 61 |
read_timeout_ms=0, |
| 62 |
))] |
| 63 |
fn new( |
| 64 |
base: &str, |
| 65 |
ca_certs: Option<PathBuf>, |
| 66 |
disable_verification: bool, |
| 67 |
user_agent: Option<String>, |
| 68 |
read_timeout_ms: i64, |
| 69 |
) -> PyResult<PyClassInitializer<Self>> { |
| 70 |
let timeout = if read_timeout_ms > 0 { |
| 71 |
Some(Duration::from_millis(read_timeout_ms as u64)) |
| 72 |
} else { |
| 73 |
None |
| 74 |
}; |
| 75 |
let cfg = HttpClientConfig { |
| 76 |
ca_certs_path: ca_certs, |
| 77 |
disable_verification, |
| 78 |
user_agent, |
| 79 |
read_timeout: timeout, |
| 80 |
}; |
| 81 |
let mut client = HttpClient::with_full_providers( |
| 82 |
cfg, |
| 83 |
Box::new(PythonCredentialProvider), |
| 84 |
Box::new(PythonNegotiateProvider) as Box<dyn NegotiateProvider>, |
| 85 |
Box::new(PythonTokenProvider), |
| 86 |
) |
| 87 |
.map_err(|e| { |
| 88 |
map_transport_err_to_py_err( |
| 89 |
dromedary::Error::Io(std::io::Error::other(format!("{}", e))), |
| 90 |
None, |
| 91 |
Some(base), |
| 92 |
) |
| 93 |
})?; |
| 94 |
// Route auth-header traces back through the Python callback |
| 95 |
// set via `set_auth_header_trace`. Breezy registers that |
| 96 |
// callback at import time so debug-flag-controlled |
| 97 |
// "> Authorization: <masked>" lines reach `trace.mutter`. |
| 98 |
client.set_auth_trace(Some(std::sync::Arc::new(|header: &str| { |
| 99 |
super::invoke_auth_header_trace(header); |
| 100 |
}))); |
| 101 |
let rust = RsHttpTransport::new(base, Arc::new(client)) |
| 102 |
.map_err(|e| map_transport_err_to_py_err(e, None, Some(base)))?; |
| 103 |
let inner = Arc::new(rust); |
| 104 |
Ok(http_transport_initializer(inner)) |
| 105 |
} |
| 106 |
|
| 107 |
/// Clone this transport at an optional offset, sharing the |
| 108 |
/// underlying HttpClient. |
| 109 |
/// |
| 110 |
/// Returns an instance of the base Rust ``HttpTransport``. |
| 111 |
/// Python subclasses that want ``type(self)``-preserving cloning |
| 112 |
/// should override ``clone`` and use |
| 113 |
/// ``_clone_from`` to graft the shared state onto |
| 114 |
/// a freshly-constructed subclass instance. |
| 115 |
#[pyo3(signature = (offset=None))] |
| 116 |
fn clone<'a>( |
| 117 |
slf: PyRef<'a, Self>, |
| 118 |
py: Python<'a>, |
| 119 |
offset: Option<&str>, |
| 120 |
) -> PyResult<Bound<'a, HttpTransport>> { |
| 121 |
let cloned = slf |
| 122 |
.inner |
| 123 |
.clone_concrete(offset) |
| 124 |
.map_err(|e| map_transport_err_to_py_err(e, None, offset))?; |
| 125 |
Bound::new(py, http_transport_initializer(Arc::new(cloned))) |
| 126 |
} |
| 127 |
|
| 128 |
/// Replace this transport's inner state with the state of |
| 129 |
/// ``source``, effectively turning ``self`` into a clone of |
| 130 |
/// ``source`` at the current base URL. Used by the Python |
| 131 |
/// subclass override of ``clone`` to achieve shared-state |
| 132 |
/// cloning while preserving the subclass identity: the subclass |
| 133 |
/// builds a fresh instance with its desired base, then calls |
| 134 |
/// this method to inherit the source transport's HttpClient, |
| 135 |
/// auth cache, and range-hint state. |
| 136 |
/// |
| 137 |
/// After calling this, the two transports share the same |
| 138 |
/// underlying Rust state exactly as if the receiver had been |
| 139 |
/// produced by ``source.clone(offset)``. |
| 140 |
fn _clone_from( |
| 141 |
mut slf: PyRefMut<Self>, |
| 142 |
source: PyRef<Self>, |
| 143 |
offset: Option<&str>, |
| 144 |
) -> PyResult<()> { |
| 145 |
// When no offset is supplied, take the source's inner |
| 146 |
// directly rather than cloning — clone_concrete's |
| 147 |
// (deliberate) segment-parameter and raw_base stripping |
| 148 |
// loses information that matters for ``__init__``-time |
| 149 |
// TLS-config rebuilds (see |
| 150 |
// ``dromedary.http.urllib.HttpTransport.__init__``). |
| 151 |
let new_inner = match offset { |
| 152 |
None => source.inner.clone(), |
| 153 |
Some(_) => { |
| 154 |
let cloned = source |
| 155 |
.inner |
| 156 |
.clone_concrete(offset) |
| 157 |
.map_err(|e| map_transport_err_to_py_err(e, None, offset))?; |
| 158 |
Arc::new(cloned) |
| 159 |
} |
| 160 |
}; |
| 161 |
// Replace the base Transport(Box<dyn Transport>) too so |
| 162 |
// calls routed through the dyn vtable see the cloned state. |
| 163 |
let base_box: Box<dyn dromedary::Transport> = Box::new(Clone::clone(&*new_inner)); |
| 164 |
// Walk up through the ConnectedTransport layer to reach the |
| 165 |
// Transport pyclass where the dyn handle actually lives. |
| 166 |
let connected = slf.as_super(); |
| 167 |
connected.as_super().0 = base_box; |
| 168 |
slf.inner = new_inner; |
| 169 |
Ok(()) |
| 170 |
} |
| 171 |
|
| 172 |
/// Install (or clear) the transport-level activity callback. |
| 173 |
/// Python subclasses invoke this with a bound method reference |
| 174 |
/// (``self._report_activity``) so internal get / has / post / |
| 175 |
/// readv calls funnel byte-count updates into breezy's progress |
| 176 |
/// UI the same way the explicit ``request()`` path already does. |
| 177 |
/// Pass ``None`` to clear. |
| 178 |
#[pyo3(signature = (callback))] |
| 179 |
fn _set_activity_callback(&self, callback: Option<Py<PyAny>>) { |
| 180 |
let cb = callback.map(super::client::make_activity_callback); |
| 181 |
self.inner.set_activity(cb); |
| 182 |
} |
| 183 |
|
| 184 |
/// Current range hint as `"multi"`, `"single"`, or `None`. Part |
| 185 |
/// of the public-ish transport interface so the breezy test |
| 186 |
/// suite can observe the client's fallback state. |
| 187 |
#[getter] |
| 188 |
fn _range_hint(&self) -> Option<&'static str> { |
| 189 |
self.inner.range_hint_str() |
| 190 |
} |
| 191 |
|
| 192 |
/// Step the range hint down one rung. Returns True if we |
| 193 |
/// stepped, False if we were already at the floor. |
| 194 |
fn _degrade_range_hint(&self) -> bool { |
| 195 |
self.inner.degrade_range_hint() |
| 196 |
} |
| 197 |
|
| 198 |
// Readv-tuning getters / setters. These mirror the Python |
| 199 |
// urllib HttpTransport's instance attributes that breezy's |
| 200 |
// tests poke at to force specific batching behaviour: |
| 201 |
// `_max_readv_combine`, `_bytes_to_read_before_seek`, |
| 202 |
// `_get_max_size`, `_max_get_ranges`. Each setter swaps the |
| 203 |
// single named field while leaving the others untouched, so |
| 204 |
// tests that override one don't reset the others. |
| 205 |
|
| 206 |
#[getter] |
| 207 |
fn _max_readv_combine(&self) -> usize { |
| 208 |
self.inner.readv_tuning().max_readv_combine |
| 209 |
} |
| 210 |
#[setter] |
| 211 |
fn set__max_readv_combine(&self, v: usize) { |
| 212 |
let mut t = self.inner.readv_tuning(); |
| 213 |
t.max_readv_combine = v; |
| 214 |
self.inner.set_readv_tuning(t); |
| 215 |
} |
| 216 |
|
| 217 |
#[getter] |
| 218 |
fn _bytes_to_read_before_seek(&self) -> usize { |
| 219 |
self.inner.readv_tuning().bytes_to_read_before_seek |
| 220 |
} |
| 221 |
#[setter] |
| 222 |
fn set__bytes_to_read_before_seek(&self, v: usize) { |
| 223 |
let mut t = self.inner.readv_tuning(); |
| 224 |
t.bytes_to_read_before_seek = v; |
| 225 |
self.inner.set_readv_tuning(t); |
| 226 |
} |
| 227 |
|
| 228 |
#[getter] |
| 229 |
fn _get_max_size(&self) -> usize { |
| 230 |
self.inner.readv_tuning().get_max_size |
| 231 |
} |
| 232 |
#[setter] |
| 233 |
fn set__get_max_size(&self, v: usize) { |
| 234 |
let mut t = self.inner.readv_tuning(); |
| 235 |
t.get_max_size = v; |
| 236 |
self.inner.set_readv_tuning(t); |
| 237 |
} |
| 238 |
|
| 239 |
#[getter] |
| 240 |
fn _max_get_ranges(&self) -> usize { |
| 241 |
self.inner.readv_tuning().max_get_ranges |
| 242 |
} |
| 243 |
#[setter] |
| 244 |
fn set__max_get_ranges(&self, v: usize) { |
| 245 |
let mut t = self.inner.readv_tuning(); |
| 246 |
t.max_get_ranges = v; |
| 247 |
self.inner.set_readv_tuning(t); |
| 248 |
} |
| 249 |
|
| 250 |
/// Unqualified HTTP scheme (`"http"` or `"https"`) — strips any |
| 251 |
/// `+impl` qualifier present in the base URL. Exposed for |
| 252 |
/// breezy's test harness which reads it directly. |
| 253 |
#[getter] |
| 254 |
fn _unqualified_scheme(&self) -> PyResult<String> { |
| 255 |
// Base URL's scheme is always the unqualified form after |
| 256 |
// normalise_http_url(); use that rather than re-parsing. |
| 257 |
let url = RsTransport::base(&*self.inner); |
| 258 |
Ok(url.scheme().to_string()) |
| 259 |
} |
| 260 |
|
| 261 |
/// Build the remote URL for `relpath`: absolute URL with any |
| 262 |
/// embedded user/password stripped and the scheme reduced to |
| 263 |
/// its unqualified form. Auth goes through headers, not URL. |
| 264 |
fn _remote_path(&self, relpath: &str) -> PyResult<String> { |
| 265 |
let url = self |
| 266 |
.inner |
| 267 |
.remote_url(relpath) |
| 268 |
.map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?; |
| 269 |
Ok(url.to_string()) |
| 270 |
} |
| 271 |
|
| 272 |
/// Drop any cached connection state. A no-op on the Rust client |
| 273 |
/// (ureq's pool is per-agent and released lazily), but kept for |
| 274 |
/// API compatibility with the urllib handler stack. |
| 275 |
fn disconnect(&self) {} |
| 276 |
|
| 277 |
/// Issue an HTTP request through the transport's shared client. |
| 278 |
/// |
| 279 |
/// Returns the same `HttpResponse` pyclass the standalone |
| 280 |
/// `HttpClient.request` hands back, so existing callers that |
| 281 |
/// previously did `self._client.request(...)` don't need to |
| 282 |
/// change response-handling code. |
| 283 |
#[pyo3(signature = ( |
| 284 |
method, |
| 285 |
url, |
| 286 |
headers=None, |
| 287 |
body=None, |
| 288 |
follow_redirects=false, |
| 289 |
report_activity=None, |
| 290 |
))] |
| 291 |
fn request( |
| 292 |
&self, |
| 293 |
py: Python, |
| 294 |
method: &str, |
| 295 |
url: &str, |
| 296 |
headers: Option<Py<PyAny>>, |
| 297 |
body: Option<Py<PyAny>>, |
| 298 |
follow_redirects: bool, |
| 299 |
report_activity: Option<Py<PyAny>>, |
| 300 |
) -> PyResult<HttpResponse> { |
| 301 |
let header_pairs = match headers { |
| 302 |
Some(h) => extract_headers(py, &h)?, |
| 303 |
None => Vec::new(), |
| 304 |
}; |
| 305 |
let body_bytes = match body { |
| 306 |
Some(b) => extract_body(py, &b)?, |
| 307 |
None => Vec::new(), |
| 308 |
}; |
| 309 |
let opts = RequestOptions { |
| 310 |
follow_redirects, |
| 311 |
..RequestOptions::default() |
| 312 |
}; |
| 313 |
let activity: Option<ActivityCallback> = report_activity.map(make_activity_callback); |
| 314 |
let resp = py.detach(|| { |
| 315 |
self.inner.client().request_with( |
| 316 |
method, |
| 317 |
url, |
| 318 |
&header_pairs, |
| 319 |
&body_bytes, |
| 320 |
&opts, |
| 321 |
activity.as_ref(), |
| 322 |
) |
| 323 |
}); |
| 324 |
let resp = resp.map_err(client_err_to_py)?; |
| 325 |
Ok(HttpResponse::new(resp)) |
| 326 |
} |
| 327 |
|
| 328 |
/// HEAD `relpath`. Returns the response for 200 / 404 and |
| 329 |
/// raises for everything else, matching the Python `_head`. |
| 330 |
fn _head(&self, py: Python, relpath: &str) -> PyResult<HttpResponse> { |
| 331 |
let resp = py |
| 332 |
.detach(|| self.inner.head(relpath)) |
| 333 |
.map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?; |
| 334 |
Ok(HttpResponse::new(resp)) |
| 335 |
} |
| 336 |
|
| 337 |
/// OPTIONS `relpath`. Returns the response headers as a list of |
| 338 |
/// `(name, value)` tuples on 2xx; raises `NoSuchFile` on 404 or |
| 339 |
/// `InvalidHttpResponse` on 403/405. |
| 340 |
fn _options(&self, py: Python, relpath: &str) -> PyResult<Vec<(String, String)>> { |
| 341 |
py.detach(|| self.inner.options(relpath)) |
| 342 |
.map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath))) |
| 343 |
} |
| 344 |
|
| 345 |
/// POST `body` to `relpath` and return `(status, response_body)`. |
| 346 |
/// Mirrors the Python `HttpTransport._post` used by breezy's |
| 347 |
/// smart HTTP medium. |
| 348 |
fn _post<'py>( |
| 349 |
&self, |
| 350 |
py: Python<'py>, |
| 351 |
relpath: &str, |
| 352 |
body: &[u8], |
| 353 |
) -> PyResult<(u16, Bound<'py, PyBytes>)> { |
| 354 |
// Release the GIL around the blocking HTTP exchange: the |
| 355 |
// in-process breezy test HTTP server runs in a Python thread |
| 356 |
// and can't accept connections while we hold the GIL, which |
| 357 |
// otherwise deadlocks POST-over-loopback tests. |
| 358 |
let (status, buf) = py |
| 359 |
.detach(|| -> Result<(u16, Vec<u8>), dromedary::Error> { |
| 360 |
let (status, mut rf) = self.inner.post(relpath, body)?; |
| 361 |
let mut buf = Vec::new(); |
| 362 |
std::io::Read::read_to_end(&mut rf, &mut buf).map_err(dromedary::Error::Io)?; |
| 363 |
Ok((status, buf)) |
| 364 |
}) |
| 365 |
.map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?; |
| 366 |
Ok((status, PyBytes::new(py, &buf))) |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
/// Build the three-layer `Transport → ConnectedTransport → |
| 371 |
/// HttpTransport` initializer PyO3 needs for pyclass construction. |
| 372 |
/// |
| 373 |
/// `pub(crate)` so `webdav::transport` can extend the chain with a |
| 374 |
/// fourth `add_subclass(HttpDavTransport {...})` layer, reusing the |
| 375 |
/// HttpTransport parent's `inner` pointer to share the HTTP client |
| 376 |
/// and range-hint state with the DAV transport above it. |
| 377 |
pub(crate) fn http_transport_initializer( |
| 378 |
inner: Arc<RsHttpTransport>, |
| 379 |
) -> PyClassInitializer<HttpTransport> { |
| 380 |
let base_box: Box<dyn dromedary::Transport> = Box::new(Clone::clone(&*inner)); |
| 381 |
http_transport_initializer_with_base(inner, base_box) |
| 382 |
} |
| 383 |
|
| 384 |
/// Like `http_transport_initializer` but lets the caller supply a |
| 385 |
/// specific `dyn Transport` to install at the base `Transport` |
| 386 |
/// pyclass layer. Used by the DAV subclass so default-method |
| 387 |
/// dispatch (e.g. `Transport::move` in Python, which goes to the |
| 388 |
/// Rust `dyn Transport::move` in turn) reaches the DAV impls (stat |
| 389 |
/// via PROPFIND, native MOVE) rather than the HTTP parent that |
| 390 |
/// has no stat support. |
| 391 |
pub(crate) fn http_transport_initializer_with_base( |
| 392 |
inner: Arc<RsHttpTransport>, |
| 393 |
base_box: Box<dyn dromedary::Transport>, |
| 394 |
) -> PyClassInitializer<HttpTransport> { |
| 395 |
PyClassInitializer::from(Transport(base_box)) |
| 396 |
.add_subclass(ConnectedTransport) |
| 397 |
.add_subclass(HttpTransport { inner }) |
| 398 |
} |
| 399 |
|
| 400 |
pub(crate) fn register(m: &Bound<PyModule>) -> PyResult<()> { |
| 401 |
m.add_class::<HttpTransport>()?; |
| 402 |
Ok(()) |
| 403 |
} |