Debian Codegraph @

_transport_rs/src/lib.rs

raw
1 use ::log::debug;
2 use dromedary::lock::{FileLock, Lock as LockTrait, LockError};
3 use dromedary::{Error, ReadStream, Transport as TransportTrait, UrlFragment, WriteStream};
4 use pyo3::exceptions::{PyRuntimeError, PyValueError};
5 use pyo3::import_exception;
6 use pyo3::prelude::*;
7 use pyo3::types::{PyBytes, PyIterator, PyList, PyType};
8 use pyo3_filelike::PyBinaryFile;
9 use std::collections::HashMap;
10 use std::fs::Permissions;
11 use std::io::{BufRead, BufReader, Read, Seek, Write};
12 #[cfg(unix)]
13 use std::os::unix::fs::PermissionsExt;
14 use std::path::{Path, PathBuf};
15 use std::sync::Mutex;
16 use url::Url;
17
18 import_exception!(dromedary.errors, TransportError);
19 import_exception!(dromedary.errors, NotLocalUrl);
20 import_exception!(dromedary.errors, InProcessTransport);
21 import_exception!(dromedary.errors, NoSuchFile);
22 import_exception!(dromedary.errors, FileExists);
23 import_exception!(dromedary.errors, PathNotChild);
24 import_exception!(dromedary.errors, PermissionDenied);
25 import_exception!(dromedary.errors, TransportNotPossible);
26 import_exception!(dromedary.errors, ShortReadvError);
27 import_exception!(dromedary.errors, LockContention);
28 import_exception!(dromedary.errors, LockFailed);
29 import_exception!(dromedary.errors, ReadError);
30 import_exception!(dromedary.errors, PathError);
31 import_exception!(dromedary.errors, DirectoryNotEmpty);
32 import_exception!(dromedary.errors, NotADirectory);
33 import_exception!(dromedary.errors, ResourceBusy);
34 import_exception!(dromedary.errors, InvalidHttpResponse);
35 import_exception!(dromedary.errors, UnexpectedHttpStatus);
36 import_exception!(dromedary.errors, InvalidHttpRange);
37 import_exception!(dromedary.errors, BadHttpRequest);
38 import_exception!(dromedary.errors, RedirectRequested);
39 import_exception!(dromedary.errors, UnusableRedirect);
40 import_exception!(dromedary.errors, ConnectionError);
41 import_exception!(dromedary.urlutils, InvalidURL);
42
43 #[pyclass(subclass)]
44 pub(crate) struct Transport(pub(crate) Box<dyn TransportTrait>);
45
46 /// Python-visible iterator wrapping the Rust-side `readv` iterator.
47 ///
48 /// Holds a strong reference to the parent Transport pyclass
49 /// (`Py<Transport>`) so the `'static`-transmuted inner iterator
50 /// never outlives the transport it borrows from. Each `__next__`
51 /// pulls one element from the Rust iterator under `py.detach` so
52 /// HTTP calls in the iterator body can block without holding the
53 /// GIL — the in-process Python test HTTP server lives in another
54 /// thread and needs the GIL to serve requests.
55 #[pyclass]
56 pub(crate) struct ReadvIter {
57 /// Keeps the underlying Transport (and therefore the `dyn
58 /// TransportTrait` + client state the iterator closed over)
59 /// alive for as long as the iterator is live. Python holds a
60 /// strong reference via this `Py`.
61 #[allow(dead_code)]
62 parent: Py<Transport>,
63 /// The Rust iterator. `Option` so `__next__` can hand out the
64 /// final `None` cleanly and drop the iterator early if a
65 /// caller leaks the iterator pyclass. `Mutex` because PyO3's
66 /// `#[pymethods]` takes `&self`, but iterator advancement
67 /// needs mutation.
68 iter: Mutex<Option<Box<dyn Iterator<Item = Result<(u64, Vec<u8>), dromedary::Error>> + Send>>>,
69 /// Path string used for error-mapping; carried alongside the
70 /// iterator for easy access on `__next__`'s Err path.
71 path: String,
72 }
73
74 #[pymethods]
75 impl ReadvIter {
76 fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
77 slf
78 }
79
80 fn __next__<'py>(&self, py: Python<'py>) -> PyResult<Option<(u64, Bound<'py, PyBytes>)>> {
81 let result = py.detach(|| {
82 let mut guard = self.iter.lock().unwrap();
83 guard.as_mut().and_then(|it| it.next())
84 });
85 match result {
86 None => {
87 // Drop the iterator so cached HTTP state releases
88 // as soon as the caller stops consuming.
89 *self.iter.lock().unwrap() = None;
90 Ok(None)
91 }
92 Some(Err(e)) => {
93 *self.iter.lock().unwrap() = None;
94 Err(map_transport_err_to_py_err(e, None, Some(&self.path)))
95 }
96 Some(Ok((offset, data))) => Ok(Some((offset, PyBytes::new(py, &data)))),
97 }
98 }
99 }
100
101 /// Python-visible base class for Rust-backed transports that talk to
102 /// a remote server. Mirrors `dromedary.ConnectedTransport` on the
103 /// Python side, providing the `_user` / `_password` / `_host` /
104 /// `_port` / `_path` / `_scheme` getters and `disconnect()` /
105 /// `_reuse_for()` that `get_transport_from_url(possible_transports=…)`
106 /// relies on for connection pooling.
107 #[pyclass(extends=Transport, subclass)]
108 pub(crate) struct ConnectedTransport;
109
110 #[pymethods]
111 impl ConnectedTransport {
112 #[getter]
113 fn _scheme(slf: PyRef<'_, Self>) -> String {
114 let base = slf.as_super().0.base();
115 dromedary::connected_url_scheme(&base)
116 }
117
118 #[getter]
119 fn _host(slf: PyRef<'_, Self>) -> Option<String> {
120 let base = slf.as_super().0.base();
121 dromedary::connected_url_host(&base)
122 }
123
124 #[getter]
125 fn _port(slf: PyRef<'_, Self>) -> Option<u16> {
126 let base = slf.as_super().0.base();
127 dromedary::connected_url_port(&base)
128 }
129
130 #[getter]
131 fn _user(slf: PyRef<'_, Self>) -> Option<String> {
132 let base = slf.as_super().0.base();
133 dromedary::connected_url_user(&base)
134 }
135
136 #[getter]
137 fn _password(slf: PyRef<'_, Self>) -> Option<String> {
138 let base = slf.as_super().0.base();
139 dromedary::connected_url_password(&base)
140 }
141
142 #[getter]
143 fn _path(slf: PyRef<'_, Self>) -> String {
144 let base = slf.as_super().0.base();
145 dromedary::connected_url_path(&base)
146 }
147
148 /// Parsed form of the base URL as a `dromedary.urlutils.URL`.
149 /// Historically set on the Python `ConnectedTransport` at
150 /// construction; breezy's `transport/remote.py` reads it for
151 /// host / port / user / password access. We build one on
152 /// demand so Rust-backed transports don't have to carry extra
153 /// state.
154 #[getter]
155 fn _parsed_url<'py>(slf: PyRef<'py, Self>, py: Python<'py>) -> PyResult<Py<PyAny>> {
156 let base = slf.as_super().0.base();
157 let base_str = base.to_string();
158 let module = py.import("dromedary.urlutils")?;
159 let cls = module.getattr("URL")?;
160 let url = cls.call_method1("from_string", (base_str.as_str(),))?;
161 Ok(url.unbind())
162 }
163
164 /// Shared-connection handle. Breezy compares
165 /// `_get_connection()` results across clones to decide whether
166 /// two transports share an underlying connection. We can't
167 /// expose the Rust `Arc<HttpClient>` identity directly across
168 /// the FFI boundary, so we use the next best signal: the
169 /// `(scheme, host, port)` tuple. Two transports with the same
170 /// origin share the same `HttpClient` pool entry and from
171 /// breezy's perspective are "the same connection"; transports
172 /// at different paths under the same origin (e.g. after a
173 /// redirect from `/foo/` to `/foo/subdir/`) are also "the same
174 /// connection" and should compare equal here.
175 fn _get_connection<'py>(slf: PyRef<'py, Self>, py: Python<'py>) -> PyResult<Py<PyAny>> {
176 let base = slf.as_super().0.base();
177 let key = format!(
178 "{}://{}:{}",
179 base.scheme(),
180 base.host_str().unwrap_or(""),
181 base.port_or_known_default().unwrap_or(0),
182 );
183 Ok(pyo3::types::PyString::new(py, &key).into())
184 }
185
186 /// Default `disconnect` — a no-op. Concrete transports with an
187 /// explicit connection handle override this in Python (or extend
188 /// the pyclass and override the pymethod).
189 fn disconnect(&self) {}
190
191 /// Return a transport for `other_base` sharing this transport's
192 /// connection state, or `None` if the URLs point at different
193 /// origins.
194 ///
195 /// The comparison logic lives in pure Rust (`classify_reuse_for`)
196 /// so pure-Rust callers use the same rules. This layer just
197 /// dispatches on the result: same-origin-same-path returns
198 /// `self`, same-origin-different-path calls back into Python to
199 /// let subclass `__init__` flow through with its extra kwargs
200 /// (e.g. HTTPS_transport's `ca_certs`).
201 fn _reuse_for<'py>(
202 slf: PyRef<'py, Self>,
203 py: Python<'py>,
204 other_base: &str,
205 ) -> PyResult<Py<PyAny>> {
206 let base = slf.as_super().0.base();
207 match dromedary::classify_reuse_for(&base, other_base) {
208 dromedary::ReuseMatch::None => Ok(py.None()),
209 dromedary::ReuseMatch::Same => Ok(slf.into_pyobject(py)?.into_any().unbind()),
210 dromedary::ReuseMatch::Sibling => {
211 let bound = slf.into_pyobject(py)?;
212 let cls = bound.get_type();
213 let kwargs = pyo3::types::PyDict::new(py);
214 kwargs.set_item("_from_transport", bound.clone())?;
215 let sibling = cls.call((other_base,), Some(&kwargs))?;
216 Ok(sibling.unbind())
217 }
218 }
219 }
220 }
221
222 /// Shared base class for all Rust-backed Transport decorators.
223 ///
224 /// Stores a reference to the wrapped Python transport and provides the
225 /// common decorator machinery (`_decorated` accessor, `__getattr__`
226 /// fallback, redirect re-wrapping). Concrete decorators extend this class
227 /// and only need to supply their URL prefix and their `__new__` / `clone`
228 /// (which construct the decorator-specific wrapped Rust transport).
229 #[pyclass(extends=Transport, subclass)]
230 pub(crate) struct TransportDecorator {
231 pub(crate) decorated: Py<PyAny>,
232 pub(crate) prefix: &'static str,
233 }
234
235 #[pymethods]
236 impl TransportDecorator {
237 #[getter]
238 fn _decorated(&self, py: Python) -> Py<PyAny> {
239 self.decorated.clone_ref(py)
240 }
241
242 #[classmethod]
243 fn _get_url_prefix(_cls: &Bound<'_, pyo3::types::PyType>) -> PyResult<&'static str> {
244 // Subclasses override this to return their static prefix. Called on
245 // the class itself, not the instance, so we can't consult `prefix`
246 // here — but since this is the abstract base, we shouldn't be called
247 // on it directly. Return empty to make the failure obvious.
248 Ok("")
249 }
250
251 /// Forward unrecognised attribute access to the wrapped transport.
252 ///
253 /// Decorators mix Rust (base Transport methods) with Python (extras like
254 /// HttpTransport.request). Anything not bound on the decorator itself
255 /// should pass through to the inner transport.
256 fn __getattr__(&self, py: Python, name: &str) -> PyResult<Py<PyAny>> {
257 self.decorated.bind(py).getattr(name).map(|b| b.unbind())
258 }
259
260 /// Re-wrap the redirected transport so the decorator qualifier is
261 /// preserved across HTTP redirects.
262 fn _redirected_to<'a>(
263 slf: PyRef<'a, Self>,
264 py: Python<'a>,
265 source: &str,
266 target: &str,
267 ) -> PyResult<Option<Py<PyAny>>> {
268 let inner = slf.decorated.bind(py);
269 let redirected = inner.call_method1("_redirected_to", (source, target))?;
270 if redirected.is_none() {
271 return Ok(None);
272 }
273 let base: String = redirected.getattr("base")?.extract()?;
274 let new_url = format!("{}{}", slf.prefix, base);
275 let cls = slf.into_pyobject(py)?.get_type();
276 let instance = cls.call1((new_url, redirected.clone().unbind()))?;
277 Ok(Some(instance.unbind()))
278 }
279 }
280
281 pub(crate) fn map_transport_err_to_py_err(
282 e: Error,
283 t: Option<Py<PyAny>>,
284 p: Option<&UrlFragment>,
285 ) -> PyErr {
286 let pick_path = |n: Option<String>| n.or_else(|| p.map(|p| p.to_string()));
287 match e {
288 Error::InProcessTransport => InProcessTransport::new_err((t,)),
289 Error::NotLocalUrl(url) => NotLocalUrl::new_err((url,)),
290 Error::NoSuchFile(name) => NoSuchFile::new_err((pick_path(name),)),
291 Error::FileExists(name) => FileExists::new_err((pick_path(name),)),
292 Error::TransportNotPossible(msg) => TransportNotPossible::new_err((msg,)),
293 Error::UrlError(_e) => InvalidURL::new_err((p.map(|p| p.to_string()),)),
294 Error::PermissionDenied(name) => PermissionDenied::new_err((pick_path(name),)),
295 Error::PathNotChild => {
296 PathNotChild::new_err((p.map(|p| p.to_string()).unwrap_or_default(), "".to_string()))
297 }
298 Error::UrlutilsError(_e) => InvalidURL::new_err((p.map(|p| p.to_string()),)),
299 Error::Io(e) => e.into(),
300 Error::UnexpectedEof => PyValueError::new_err("Unexpected EOF"),
301 Error::LockContention(name) => LockContention::new_err((name,)),
302 Error::LockFailed(name, error) => LockFailed::new_err((name, error)),
303 Error::NotADirectoryError(name) => NoSuchFile::new_err((pick_path(name),)),
304 Error::IsADirectoryError(name) => ReadError::new_err((pick_path(name), "is a directory")),
305 Error::DirectoryNotEmptyError(name) => DirectoryNotEmpty::new_err((pick_path(name),)),
306 Error::ShortReadvError(path, offset, expected, got) => {
307 ShortReadvError::new_err((path, offset, expected, got))
308 }
309 Error::ResourceBusy(name) => ResourceBusy::new_err((pick_path(name),)),
310 Error::InvalidHttpResponse { path, msg } => InvalidHttpResponse::new_err((path, msg)),
311 Error::UnexpectedHttpStatus { path, code, extra } => {
312 UnexpectedHttpStatus::new_err((path, code, extra))
313 }
314 Error::InvalidHttpRange { path, range, msg } => {
315 InvalidHttpRange::new_err((path, range, msg))
316 }
317 Error::BadHttpRequest { path, reason } => BadHttpRequest::new_err((path, reason)),
318 Error::RedirectRequested {
319 source,
320 target,
321 is_permanent,
322 } => RedirectRequested::new_err((source, target, is_permanent)),
323 Error::UnusableRedirect {
324 source,
325 target,
326 reason,
327 } => UnusableRedirect::new_err((source, target, reason)),
328 Error::ConnectionError(msg) => ConnectionError::new_err((msg,)),
329 }
330 }
331
332 /// Convert a Python mode int to Rust `Option<Permissions>`.
333 ///
334 /// On Unix we translate the int into `Permissions` via `PermissionsExt`.
335 /// On Windows there is no meaningful mapping — Python's own transport layer
336 /// ignores the mode argument there — so we discard it and return `None`.
337 #[cfg(unix)]
338 fn perms_from_py_object(obj: Py<PyAny>) -> Option<Permissions> {
339 Python::attach(|py| {
340 let mode = obj.extract::<u32>(py).ok()?;
341 Some(Permissions::from_mode(mode))
342 })
343 }
344
345 #[cfg(not(unix))]
346 fn perms_from_py_object(_obj: Py<PyAny>) -> Option<Permissions> {
347 None
348 }
349
350 /// Default permissions to apply when Python passes no mode.
351 /// On Unix this mirrors the process umask; on Windows we have nothing
352 /// meaningful to set, so we return `None`.
353 #[cfg(unix)]
354 fn default_perms() -> Option<Permissions> {
355 use nix::sys::stat::{umask, Mode};
356 let mask = umask(Mode::empty());
357 umask(mask);
358 let mode = 0o666 & !mask.bits();
359 Some(Permissions::from_mode(mode as u32))
360 }
361
362 #[cfg(not(unix))]
363 fn default_perms() -> Option<Permissions> {
364 None
365 }
366
367 #[pyclass]
368 struct PyStat {
369 #[pyo3(get)]
370 st_mode: u32,
371
372 #[pyo3(get)]
373 st_size: usize,
374
375 #[pyo3(get)]
376 st_mtime: Option<f64>,
377 }
378
379 trait BufReadStream: BufRead + Seek {}
380
381 impl BufReadStream for BufReader<Box<dyn ReadStream + Sync + Send>> {}
382
383 #[pyclass]
384 struct PyBufReadStream {
385 f: Box<dyn BufReadStream + Sync + Send>,
386 path: PathBuf,
387 }
388
389 #[pyclass]
390 struct PyWriteStream(Option<Box<dyn WriteStream + Sync + Send>>);
391
392 impl PyWriteStream {
393 fn inner_mut(&mut self) -> PyResult<&mut (dyn WriteStream + Sync + Send)> {
394 match self.0.as_deref_mut() {
395 Some(s) => Ok(s),
396 None => Err(pyo3::exceptions::PyValueError::new_err(
397 "I/O operation on closed file",
398 )),
399 }
400 }
401 }
402
403 #[pymethods]
404 impl PyWriteStream {
405 fn write(&mut self, py: Python, data: &[u8]) -> PyResult<usize> {
406 let inner = self.inner_mut()?;
407 py.detach(|| inner.write(data)).map_err(|e| e.into())
408 }
409
410 #[pyo3(signature = (want_fdatasync=None))]
411 fn close(&mut self, py: Python, want_fdatasync: Option<bool>) -> PyResult<()> {
412 if want_fdatasync.unwrap_or(false) {
413 if let Err(err) = self.fdatasync(py) {
414 if !err.is_instance_of::<TransportNotPossible>(py) {
415 return Err(err);
416 }
417 }
418 }
419 // Drop the underlying writer so its file descriptor is released
420 // immediately — Python's FileStream.close() contract promises
421 // the file is no longer in use after this returns.
422 self.0 = None;
423 Ok(())
424 }
425
426 fn fdatasync(&mut self, py: Python) -> PyResult<()> {
427 let inner = self.inner_mut()?;
428 py.detach(|| inner.sync_data()).map_err(|e| e.into())
429 }
430
431 fn __enter__(slf: PyRef<Self>) -> Py<Self> {
432 slf.into()
433 }
434
435 fn __exit__(
436 &mut self,
437 py: Python<'_>,
438 _exc_type: Option<&Bound<PyType>>,
439 _exc_val: Option<&Bound<PyAny>>,
440 _exc_tb: Option<&Bound<PyAny>>,
441 ) -> PyResult<bool> {
442 self.close(py, None)?;
443 Ok(false)
444 }
445
446 fn flush(&mut self, py: Python) -> PyResult<()> {
447 let inner = self.inner_mut()?;
448 py.detach(|| inner.flush()).map_err(|e| e.into())
449 }
450
451 fn writelines(&mut self, py: Python, lines: &Bound<PyList>) -> PyResult<()> {
452 for line in lines.iter() {
453 self.write(py, line.extract::<&[u8]>().unwrap())?;
454 }
455 Ok(())
456 }
457 }
458
459 impl PyBufReadStream {
460 fn new(read: Box<dyn ReadStream + Sync + Send>, path: &Path) -> Self {
461 Self {
462 f: Box::new(BufReader::new(read)),
463 path: path.to_path_buf(),
464 }
465 }
466
467 fn map_io_err_to_py_err(&self, e: std::io::Error) -> PyErr {
468 let transport_err =
469 dromedary::map_io_err_to_transport_err(e, Some(&self.path.as_path().to_string_lossy()));
470 map_transport_err_to_py_err(
471 transport_err,
472 None,
473 Some(self.path.as_path().to_string_lossy().as_ref()),
474 )
475 }
476 }
477
478 #[pymethods]
479 impl PyBufReadStream {
480 #[pyo3(signature = (size=None))]
481 fn read<'a>(&mut self, py: Python<'a>, size: Option<usize>) -> PyResult<Bound<'a, PyBytes>> {
482 if let Some(size) = size {
483 let mut buf = vec![0; size];
484 let ret = py
485 .detach(|| self.f.read(&mut buf))
486 .map_err(|e| self.map_io_err_to_py_err(e))?;
487 Ok(PyBytes::new(py, &buf[..ret]))
488 } else {
489 let mut buf = Vec::new();
490 py.detach(|| self.f.read_to_end(&mut buf))
491 .map_err(|e| self.map_io_err_to_py_err(e))?;
492 Ok(PyBytes::new(py, &buf))
493 }
494 }
495
496 fn seekable(&self) -> bool {
497 true
498 }
499
500 #[pyo3(signature = (offset, whence=None))]
501 fn seek(&mut self, py: Python, offset: i64, whence: Option<i8>) -> PyResult<u64> {
502 let seekfrom = match whence.unwrap_or(0) {
503 0 => std::io::SeekFrom::Start(offset as u64),
504 1 => std::io::SeekFrom::Current(offset),
505 2 => std::io::SeekFrom::End(offset),
506 _ => return Err(PyValueError::new_err("Invalid whence")),
507 };
508
509 py.detach(|| self.f.seek(seekfrom))
510 .map_err(|e| self.map_io_err_to_py_err(e))
511 }
512
513 fn tell(&mut self, py: Python) -> PyResult<u64> {
514 py.detach(|| self.f.stream_position())
515 .map_err(|e| self.map_io_err_to_py_err(e))
516 }
517
518 fn readline<'a>(&mut self, py: Python<'a>) -> PyResult<Bound<'a, PyBytes>> {
519 let mut buf = vec![];
520 let ret = py
521 .detach(|| self.f.read_until(b'\n', &mut buf))
522 .map_err(|e| self.map_io_err_to_py_err(e))?;
523 buf.truncate(ret);
524 Ok(PyBytes::new(py, &buf))
525 }
526
527 fn __iter__(slf: PyRef<Self>) -> Py<Self> {
528 slf.into()
529 }
530
531 fn __next__<'a>(&mut self, py: Python<'a>) -> PyResult<Option<Bound<'a, PyBytes>>> {
532 let mut buf = vec![];
533 let ret = py
534 .detach(|| self.f.read_until(b'\n', &mut buf))
535 .map_err(|e| self.map_io_err_to_py_err(e))?;
536 if ret == 0 {
537 return Ok(None);
538 }
539 buf.truncate(ret);
540 Ok(Some(PyBytes::new(py, &buf)))
541 }
542
543 fn close(&mut self) -> PyResult<()> {
544 Ok(())
545 }
546
547 fn __enter__(slf: PyRef<Self>) -> Py<Self> {
548 slf.into()
549 }
550
551 fn __exit__(
552 &self,
553 _exc_type: Option<&Bound<PyType>>,
554 _exc_val: Option<&Bound<PyAny>>,
555 _exc_tb: Option<&Bound<PyAny>>,
556 ) -> PyResult<bool> {
557 Ok(false)
558 }
559
560 fn readlines<'a>(&mut self, py: Python<'a>) -> PyResult<Bound<'a, PyList>> {
561 let ret = PyList::empty(py);
562 while let Some(line) = self.__next__(py)? {
563 ret.append(line)?;
564 }
565 Ok(ret)
566 }
567 }
568
569 impl Transport {
570 fn map_to_py_err(slf: PyRef<Self>, py: Python, e: Error, p: Option<&str>) -> PyErr {
571 let obj = slf.into_pyobject(py).unwrap();
572 map_transport_err_to_py_err(e, Some(obj.into()), p)
573 }
574 }
575
576 #[pymethods]
577 impl Transport {
578 fn external_url(slf: PyRef<Self>, py: Python) -> PyResult<String> {
579 match slf.0.external_url() {
580 Ok(url) => Ok(url.to_string()),
581 Err(e) => Err(Self::map_to_py_err(slf, py, e, None)),
582 }
583 }
584
585 fn __repr__(&self) -> PyResult<String> {
586 Ok(format!("{:?}", self.0))
587 }
588
589 /// Coalesce a list of `(start, length)` offsets into the
590 /// fewest number of reads that still covers every byte of the
591 /// originals, returning `_CoalescedOffset`-shaped tuples.
592 ///
593 /// Historically lived on the Python `Transport` base class. Breezy
594 /// reaches into it from `transport/remote.py` and from a few
595 /// HTTP tests, so we expose it as a staticmethod on the Rust
596 /// base pyclass too. Keep the signature (name and arg order)
597 /// bit-compatible with the Python original — callers pass 0 for
598 /// "no limit" rather than None.
599 #[staticmethod]
600 #[pyo3(signature = (offsets, limit=None, fudge_factor=None, max_size=None))]
601 fn _coalesce_offsets(
602 py: Python,
603 offsets: Vec<(usize, usize)>,
604 limit: Option<usize>,
605 fudge_factor: Option<usize>,
606 max_size: Option<usize>,
607 ) -> PyResult<Py<PyAny>> {
608 let raw = coalesce_offsets(offsets, limit, fudge_factor, max_size)?;
609 // The Python version returns `_CoalescedOffset` namedtuples
610 // (defined in `dromedary.__init__`); wrap each raw tuple so
611 // callers that use attribute access (`coal.start`,
612 // `coal.length`, `coal.ranges`) keep working.
613 let module = py.import("dromedary")?;
614 let cls = module.getattr("_CoalescedOffset")?;
615 let out = pyo3::types::PyList::empty(py);
616 for (start, length, ranges) in raw {
617 let tuple = cls.call1((start, length, ranges))?;
618 out.append(tuple)?;
619 }
620 Ok(out.into())
621 }
622
623 fn get_bytes<'a>(
624 slf: Bound<'a, Self>,
625 py: Python<'a>,
626 path: &'a str,
627 ) -> PyResult<Bound<'a, PyBytes>> {
628 let t = &slf.borrow().0;
629 let ret = py.detach(|| t.get_bytes(path)).map_err(|e| match e {
630 Error::IsADirectoryError(_) => {
631 ReadError::new_err((path.to_string(), "Is a directory".to_string()))
632 }
633 Error::NotADirectoryError(_) => {
634 NoSuchFile::new_err((path.to_string(), "Not a directory".to_string()))
635 }
636 e => {
637 let obj = slf.unbind().into_any();
638 map_transport_err_to_py_err(e, Some(obj), Some(path))
639 }
640 })?;
641
642 Ok(PyBytes::new(py, &ret))
643 }
644
645 #[getter]
646 fn base(&self) -> PyResult<String> {
647 Ok(self.0.base().to_string())
648 }
649
650 fn has(&self, py: Python, path: &str) -> PyResult<bool> {
651 py.detach(|| self.0.has(path))
652 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
653 }
654
655 fn has_any(&self, py: Python, paths: Vec<String>) -> PyResult<bool> {
656 let paths = paths.iter().map(|p| p.as_str()).collect::<Vec<_>>();
657 py.detach(|| self.0.has_any(paths.as_slice()))
658 .map_err(|e| map_transport_err_to_py_err(e, None, None))
659 }
660
661 #[pyo3(signature = (path, mode=None))]
662 fn mkdir(slf: &Bound<Self>, py: Python, path: &str, mode: Option<Py<PyAny>>) -> PyResult<()> {
663 let mode = mode.and_then(perms_from_py_object);
664 let t = &slf.borrow().0;
665 py.detach(|| t.mkdir(path, mode)).map_err(|e| {
666 let obj = slf.clone().unbind().into();
667 map_transport_err_to_py_err(e, Some(obj), Some(path))
668 })?;
669 Ok(())
670 }
671
672 #[pyo3(signature = (mode=None))]
673 fn ensure_base(&self, py: Python, mode: Option<Py<PyAny>>) -> PyResult<bool> {
674 let mode = mode.and_then(perms_from_py_object);
675 py.detach(|| self.0.ensure_base(mode))
676 .map_err(|e| map_transport_err_to_py_err(e, None, None))
677 }
678
679 fn local_abspath(&self, py: Python, path: &str) -> PyResult<String> {
680 let path = py
681 .detach(|| self.0.local_abspath(path))
682 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))?;
683
684 path.to_str()
685 .map(|s| s.to_string())
686 .ok_or_else(|| PyValueError::new_err(format!("Invalid path: {}", path.display())))
687 }
688
689 fn get<'a>(
690 slf: PyRef<'a, Self>,
691 py: Python<'a>,
692 path: &'a str,
693 ) -> PyResult<Bound<'a, PyBufReadStream>> {
694 let t = &slf.0;
695 let ret = py.detach(|| t.get(path)).map_err(|e| match e {
696 Error::IsADirectoryError(_) => {
697 ReadError::new_err((path.to_string(), "Is a directory".to_string()))
698 }
699 Error::NotADirectoryError(_) => {
700 NoSuchFile::new_err((path.to_string(), "Not a directory".to_string()))
701 }
702 e => {
703 let obj = slf.into_pyobject(py).unwrap().unbind().into_any();
704 map_transport_err_to_py_err(e, Some(obj), Some(path))
705 }
706 })?;
707 Bound::new(py, PyBufReadStream::new(ret, Path::new(path)))
708 }
709
710 fn stat<'a>(&self, py: Python<'a>, path: &str) -> PyResult<Bound<'a, PyStat>> {
711 let t = &self.0;
712 let stat = py
713 .detach(|| t.stat(path))
714 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))?;
715 // On Unix we report the real mode bits; on Windows the `Stat` struct
716 // carries no mode (see `project_windows_port.md`) so we synthesise one
717 // from the file kind, mirroring what Python's own `os.stat_result`
718 // exposes on Windows.
719 #[cfg(unix)]
720 let st_mode = stat.mode;
721 #[cfg(not(unix))]
722 let st_mode = {
723 use dromedary::FileKind;
724 const S_IFDIR: u32 = 0o040000;
725 const S_IFREG: u32 = 0o100000;
726 const S_IFLNK: u32 = 0o120000;
727 let kind_bits = match stat.kind {
728 FileKind::Dir => S_IFDIR,
729 FileKind::File => S_IFREG,
730 FileKind::Symlink => S_IFLNK,
731 FileKind::Other => 0,
732 };
733 kind_bits | 0o777
734 };
735 Bound::new(
736 py,
737 PyStat {
738 st_size: stat.size,
739 st_mode,
740 st_mtime: stat.mtime,
741 },
742 )
743 }
744
745 #[pyo3(signature = (path=None))]
746 fn relpath(&self, path: Option<&str>) -> PyResult<String> {
747 let path = path.unwrap_or(".");
748 let url = Url::parse(path).map_err(|_| PyValueError::new_err((path.to_string(),)))?;
749 self.0
750 .relpath(&url)
751 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
752 }
753
754 fn abspath(&self, path: &str) -> PyResult<String> {
755 Ok(self
756 .0
757 .abspath(path)
758 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))?
759 .to_string())
760 }
761
762 #[pyo3(signature = (path, data, mode=None))]
763 fn put_bytes(
764 slf: &Bound<Self>,
765 py: Python,
766 path: &str,
767 data: &[u8],
768 mode: Option<Py<PyAny>>,
769 ) -> PyResult<()> {
770 let mode = mode.and_then(perms_from_py_object).or_else(default_perms);
771 let t = &slf.borrow().0;
772 py.detach(|| t.put_bytes(path, data, mode)).map_err(|e| {
773 let obj = slf.clone().unbind().into();
774 map_transport_err_to_py_err(e, Some(obj), Some(path))
775 })?;
776 Ok(())
777 }
778
779 #[pyo3(signature = (path, data, mode=None, create_parent_dir=None, dir_mode=None))]
780 fn put_bytes_non_atomic(
781 slf: &Bound<Self>,
782 py: Python,
783 path: &str,
784 data: &[u8],
785 mode: Option<Py<PyAny>>,
786 create_parent_dir: Option<bool>,
787 dir_mode: Option<Py<PyAny>>,
788 ) -> PyResult<()> {
789 let t = &slf.borrow().0;
790
791 py.detach(|| {
792 t.put_bytes_non_atomic(
793 path,
794 data,
795 mode.and_then(perms_from_py_object).or_else(default_perms),
796 create_parent_dir,
797 dir_mode.and_then(perms_from_py_object),
798 )
799 })
800 .map_err(|e| {
801 let obj = slf.clone().unbind().into();
802 map_transport_err_to_py_err(e, Some(obj), Some(path))
803 })?;
804 Ok(())
805 }
806
807 #[pyo3(signature = (path, file, mode=None))]
808 fn put_file(
809 slf: &Bound<Self>,
810 py: Python,
811 path: &str,
812 file: Py<PyAny>,
813 mode: Option<Py<PyAny>>,
814 ) -> PyResult<u64> {
815 let t = &slf.borrow().0;
816 let mut file = PyBinaryFile::from(file);
817 let ret = py
818 .detach(|| {
819 t.put_file(
820 path,
821 &mut file,
822 mode.and_then(perms_from_py_object).or_else(default_perms),
823 )
824 })
825 .map_err(|e| {
826 let obj = slf.clone().unbind().into();
827 map_transport_err_to_py_err(e, Some(obj), Some(path))
828 })?;
829 Ok(ret)
830 }
831
832 #[pyo3(signature = (path, file, mode=None, create_parent_dir=None, dir_mode=None))]
833 fn put_file_non_atomic(
834 slf: &Bound<Self>,
835 py: Python,
836 path: &str,
837 file: Py<PyAny>,
838 mode: Option<Py<PyAny>>,
839 create_parent_dir: Option<bool>,
840 dir_mode: Option<Py<PyAny>>,
841 ) -> PyResult<()> {
842 let t = &slf.borrow().0;
843 let mut file = PyBinaryFile::from(file);
844 py.detach(|| {
845 t.put_file_non_atomic(
846 path,
847 &mut file,
848 mode.and_then(perms_from_py_object).or_else(default_perms),
849 create_parent_dir,
850 dir_mode.and_then(perms_from_py_object),
851 )
852 })
853 .map_err(|e| {
854 let obj = slf.clone().unbind().into();
855 map_transport_err_to_py_err(e, Some(obj), Some(path))
856 })?;
857 Ok(())
858 }
859
860 fn delete(&self, py: Python, path: &str) -> PyResult<()> {
861 let t = &self.0;
862 py.detach(|| t.delete(path))
863 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))?;
864 Ok(())
865 }
866
867 fn rmdir(&self, py: Python, path: &str) -> PyResult<()> {
868 let t = &self.0;
869
870 py.detach(|| t.rmdir(path))
871 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))?;
872 Ok(())
873 }
874
875 fn rename(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
876 let t = &self.0;
877
878 py.detach(|| t.rename(from, to))
879 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))?;
880 Ok(())
881 }
882
883 #[pyo3(signature = (name, value=None))]
884 fn set_segment_parameter(
885 &mut self,
886 py: Python,
887 name: &str,
888 value: Option<&str>,
889 ) -> PyResult<()> {
890 py.detach(|| self.0.set_segment_parameter(name, value))
891 .map_err(|e| map_transport_err_to_py_err(e, None, None))?;
892 Ok(())
893 }
894
895 fn get_segment_parameters(&self, py: Python) -> PyResult<HashMap<String, String>> {
896 let t = &self.0;
897
898 py.detach(|| t.get_segment_parameters())
899 .map_err(|e| map_transport_err_to_py_err(e, None, None))
900 }
901
902 #[pyo3(signature = (mode=None))]
903 fn create_prefix(&self, py: Python, mode: Option<Py<PyAny>>) -> PyResult<()> {
904 let t = &self.0;
905
906 py.detach(|| t.create_prefix(mode.and_then(perms_from_py_object)))
907 .map_err(|e| map_transport_err_to_py_err(e, None, None))
908 }
909
910 fn lock_write(&self, py: Python, path: &str) -> PyResult<Lock> {
911 let t = &self.0;
912
913 py.detach(|| t.lock_write(path))
914 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
915 .map(Lock::from)
916 }
917
918 fn lock_read(&self, py: Python, path: &str) -> PyResult<Lock> {
919 let t = &self.0;
920
921 py.detach(|| t.lock_read(path))
922 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
923 .map(Lock::from)
924 }
925
926 fn recommended_page_size(&self, py: Python) -> usize {
927 py.detach(|| self.0.recommended_page_size())
928 }
929
930 fn is_readonly(&self, py: Python) -> bool {
931 py.detach(|| self.0.is_readonly())
932 }
933
934 #[pyo3(signature = (path, offsets, max_readv_combine=None, bytes_to_read_before_seek=None))]
935 fn _readv<'a>(
936 slf: &Bound<'a, Self>,
937 py: Python<'a>,
938 path: &str,
939 offsets: Vec<(usize, usize)>,
940 max_readv_combine: Option<usize>,
941 bytes_to_read_before_seek: Option<usize>,
942 ) -> PyResult<Bound<'a, PyAny>> {
943 if offsets.is_empty() {
944 return Ok(PyList::empty(py).into_any());
945 }
946 let t = &slf.borrow().0;
947 let ret = py.detach(|| t.get(path)).map_err(|e| match e {
948 Error::IsADirectoryError(_) => {
949 ReadError::new_err((path.to_string(), "Is a directory".to_string()))
950 }
951 Error::NotADirectoryError(_) => {
952 ReadError::new_err((path.to_string(), "Not a directory".to_string()))
953 }
954 e => {
955 let obj = slf.clone().unbind().into();
956 map_transport_err_to_py_err(e, Some(obj), Some(path))
957 }
958 })?;
959 let f = Bound::new(py, PyBufReadStream::new(ret, Path::new(path)))?;
960 let buffered = seek_and_read(
961 py,
962 f.into_any(),
963 offsets,
964 max_readv_combine,
965 bytes_to_read_before_seek,
966 Some(path),
967 )?;
968 let list = PyList::new(py, &buffered)?;
969 Ok(PyIterator::from_object(&list.into_any())?.into_any())
970 }
971
972 #[pyo3(signature = (path, offsets, adjust_for_latency=None, upper_limit=None))]
973 fn readv<'a>(
974 slf: PyRef<'a, Self>,
975 py: Python<'a>,
976 path: String,
977 offsets: Vec<(u64, usize)>,
978 adjust_for_latency: Option<bool>,
979 upper_limit: Option<u64>,
980 ) -> PyResult<Py<ReadvIter>> {
981 // Construct the Rust iterator up front — that step only
982 // does coalescing, no HTTP, so running it with the GIL
983 // held is fine. The returned iterator borrows the
984 // transport's `dyn TransportTrait` but our HttpTransport
985 // readv constructs a LazyReadv that owns its state (no
986 // borrow of `self`); promote to `'static` via transmute
987 // and keep the parent transport alive via a Python
988 // reference held inside `ReadvIter`. Subsequent `__next__`
989 // calls then pull elements under `py.detach` so blocking
990 // HTTP work doesn't hold the GIL.
991 let boxed: Box<dyn Iterator<Item = _> + Send + '_> = slf.0.readv(
992 &path,
993 offsets,
994 adjust_for_latency.unwrap_or(false),
995 upper_limit,
996 );
997 let mut iter: Box<dyn Iterator<Item = Result<(u64, Vec<u8>), dromedary::Error>> + Send> = unsafe {
998 std::mem::transmute::<
999 Box<dyn Iterator<Item = _> + Send + '_>,
1000 Box<dyn Iterator<Item = _> + Send + 'static>,
1001 >(boxed)
1002 };
1003 // Peek the first element synchronously so errors that the
1004 // transport raises up-front (NoSuchFile for a missing
1005 // file, PermissionDenied, &c) surface from the `readv()`
1006 // *call* itself, not from the first `__next__` on the
1007 // returned iterator. Python's Transport.readv contract
1008 // historically raised there — breezy's pack-repo autopack
1009 // (see `test_autopack_reloads_and_stops`) catches those
1010 // around `make_readv_reader` construction to translate
1011 // deleted-pack races into RetryWithNewPacks.
1012 let first = py.detach(|| iter.next());
1013 if let Some(Err(e)) = first {
1014 return Err(map_transport_err_to_py_err(e, None, Some(&path)));
1015 }
1016 let prefixed: Box<dyn Iterator<Item = Result<(u64, Vec<u8>), dromedary::Error>> + Send> =
1017 Box::new(first.into_iter().chain(iter));
1018 Py::new(
1019 py,
1020 ReadvIter {
1021 parent: slf.into_pyobject(py)?.unbind(),
1022 iter: Mutex::new(Some(prefixed)),
1023 path,
1024 },
1025 )
1026 }
1027
1028 fn listable(&self, py: Python) -> bool {
1029 py.detach(|| self.0.listable())
1030 }
1031
1032 fn list_dir(&self, py: Python, path: &str) -> PyResult<Vec<String>> {
1033 py.detach(|| {
1034 self.0
1035 .list_dir(path)
1036 .map(|r| r.map_err(|e| map_transport_err_to_py_err(e, None, Some(path))))
1037 .collect::<PyResult<Vec<_>>>()
1038 })
1039 }
1040
1041 #[pyo3(signature = (path, bytes, mode=None))]
1042 fn append_bytes(
1043 &self,
1044 py: Python,
1045 path: &str,
1046 bytes: &[u8],
1047 mode: Option<Py<PyAny>>,
1048 ) -> PyResult<u64> {
1049 let mode = mode.and_then(perms_from_py_object);
1050 py.detach(|| self.0.append_bytes(path, bytes, mode))
1051 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
1052 }
1053
1054 #[pyo3(signature = (path, file, mode=None))]
1055 fn append_file(
1056 &self,
1057 py: Python,
1058 path: &str,
1059 file: Py<PyAny>,
1060 mode: Option<Py<PyAny>>,
1061 ) -> PyResult<u64> {
1062 let mut file = PyBinaryFile::from(file);
1063 let mode = mode.and_then(perms_from_py_object);
1064 py.detach(|| self.0.append_file(path, &mut file, mode))
1065 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
1066 }
1067
1068 fn iter_files_recursive<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyList>> {
1069 self.0
1070 .iter_files_recursive()
1071 .map(|r| {
1072 r.map_err(|e| map_transport_err_to_py_err(e, None, Some(".")))
1073 .map(|o| o.to_string())
1074 })
1075 .collect::<PyResult<Vec<_>>>()
1076 .and_then(move |v| PyList::new(py, &v))
1077 }
1078
1079 #[pyo3(signature = (path, mode=None))]
1080 fn open_write_stream(
1081 slf: &Bound<Self>,
1082 py: Python,
1083 path: &str,
1084 mode: Option<Py<PyAny>>,
1085 ) -> PyResult<PyWriteStream> {
1086 let t = &slf.borrow().0;
1087 py.detach(|| t.open_write_stream(path, mode.and_then(perms_from_py_object)))
1088 .map_err(|e| Transport::map_to_py_err(slf.borrow(), py, e, Some(path)))
1089 .map(|w| PyWriteStream(Some(w)))
1090 }
1091
1092 fn delete_tree(&self, py: Python, path: &str) -> PyResult<()> {
1093 py.detach(|| self.0.delete_tree(path))
1094 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
1095 }
1096
1097 fn r#move(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
1098 py.detach(|| self.0.r#move(from, to))
1099 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))
1100 }
1101
1102 fn copy_tree(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
1103 py.detach(|| self.0.copy_tree(from, to))
1104 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))
1105 }
1106
1107 fn copy_tree_to_transport(&self, py: Python, to_transport: Py<PyAny>) -> PyResult<()> {
1108 if let Ok(t) = to_transport.clone_ref(py).extract::<PyRef<Transport>>(py) {
1109 let t = t.0.as_ref();
1110 py.detach(|| self.0.copy_tree_to_transport(t))
1111 .map_err(|e| map_transport_err_to_py_err(e, None, Some(".")))
1112 } else {
1113 let t = Box::new(dromedary::pyo3::PyTransport::from(to_transport));
1114 py.detach(|| self.0.copy_tree_to_transport(t.as_ref()))
1115 .map_err(|e| map_transport_err_to_py_err(e, None, Some(".")))
1116 }
1117 }
1118
1119 fn hardlink(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
1120 py.detach(|| self.0.hardlink(from, to))
1121 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))
1122 }
1123
1124 fn symlink(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
1125 py.detach(|| self.0.symlink(from, to))
1126 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))
1127 }
1128
1129 fn readlink(&self, py: Python, path: &str) -> PyResult<String> {
1130 py.detach(|| self.0.readlink(path))
1131 .map_err(|e| map_transport_err_to_py_err(e, None, Some(path)))
1132 }
1133
1134 #[pyo3(signature = (relpaths, to_transport, mode=None))]
1135 fn copy_to(
1136 &self,
1137 py: Python,
1138 relpaths: Py<PyAny>,
1139 to_transport: Py<PyAny>,
1140 mode: Option<Py<PyAny>>,
1141 ) -> PyResult<usize> {
1142 let relpaths = relpaths
1143 .bind(py)
1144 .try_iter()?
1145 .map(|o| o?.extract::<String>())
1146 .collect::<PyResult<Vec<_>>>()?;
1147
1148 let relpaths_ref = relpaths.iter().map(|s| s.as_str()).collect::<Vec<_>>();
1149
1150 if let Ok(t) = to_transport.clone_ref(py).cast_bound::<Transport>(py) {
1151 let t = &t.borrow().0;
1152 py.detach(|| {
1153 self.0.copy_to(
1154 relpaths_ref.as_slice(),
1155 t.as_ref(),
1156 mode.and_then(perms_from_py_object),
1157 )
1158 })
1159 .map_err(|e| map_transport_err_to_py_err(e, None, None))
1160 } else {
1161 let t = Box::new(dromedary::pyo3::PyTransport::from(to_transport));
1162 py.detach(|| {
1163 self.0
1164 .copy_to(
1165 relpaths_ref.as_slice(),
1166 t.as_ref(),
1167 mode.and_then(perms_from_py_object),
1168 )
1169 .map_err(|e| map_transport_err_to_py_err(e, None, None))
1170 })
1171 }
1172 }
1173
1174 fn _can_roundtrip_unix_modebits(&self) -> bool {
1175 self.0.can_roundtrip_unix_modebits()
1176 }
1177
1178 fn copy(&self, py: Python, from: &str, to: &str) -> PyResult<()> {
1179 py.detach(|| self.0.copy(from, to))
1180 .map_err(|e| map_transport_err_to_py_err(e, None, Some(from)))
1181 }
1182 }
1183
1184 #[pyclass]
1185 struct Lock(Box<dyn dromedary::lock::Lock + Send + Sync>);
1186
1187 impl From<Box<dyn dromedary::lock::Lock + Send + Sync>> for Lock {
1188 fn from(lock: Box<dyn dromedary::lock::Lock + Send + Sync>) -> Self {
1189 Lock(lock)
1190 }
1191 }
1192
1193 #[pymethods]
1194 impl Lock {
1195 fn unlock(&mut self) -> PyResult<()> {
1196 self.0.unlock().map_err(map_lock_err_to_py_err)
1197 }
1198 }
1199
1200 #[pyclass(extends=Transport,subclass)]
1201 struct LocalTransport {}
1202
1203 #[pymethods]
1204 impl LocalTransport {
1205 #[new]
1206 fn new(url: &str) -> PyResult<(Self, Transport)> {
1207 Ok((
1208 LocalTransport {},
1209 Transport(Box::new(
1210 dromedary::local::LocalTransport::new(url)
1211 .map_err(|e| map_transport_err_to_py_err(e, None, None))?,
1212 )),
1213 ))
1214 }
1215
1216 #[pyo3(signature = (abspath,))]
1217 #[classmethod]
1218 fn from_abspath<'a>(cls: &'a Bound<'a, PyType>, abspath: &'a str) -> PyResult<Bound<'a, Self>> {
1219 let ret = dromedary::local::LocalTransport::from_abspath(Path::new(abspath))
1220 .map_err(|e| map_transport_err_to_py_err(e, None, Some(abspath)))?;
1221
1222 let init = PyClassInitializer::from(Transport(Box::new(ret)));
1223 let init = init.add_subclass(Self {});
1224 Bound::new(cls.py(), init)
1225 }
1226
1227 #[pyo3(signature = (offset=None))]
1228 fn clone<'a>(
1229 slf: PyRef<'a, Self>,
1230 py: Python<'a>,
1231 offset: Option<Py<PyAny>>,
1232 ) -> PyResult<Bound<'a, LocalTransport>> {
1233 let super_ = slf.as_ref();
1234 let inner = if let Some(offset) = offset {
1235 let offset = offset.extract::<String>(py)?;
1236 super_.0.clone(Some(&offset))
1237 } else {
1238 super_.0.clone(None)
1239 }
1240 .map_err(|e| map_transport_err_to_py_err(e, None, None))?;
1241
1242 let init = PyClassInitializer::from(Transport(inner));
1243 let init = init.add_subclass(Self {});
1244 Bound::new(py, init)
1245 }
1246 }
1247
1248 #[pyfunction]
1249 fn get_test_permutations(py: Python) -> PyResult<Bound<PyList>> {
1250 let test_server_module = py.import("dromedary.tests.test_server")?;
1251 let local_url_server = test_server_module.getattr("LocalURLServer")?;
1252 let local_transport = py.import("dromedary.local")?.getattr("LocalTransport")?;
1253 let ret = PyList::empty(py);
1254 ret.append((local_transport, local_url_server))?;
1255 Ok(ret)
1256 }
1257
1258 #[pyfunction]
1259 #[pyo3(signature = (offsets, limit=None, fudge_factor=None, max_size=None))]
1260 fn coalesce_offsets(
1261 offsets: Vec<(usize, usize)>,
1262 mut limit: Option<usize>,
1263 mut fudge_factor: Option<usize>,
1264 mut max_size: Option<usize>,
1265 ) -> PyResult<Vec<(usize, usize, Vec<(usize, usize)>)>> {
1266 if limit == Some(0) {
1267 limit = None;
1268 }
1269 if fudge_factor == Some(0) {
1270 fudge_factor = None;
1271 }
1272 if max_size == Some(0) {
1273 max_size = None;
1274 }
1275 dromedary::readv::coalesce_offsets(offsets.as_slice(), limit, fudge_factor, max_size)
1276 .map_err(|e| PyValueError::new_err(format!("{}", e)))
1277 }
1278
1279 const DEFAULT_MAX_READV_COMBINE: usize = 50;
1280 const DEFAULT_BYTES_TO_READ_BEFORE_SEEK: usize = 0;
1281
1282 #[pyfunction]
1283 #[pyo3(signature = (file, offsets, max_readv_combine=None, bytes_to_read_before_seek=None, path=None))]
1284 fn seek_and_read(
1285 py: Python,
1286 file: Bound<PyAny>,
1287 offsets: Vec<(usize, usize)>,
1288 max_readv_combine: Option<usize>,
1289 bytes_to_read_before_seek: Option<usize>,
1290 path: Option<&str>,
1291 ) -> PyResult<Vec<(usize, Py<PyAny>)>> {
1292 let f = PyBinaryFile::from(file);
1293 let mut data = py
1294 .detach(|| {
1295 dromedary::readv::seek_and_read(
1296 f,
1297 offsets,
1298 max_readv_combine.unwrap_or(DEFAULT_MAX_READV_COMBINE),
1299 bytes_to_read_before_seek.unwrap_or(DEFAULT_BYTES_TO_READ_BEFORE_SEEK),
1300 )
1301 })
1302 .map_err(|e| -> PyErr { e.into() })?;
1303
1304 std::iter::from_fn(move || py.detach(|| data.next()))
1305 .map(|e| {
1306 e.map(|(offset, data)| (offset, PyBytes::new(py, data.as_slice()).into()))
1307 .map_err(|(e, offset, length, actual)| match e.kind() {
1308 std::io::ErrorKind::UnexpectedEof => ShortReadvError::new_err((
1309 path.map(|p| p.to_string()),
1310 offset,
1311 length,
1312 actual,
1313 )),
1314 _ => e.into(),
1315 })
1316 })
1317 .collect::<PyResult<Vec<_>>>()
1318 }
1319
1320 #[pyfunction]
1321 #[pyo3(signature = (offsets, upper_limit=None, recommended_page_size=None))]
1322 fn sort_expand_and_combine(
1323 offsets: Vec<(u64, usize)>,
1324 upper_limit: Option<u64>,
1325 recommended_page_size: Option<usize>,
1326 ) -> Vec<(u64, usize)> {
1327 dromedary::readv::sort_expand_and_combine(
1328 offsets,
1329 upper_limit,
1330 recommended_page_size.unwrap_or(4 * 1024),
1331 )
1332 }
1333
1334 #[pyclass]
1335 struct PyFile(BufReader<Box<std::fs::File>>);
1336
1337 impl PyFile {
1338 fn new(f: Box<std::fs::File>, _path: &Path) -> Self {
1339 Self(BufReader::new(f))
1340 }
1341 }
1342
1343 #[pymethods]
1344 impl PyFile {
1345 fn seekable(&self) -> bool {
1346 true
1347 }
1348
1349 #[pyo3(signature = (size=None))]
1350 fn read<'a>(&mut self, py: Python<'a>, size: Option<usize>) -> PyResult<Bound<'a, PyBytes>> {
1351 if let Some(size) = size {
1352 let mut buf = vec![0; size];
1353 let ret = py
1354 .detach(|| self.0.read(&mut buf))
1355 .map_err(|e| -> PyErr { e.into() })?;
1356 Ok(PyBytes::new(py, &buf[..ret]))
1357 } else {
1358 let mut buf = Vec::new();
1359 py.detach(|| self.0.read_to_end(&mut buf))
1360 .map_err(|e| -> PyErr { e.into() })?;
1361 Ok(PyBytes::new(py, &buf))
1362 }
1363 }
1364
1365 fn write(&mut self, py: Python, data: &[u8]) -> PyResult<usize> {
1366 py.detach(|| self.0.get_mut().write(data))
1367 .map_err(|e| e.into())
1368 }
1369
1370 fn readline<'a>(&mut self, py: Python<'a>) -> PyResult<Bound<'a, PyBytes>> {
1371 let mut buf = vec![];
1372 let ret = py.detach(|| self.0.read_until(b'\n', &mut buf))?;
1373 buf.truncate(ret);
1374 Ok(PyBytes::new(py, &buf))
1375 }
1376
1377 fn __iter__(slf: PyRef<Self>) -> Py<Self> {
1378 slf.into()
1379 }
1380
1381 fn __next__<'a>(&mut self, py: Python<'a>) -> PyResult<Option<Bound<'a, PyBytes>>> {
1382 let mut buf = vec![];
1383 let ret = py
1384 .detach(|| self.0.read_until(b'\n', &mut buf))
1385 .map_err(|e| -> PyErr { e.into() })?;
1386 if ret == 0 {
1387 return Ok(None);
1388 }
1389 buf.truncate(ret);
1390 Ok(Some(PyBytes::new(py, &buf)))
1391 }
1392
1393 fn readlines<'a>(&mut self, py: Python<'a>) -> PyResult<Bound<'a, PyList>> {
1394 let ret = PyList::empty(py);
1395 while let Some(line) = self.__next__(py)? {
1396 ret.append(line)?;
1397 }
1398 Ok(ret)
1399 }
1400
1401 #[pyo3(signature = (offset, whence=None))]
1402 fn seek(&mut self, offset: i64, whence: Option<i8>) -> PyResult<u64> {
1403 let seekfrom = match whence.unwrap_or(0) {
1404 0 => std::io::SeekFrom::Start(offset as u64),
1405 1 => std::io::SeekFrom::Current(offset),
1406 2 => std::io::SeekFrom::End(offset),
1407 _ => return Err(PyValueError::new_err("Invalid whence")),
1408 };
1409
1410 self.0.seek(seekfrom).map_err(|e| e.into())
1411 }
1412
1413 fn tell(&mut self) -> PyResult<u64> {
1414 self.0.stream_position().map_err(|e| e.into())
1415 }
1416
1417 fn __enter__(slf: PyRef<Self>) -> Py<Self> {
1418 slf.into()
1419 }
1420
1421 fn __exit__(
1422 &self,
1423 _exc_type: Option<&Bound<PyType>>,
1424 _exc_val: Option<&Bound<PyAny>>,
1425 _exc_tb: Option<&Bound<PyAny>>,
1426 ) -> PyResult<bool> {
1427 Ok(false)
1428 }
1429
1430 fn flush(&mut self) -> PyResult<()> {
1431 self.0.get_mut().flush().map_err(|e| e.into())
1432 }
1433
1434 fn writelines(&mut self, py: Python, lines: &Bound<PyList>) -> PyResult<()> {
1435 for line in lines.iter() {
1436 self.write(py, line.extract::<&[u8]>()?)?;
1437 }
1438 Ok(())
1439 }
1440
1441 #[pyo3(signature = (size=None))]
1442 fn truncate(&mut self, py: Python, size: Option<u64>) -> PyResult<()> {
1443 let size = size.map_or_else(|| py.detach(|| self.tell()), Ok)?;
1444 py.detach(|| self.0.get_mut().set_len(size))
1445 .map_err(|e| e.into())
1446 }
1447
1448 #[cfg(unix)]
1449 fn fileno(&self, py: Python) -> PyResult<i32> {
1450 use std::os::unix::io::AsRawFd;
1451 Ok(py.detach(|| self.0.get_ref().as_raw_fd()))
1452 }
1453 }
1454
1455 fn map_lock_err_to_py_err(err: LockError) -> PyErr {
1456 match err {
1457 LockError::Contention(p) => LockContention::new_err((p,)),
1458 LockError::Failed(p, w) => LockFailed::new_err((p, w)),
1459 LockError::IoError(e) => e.into(),
1460 }
1461 }
1462
1463 #[pyclass]
1464 struct ReadLock(Option<dromedary::filelock::ReadLock>);
1465
1466 #[pyclass]
1467 struct WriteLock(dromedary::filelock::WriteLock);
1468
1469 #[pymethods]
1470 impl ReadLock {
1471 fn unlock(&mut self) -> PyResult<()> {
1472 if let Some(mut read_lock) = self.0.take() {
1473 read_lock.unlock().map_err(map_lock_err_to_py_err)
1474 } else {
1475 debug!("ReadLock already unlocked");
1476 Ok(())
1477 }
1478 }
1479
1480 #[new]
1481 #[pyo3(signature = (filename, strict_locks=None))]
1482 fn new(filename: PathBuf, strict_locks: Option<bool>) -> PyResult<Self> {
1483 Ok(Self(Some(
1484 dromedary::filelock::ReadLock::new(&filename, strict_locks.unwrap_or(false))
1485 .map_err(map_lock_err_to_py_err)?,
1486 )))
1487 }
1488
1489 fn temporary_write_lock<'a>(
1490 slf: Bound<'a, Self>,
1491 py: Python<'a>,
1492 ) -> PyResult<(bool, Bound<'a, PyAny>)> {
1493 let mut m = slf.borrow_mut();
1494 if let Some(read_lock) = m.0.take() {
1495 match read_lock.temporary_write_lock() {
1496 Ok(twl) => Ok((
1497 true,
1498 Bound::new(py, TemporaryWriteLock(Some(twl)))?.into_any(),
1499 )),
1500 Err((rl, LockError::Contention(_))) => {
1501 m.0 = Some(rl);
1502 Ok((false, slf.into_any()))
1503 }
1504 Err((_rl, LockError::Failed(p, w))) => Err(LockFailed::new_err((p, w))),
1505 Err((_rl, LockError::IoError(e))) => Err(e.into()),
1506 }
1507 } else {
1508 Err(PyRuntimeError::new_err("ReadLock already unlocked"))
1509 }
1510 }
1511
1512 #[getter]
1513 fn f(&self) -> PyResult<PyFile> {
1514 if let Some(read_lock) = &self.0 {
1515 Ok(PyFile::new(read_lock.file()?, read_lock.path()))
1516 } else {
1517 Err(PyRuntimeError::new_err("ReadLock already unlocked"))
1518 }
1519 }
1520 }
1521
1522 #[pyclass]
1523 struct TemporaryWriteLock(Option<dromedary::filelock::TemporaryWriteLock>);
1524
1525 #[pymethods]
1526 impl TemporaryWriteLock {
1527 fn restore_read_lock(&mut self) -> PyResult<ReadLock> {
1528 if let Some(lock) = self.0.take() {
1529 let rl = lock.restore_read_lock();
1530 Ok(ReadLock(Some(rl)))
1531 } else {
1532 Err(PyRuntimeError::new_err(
1533 "TemporaryWriteLock already unlocked",
1534 ))
1535 }
1536 }
1537
1538 #[getter]
1539 fn f(&self) -> PyResult<PyFile> {
1540 if let Some(lock) = &self.0 {
1541 Ok(PyFile::new(lock.file()?, lock.path()))
1542 } else {
1543 Err(PyRuntimeError::new_err(
1544 "TemporaryWriteLock already unlocked",
1545 ))
1546 }
1547 }
1548 }
1549
1550 #[pymethods]
1551 impl WriteLock {
1552 fn unlock(&mut self) -> PyResult<()> {
1553 self.0.unlock().map_err(map_lock_err_to_py_err)
1554 }
1555
1556 #[new]
1557 #[pyo3(signature = (filename, strict_locks=None))]
1558 fn new(filename: PathBuf, strict_locks: Option<bool>) -> PyResult<Self> {
1559 Ok(Self(
1560 dromedary::filelock::WriteLock::new(&filename, strict_locks.unwrap_or(false))
1561 .map_err(map_lock_err_to_py_err)?,
1562 ))
1563 }
1564
1565 #[getter]
1566 fn f(&self) -> PyResult<PyFile> {
1567 Ok(PyFile::new(self.0.file()?, self.0.path()))
1568 }
1569 }
1570
1571 mod brokenrename;
1572 mod fakenfs;
1573 mod fakevfat;
1574 #[cfg(feature = "gio")]
1575 mod gio;
1576 mod http;
1577 mod log;
1578 mod memory;
1579 mod pathfilter;
1580 mod readonly;
1581 mod sftp;
1582 mod ssh;
1583 mod unlistable;
1584 mod urlutils;
1585 #[cfg(feature = "webdav")]
1586 mod webdav;
1587
1588 #[pymodule]
1589 fn _transport_rs(py: Python, m: &Bound<PyModule>) -> PyResult<()> {
1590 m.add_class::<Transport>()?;
1591 m.add_class::<ConnectedTransport>()?;
1592 m.add_class::<ReadvIter>()?;
1593 m.add_class::<TransportDecorator>()?;
1594 let localm = PyModule::new(py, "local")?;
1595 localm.add_class::<LocalTransport>()?;
1596 m.add_submodule(&localm)?;
1597 m.add_class::<ReadLock>()?;
1598 m.add_class::<WriteLock>()?;
1599 m.add_class::<TemporaryWriteLock>()?;
1600 m.add_function(wrap_pyfunction!(get_test_permutations, m)?)?;
1601 m.add_wrapped(wrap_pyfunction!(seek_and_read))?;
1602 m.add_wrapped(wrap_pyfunction!(coalesce_offsets))?;
1603 m.add_wrapped(wrap_pyfunction!(sort_expand_and_combine))?;
1604
1605 let sftpm = PyModule::new(py, "sftp")?;
1606 sftp::_sftp_rs(py, &sftpm)?;
1607 m.add_submodule(&sftpm)?;
1608
1609 let sshm = PyModule::new(py, "ssh")?;
1610 ssh::register(py, &sshm)?;
1611 m.add_submodule(&sshm)?;
1612 m.add_class::<ReadLock>()?;
1613 m.add_class::<WriteLock>()?;
1614 m.add_class::<TemporaryWriteLock>()?;
1615
1616 let urlutilsm = PyModule::new(py, "urlutils")?;
1617 urlutils::_urlutils_rs(py, &urlutilsm)?;
1618 m.add_submodule(&urlutilsm)?;
1619
1620 let unlistablem = PyModule::new(py, "unlistable")?;
1621 unlistable::register(py, &unlistablem)?;
1622 m.add_submodule(&unlistablem)?;
1623
1624 let readonlym = PyModule::new(py, "readonly")?;
1625 readonly::register(py, &readonlym)?;
1626 m.add_submodule(&readonlym)?;
1627
1628 let brokenrenamem = PyModule::new(py, "brokenrename")?;
1629 brokenrename::register(py, &brokenrenamem)?;
1630 m.add_submodule(&brokenrenamem)?;
1631
1632 let fakevfatm = PyModule::new(py, "fakevfat")?;
1633 fakevfat::register(py, &fakevfatm)?;
1634 m.add_submodule(&fakevfatm)?;
1635
1636 let fakenfsm = PyModule::new(py, "fakenfs")?;
1637 fakenfs::register(py, &fakenfsm)?;
1638 m.add_submodule(&fakenfsm)?;
1639
1640 let pathfilterm = PyModule::new(py, "pathfilter")?;
1641 pathfilter::register(py, &pathfilterm)?;
1642 m.add_submodule(&pathfilterm)?;
1643
1644 let memorym = PyModule::new(py, "memory")?;
1645 memory::register(py, &memorym)?;
1646 m.add_submodule(&memorym)?;
1647
1648 let httpm = PyModule::new(py, "http")?;
1649 http::register(py, &httpm)?;
1650 m.add_submodule(&httpm)?;
1651
1652 #[cfg(feature = "webdav")]
1653 let webdavm = {
1654 let webdavm = PyModule::new(py, "webdav")?;
1655 webdav::register(&webdavm)?;
1656 m.add_submodule(&webdavm)?;
1657 webdavm
1658 };
1659
1660 let logm = PyModule::new(py, "log")?;
1661 log::register(py, &logm)?;
1662 m.add_submodule(&logm)?;
1663
1664 #[cfg(feature = "gio")]
1665 let giom = {
1666 let giom = PyModule::new(py, "gio")?;
1667 gio::register(py, &giom)?;
1668 m.add_submodule(&giom)?;
1669 giom
1670 };
1671
1672 // PyO3 submodule hack for proper import support
1673 let sys = py.import("sys")?;
1674 let modules = sys.getattr("modules")?;
1675 let module_name = m.name()?;
1676
1677 // Register submodules in sys.modules for dotted import support
1678 modules.set_item(format!("{}.local", module_name), &localm)?;
1679 modules.set_item(format!("{}.sftp", module_name), &sftpm)?;
1680 modules.set_item(format!("{}.ssh", module_name), &sshm)?;
1681 modules.set_item(format!("{}.urlutils", module_name), &urlutilsm)?;
1682 modules.set_item(format!("{}.unlistable", module_name), &unlistablem)?;
1683 modules.set_item(format!("{}.readonly", module_name), &readonlym)?;
1684 modules.set_item(format!("{}.brokenrename", module_name), &brokenrenamem)?;
1685 modules.set_item(format!("{}.fakevfat", module_name), &fakevfatm)?;
1686 modules.set_item(format!("{}.fakenfs", module_name), &fakenfsm)?;
1687 modules.set_item(format!("{}.pathfilter", module_name), &pathfilterm)?;
1688 modules.set_item(format!("{}.memory", module_name), &memorym)?;
1689 modules.set_item(format!("{}.http", module_name), &httpm)?;
1690 #[cfg(feature = "webdav")]
1691 modules.set_item(format!("{}.webdav", module_name), &webdavm)?;
1692 modules.set_item(format!("{}.log", module_name), &logm)?;
1693 #[cfg(feature = "gio")]
1694 modules.set_item(format!("{}.gio", module_name), &giom)?;
1695
1696 Ok(())
1697 }