| 1 |
//! Python bindings for `dromedary::http::response`. |
| 2 |
//! |
| 3 |
//! Exposes `ResponseFile`, `RangeFile`, and `handle_response` so that |
| 4 |
//! the Python side of `dromedary.http` can drop its hand-rolled |
| 5 |
//! implementation and delegate here. |
| 6 |
//! |
| 7 |
//! The two classes each hold their Rust counterpart. The underlying |
| 8 |
//! input file is an arbitrary Python file-like: we don't require |
| 9 |
//! `pyo3-filelike` because the trait we need (`read(n)` and |
| 10 |
//! `readline()` only) is simpler than the full file protocol. |
| 11 |
|
| 12 |
use std::io; |
| 13 |
|
| 14 |
use pyo3::exceptions::PyTypeError; |
| 15 |
use pyo3::import_exception; |
| 16 |
use pyo3::prelude::*; |
| 17 |
use pyo3::types::PyBytes; |
| 18 |
|
| 19 |
use dromedary::http::response::{ |
| 20 |
handle_response as rs_handle_response, InFile, RangeFile as RsRangeFile, ResponseError, |
| 21 |
ResponseFile as RsResponseFile, ResponseKind, |
| 22 |
}; |
| 23 |
|
| 24 |
import_exception!(dromedary.errors, InvalidHttpResponse); |
| 25 |
import_exception!(dromedary.errors, InvalidHttpRange); |
| 26 |
import_exception!(dromedary.errors, HttpBoundaryMissing); |
| 27 |
import_exception!(dromedary.errors, ShortReadvError); |
| 28 |
import_exception!(dromedary.errors, InvalidRange); |
| 29 |
import_exception!(dromedary.errors, UnexpectedHttpStatus); |
| 30 |
|
| 31 |
/// Adapter: a Python file-like object accessed via Python attribute |
| 32 |
/// calls. We do **not** wrap with `pyo3_filelike::PyBinaryFile` |
| 33 |
/// because we need the file-like's own `readline()` semantics to |
| 34 |
/// match what socket / BytesIO objects already provide — stdlib |
| 35 |
/// `BufReader::read_until` splits differently on non-terminated |
| 36 |
/// last lines. |
| 37 |
struct PyInFile { |
| 38 |
obj: Py<PyAny>, |
| 39 |
} |
| 40 |
|
| 41 |
impl PyInFile { |
| 42 |
fn new(obj: Py<PyAny>) -> Self { |
| 43 |
Self { obj } |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
fn py_err_to_io(e: PyErr) -> io::Error { |
| 48 |
io::Error::other(e.to_string()) |
| 49 |
} |
| 50 |
|
| 51 |
fn pyany_to_bytes(py: Python, any: &Bound<PyAny>) -> io::Result<Vec<u8>> { |
| 52 |
if let Ok(b) = any.cast::<PyBytes>() { |
| 53 |
return Ok(b.as_bytes().to_vec()); |
| 54 |
} |
| 55 |
// Some file-likes (e.g. text-mode objects, or `StringIO`) return |
| 56 |
// `str` instead of `bytes`. Convert with UTF-8 encoding; matches |
| 57 |
// the Python-side behaviour where a caller using a StringIO for |
| 58 |
// tests would get the same bytes out. |
| 59 |
if let Ok(s) = any.extract::<String>() { |
| 60 |
return Ok(s.into_bytes()); |
| 61 |
} |
| 62 |
// As a last resort, anything buffer-protocol-compatible (memoryview, |
| 63 |
// bytearray) can go through `bytes()`. |
| 64 |
let as_bytes = py |
| 65 |
.get_type::<PyBytes>() |
| 66 |
.call1((any,)) |
| 67 |
.map_err(py_err_to_io)?; |
| 68 |
let b = as_bytes |
| 69 |
.cast::<PyBytes>() |
| 70 |
.map_err(|e| io::Error::other(format!("file-like returned non-bytes: {}", e)))?; |
| 71 |
Ok(b.as_bytes().to_vec()) |
| 72 |
} |
| 73 |
|
| 74 |
impl InFile for PyInFile { |
| 75 |
fn read(&mut self, n: usize) -> io::Result<Vec<u8>> { |
| 76 |
Python::attach(|py| { |
| 77 |
let r = self |
| 78 |
.obj |
| 79 |
.bind(py) |
| 80 |
.call_method1("read", (n,)) |
| 81 |
.map_err(py_err_to_io)?; |
| 82 |
pyany_to_bytes(py, &r) |
| 83 |
}) |
| 84 |
} |
| 85 |
|
| 86 |
fn readline(&mut self) -> io::Result<Vec<u8>> { |
| 87 |
Python::attach(|py| { |
| 88 |
let r = self |
| 89 |
.obj |
| 90 |
.bind(py) |
| 91 |
.call_method0("readline") |
| 92 |
.map_err(py_err_to_io)?; |
| 93 |
pyany_to_bytes(py, &r) |
| 94 |
}) |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
fn response_err_to_py(err: ResponseError) -> PyErr { |
| 99 |
match err { |
| 100 |
ResponseError::InvalidResponse { path, msg } => InvalidHttpResponse::new_err((path, msg)), |
| 101 |
ResponseError::InvalidHttpRange { path, range, msg } => { |
| 102 |
InvalidHttpRange::new_err((path, range, msg)) |
| 103 |
} |
| 104 |
ResponseError::BoundaryMissing { path, boundary } => { |
| 105 |
// The Python side passes the raw boundary bytes as the |
| 106 |
// `msg` argument; mirror that. |
| 107 |
Python::attach(|py| { |
| 108 |
HttpBoundaryMissing::new_err((path, PyBytes::new(py, &boundary).unbind())) |
| 109 |
}) |
| 110 |
} |
| 111 |
ResponseError::ShortReadv { |
| 112 |
path, |
| 113 |
offset, |
| 114 |
length, |
| 115 |
actual, |
| 116 |
} => ShortReadvError::new_err((path, offset, length, actual)), |
| 117 |
ResponseError::InvalidRange { path, offset, msg } => { |
| 118 |
InvalidRange::new_err((path, offset, msg)) |
| 119 |
} |
| 120 |
ResponseError::UnexpectedStatus { path, code } => { |
| 121 |
UnexpectedHttpStatus::new_err((path, code)) |
| 122 |
} |
| 123 |
ResponseError::Io(e) => pyo3::exceptions::PyIOError::new_err(e.to_string()), |
| 124 |
ResponseError::InvalidWhence(w) => { |
| 125 |
pyo3::exceptions::PyValueError::new_err(format!("Invalid value {} for whence.", w)) |
| 126 |
} |
| 127 |
ResponseError::BackwardSeek { path, pos, offset } => { |
| 128 |
pyo3::exceptions::PyAssertionError::new_err(format!( |
| 129 |
"{}: can't seek backwards, pos: {}, offset: {}", |
| 130 |
path, pos, offset |
| 131 |
)) |
| 132 |
} |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
/// Python binding: `dromedary._transport_rs.http.ResponseFile`. |
| 137 |
/// |
| 138 |
/// Constructor: `ResponseFile(path, infile)`. The `infile` must |
| 139 |
/// expose at least `read(n)` and `readline()` — standard file-like |
| 140 |
/// duck typing, the same as what the Python original needed. |
| 141 |
#[pyclass(module = "dromedary._transport_rs.http", subclass)] |
| 142 |
pub(crate) struct ResponseFile { |
| 143 |
inner: RsResponseFile<PyInFile>, |
| 144 |
} |
| 145 |
|
| 146 |
#[pymethods] |
| 147 |
impl ResponseFile { |
| 148 |
#[new] |
| 149 |
fn new(path: String, infile: Py<PyAny>) -> Self { |
| 150 |
Self { |
| 151 |
inner: RsResponseFile::new(path, PyInFile::new(infile)), |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
/// No-op; matches the Python API for file-like compatibility. |
| 156 |
fn close(&self) {} |
| 157 |
|
| 158 |
fn __enter__(slf: Py<Self>) -> Py<Self> { |
| 159 |
slf |
| 160 |
} |
| 161 |
|
| 162 |
#[pyo3(signature = (_exc_type=None, _exc_val=None, _exc_tb=None))] |
| 163 |
fn __exit__( |
| 164 |
&self, |
| 165 |
_exc_type: Option<Py<PyAny>>, |
| 166 |
_exc_val: Option<Py<PyAny>>, |
| 167 |
_exc_tb: Option<Py<PyAny>>, |
| 168 |
) -> bool { |
| 169 |
false |
| 170 |
} |
| 171 |
|
| 172 |
/// Read up to `size` bytes; `None` (the default) means "read to |
| 173 |
/// EOF". `-1` is accepted as an alias for `None`, matching the |
| 174 |
/// Python convention. |
| 175 |
#[pyo3(signature = (size=None))] |
| 176 |
fn read<'py>(&mut self, py: Python<'py>, size: Option<i64>) -> PyResult<Bound<'py, PyBytes>> { |
| 177 |
let sz = match size { |
| 178 |
None | Some(-1) => None, |
| 179 |
Some(n) if n < 0 => None, |
| 180 |
Some(n) => Some(n as usize), |
| 181 |
}; |
| 182 |
let data = self.inner.read(sz).map_err(response_err_to_py)?; |
| 183 |
Ok(PyBytes::new(py, &data)) |
| 184 |
} |
| 185 |
|
| 186 |
fn readline<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> { |
| 187 |
let data = self.inner.readline().map_err(response_err_to_py)?; |
| 188 |
Ok(PyBytes::new(py, &data)) |
| 189 |
} |
| 190 |
|
| 191 |
/// Read all remaining lines. The optional `size` argument is |
| 192 |
/// accepted for Python-file-like compatibility but ignored, |
| 193 |
/// matching the Python version. |
| 194 |
#[pyo3(signature = (_size=None))] |
| 195 |
fn readlines<'py>( |
| 196 |
&mut self, |
| 197 |
py: Python<'py>, |
| 198 |
_size: Option<i64>, |
| 199 |
) -> PyResult<Vec<Bound<'py, PyBytes>>> { |
| 200 |
let lines = self.inner.readlines().map_err(response_err_to_py)?; |
| 201 |
Ok(lines.into_iter().map(|l| PyBytes::new(py, &l)).collect()) |
| 202 |
} |
| 203 |
|
| 204 |
fn __iter__(slf: Py<Self>) -> Py<Self> { |
| 205 |
slf |
| 206 |
} |
| 207 |
|
| 208 |
fn __next__<'py>(&mut self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> { |
| 209 |
let line = self.inner.readline().map_err(response_err_to_py)?; |
| 210 |
if line.is_empty() { |
| 211 |
Ok(None) |
| 212 |
} else { |
| 213 |
Ok(Some(PyBytes::new(py, &line))) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
fn tell(&self) -> u64 { |
| 218 |
self.inner.tell() |
| 219 |
} |
| 220 |
|
| 221 |
#[pyo3(signature = (offset, whence=0))] |
| 222 |
fn seek(&mut self, offset: i64, whence: u32) -> PyResult<()> { |
| 223 |
self.inner.seek(offset, whence).map_err(response_err_to_py) |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
/// Python binding: `dromedary._transport_rs.http.RangeFile`. |
| 228 |
/// |
| 229 |
/// Not a subclass of `ResponseFile` in the Rust bindings — nothing |
| 230 |
/// in the Python code base does `isinstance(rf, ResponseFile)`, so |
| 231 |
/// keeping them independent avoids the PyO3 subclass boilerplate. |
| 232 |
#[pyclass(module = "dromedary._transport_rs.http")] |
| 233 |
pub(crate) struct RangeFile { |
| 234 |
inner: RsRangeFile<PyInFile>, |
| 235 |
} |
| 236 |
|
| 237 |
#[pymethods] |
| 238 |
impl RangeFile { |
| 239 |
#[new] |
| 240 |
fn new(path: String, infile: Py<PyAny>) -> Self { |
| 241 |
Self { |
| 242 |
inner: RsRangeFile::new(path, PyInFile::new(infile)), |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
fn close(&self) {} |
| 247 |
|
| 248 |
fn __enter__(slf: Py<Self>) -> Py<Self> { |
| 249 |
slf |
| 250 |
} |
| 251 |
|
| 252 |
#[pyo3(signature = (_exc_type=None, _exc_val=None, _exc_tb=None))] |
| 253 |
fn __exit__( |
| 254 |
&self, |
| 255 |
_exc_type: Option<Py<PyAny>>, |
| 256 |
_exc_val: Option<Py<PyAny>>, |
| 257 |
_exc_tb: Option<Py<PyAny>>, |
| 258 |
) -> bool { |
| 259 |
false |
| 260 |
} |
| 261 |
|
| 262 |
/// Read up to `size` bytes from the current range. `-1` means |
| 263 |
/// "read to end of range" (matches the Python default). |
| 264 |
#[pyo3(signature = (size=-1))] |
| 265 |
fn read<'py>(&mut self, py: Python<'py>, size: i64) -> PyResult<Bound<'py, PyBytes>> { |
| 266 |
let data = self.inner.read(size).map_err(response_err_to_py)?; |
| 267 |
Ok(PyBytes::new(py, &data)) |
| 268 |
} |
| 269 |
|
| 270 |
fn tell(&self) -> u64 { |
| 271 |
self.inner.tell() |
| 272 |
} |
| 273 |
|
| 274 |
#[pyo3(signature = (offset, whence=0))] |
| 275 |
fn seek(&mut self, offset: i64, whence: u32) -> PyResult<()> { |
| 276 |
self.inner.seek(offset, whence).map_err(response_err_to_py) |
| 277 |
} |
| 278 |
|
| 279 |
fn set_range(&mut self, start: u64, size: i64) { |
| 280 |
let size = if size < 0 { None } else { Some(size as u64) }; |
| 281 |
self.inner.set_range(start, size); |
| 282 |
} |
| 283 |
|
| 284 |
/// Multipart boundary; passed as bytes by the caller. A non-bytes |
| 285 |
/// argument raises `TypeError` to match the Python |
| 286 |
/// `isinstance(boundary, bytes)` check. |
| 287 |
fn set_boundary(&mut self, py: Python, boundary: Py<PyAny>) -> PyResult<()> { |
| 288 |
let bound = boundary.bind(py); |
| 289 |
let bytes = bound |
| 290 |
.cast::<PyBytes>() |
| 291 |
.map_err(|_| PyTypeError::new_err("boundary must be bytes"))?; |
| 292 |
self.inner |
| 293 |
.set_boundary(bytes.as_bytes().to_vec()) |
| 294 |
.map_err(response_err_to_py) |
| 295 |
} |
| 296 |
|
| 297 |
fn read_boundary(&mut self) -> PyResult<()> { |
| 298 |
self.inner.read_boundary().map_err(response_err_to_py) |
| 299 |
} |
| 300 |
|
| 301 |
fn read_range_definition(&mut self) -> PyResult<()> { |
| 302 |
self.inner |
| 303 |
.read_range_definition() |
| 304 |
.map_err(response_err_to_py) |
| 305 |
} |
| 306 |
|
| 307 |
fn set_range_from_header(&mut self, content_range: &str) -> PyResult<()> { |
| 308 |
self.inner |
| 309 |
.set_range_from_header(content_range) |
| 310 |
.map_err(response_err_to_py) |
| 311 |
} |
| 312 |
|
| 313 |
// Python-compatibility properties — the original pure-Python |
| 314 |
// implementation exposed `_start`, `_size`, `_pos`, and |
| 315 |
// `_boundary` as ordinary instance attributes. Several tests |
| 316 |
// (and occasionally user code that bypassed the normal seek |
| 317 |
// machinery) poke them directly, so we mirror them here. The |
| 318 |
// setter methods use the `set_<name>` naming that PyO3 expects |
| 319 |
// for `#[setter]` on properties called `_start` / `_size` / |
| 320 |
// `_pos`; that's what puts the underscore in the middle of the |
| 321 |
// Rust name. |
| 322 |
|
| 323 |
#[getter(_start)] |
| 324 |
fn py_start(&self) -> u64 { |
| 325 |
self.inner.rs_start() |
| 326 |
} |
| 327 |
|
| 328 |
#[setter(_start)] |
| 329 |
fn py_set_start(&mut self, value: u64) { |
| 330 |
self.inner.rs_set_start(value); |
| 331 |
} |
| 332 |
|
| 333 |
/// `-1` means "size unknown" (matches the Python convention). |
| 334 |
#[getter(_size)] |
| 335 |
fn py_size(&self) -> i64 { |
| 336 |
match self.inner.rs_size() { |
| 337 |
Some(n) => n as i64, |
| 338 |
None => -1, |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
#[setter(_size)] |
| 343 |
fn py_set_size(&mut self, value: i64) { |
| 344 |
let v = if value < 0 { None } else { Some(value as u64) }; |
| 345 |
self.inner.rs_set_size(v); |
| 346 |
} |
| 347 |
|
| 348 |
#[getter(_pos)] |
| 349 |
fn py_pos(&self) -> u64 { |
| 350 |
self.inner.tell() |
| 351 |
} |
| 352 |
|
| 353 |
#[setter(_pos)] |
| 354 |
fn py_set_pos(&mut self, value: u64) { |
| 355 |
self.inner.rs_set_pos(value); |
| 356 |
} |
| 357 |
|
| 358 |
#[getter(_boundary)] |
| 359 |
fn py_boundary<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> { |
| 360 |
self.inner.rs_boundary().map(|b| PyBytes::new(py, b)) |
| 361 |
} |
| 362 |
|
| 363 |
#[getter(_discarded_buf_size)] |
| 364 |
fn py_discarded_buf_size(&self) -> usize { |
| 365 |
self.inner.rs_discarded_buf_size() |
| 366 |
} |
| 367 |
|
| 368 |
#[setter(_discarded_buf_size)] |
| 369 |
fn py_set_discarded_buf_size(&mut self, value: usize) { |
| 370 |
self.inner.rs_set_discarded_buf_size(value); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
/// Factory mirroring `dromedary.http.response.handle_response`. |
| 375 |
/// |
| 376 |
/// Instead of taking a `getheader` callback like the Python version, |
| 377 |
/// we accept the headers dict up front and look them up case- |
| 378 |
/// insensitively. `getheader` takes `(name, default)` in Python; we |
| 379 |
/// unify by requiring a plain `dict[str, str]` from the caller and |
| 380 |
/// handling the default here. |
| 381 |
#[pyfunction] |
| 382 |
pub(crate) fn handle_response( |
| 383 |
py: Python, |
| 384 |
url: String, |
| 385 |
code: u16, |
| 386 |
getheader: Py<PyAny>, |
| 387 |
data: Py<PyAny>, |
| 388 |
) -> PyResult<Py<PyAny>> { |
| 389 |
// Bridge the Python getheader(name, default=None) callable to a |
| 390 |
// Rust closure returning Option<String>. |
| 391 |
let get = |name: &str| -> Option<String> { |
| 392 |
Python::attach(|py| { |
| 393 |
let res = getheader.bind(py).call1((name, py.None())).ok()?; |
| 394 |
if res.is_none() { |
| 395 |
None |
| 396 |
} else { |
| 397 |
res.extract::<String>().ok() |
| 398 |
} |
| 399 |
}) |
| 400 |
}; |
| 401 |
let kind = |
| 402 |
rs_handle_response(url, code, &get, PyInFile::new(data)).map_err(response_err_to_py)?; |
| 403 |
match kind { |
| 404 |
ResponseKind::Plain(inner) => { |
| 405 |
let cls = Py::new(py, ResponseFile { inner })?; |
| 406 |
Ok(cls.into_any()) |
| 407 |
} |
| 408 |
ResponseKind::Range(inner) => { |
| 409 |
let cls = Py::new(py, RangeFile { inner })?; |
| 410 |
Ok(cls.into_any()) |
| 411 |
} |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
pub(crate) fn register(m: &Bound<PyModule>) -> PyResult<()> { |
| 416 |
m.add_class::<ResponseFile>()?; |
| 417 |
m.add_class::<RangeFile>()?; |
| 418 |
m.add_function(wrap_pyfunction!(handle_response, m)?)?; |
| 419 |
Ok(()) |
| 420 |
} |