Debian Codegraph @

_transport_rs/src/webdav/transport.rs

raw
1 //! Python bindings for `dromedary::webdav::HttpDavTransport`.
2 //!
3 //! Exposes `dromedary._transport_rs.webdav.HttpDavTransport` as a
4 //! pyclass that extends `_transport_rs.http.HttpTransport`. The
5 //! Python `dromedary.webdav.webdav.HttpDavTransport` becomes a
6 //! thin subclass over this, same pattern as HTTP.
7 //!
8 //! Inheritance rationale: WebDAV is "HTTP plus write verbs". By
9 //! extending the HttpTransport pyclass we inherit all its Python
10 //! methods (`request`, `_post`, `_head`, `_range_hint`, etc.)
11 //! unchanged, and only have to implement the DAV-specific verbs.
12 //! The HttpTransport parent holds the underlying HttpTransport
13 //! pointer in its `inner` field; the DAV subclass holds the full
14 //! HttpDavTransport, and the two share the same underlying
15 //! `HttpClient` through `Arc` clones — so auth cache, connection
16 //! pool, and range-hint state are consistent across both layers.
17
18 use std::path::PathBuf;
19 use std::sync::Arc;
20 use std::time::Duration;
21
22 use dromedary::http::client::{HttpClientConfig, NegotiateProvider};
23 use dromedary::http::HttpClient;
24 use dromedary::webdav::HttpDavTransport as RsHttpDavTransport;
25 use pyo3::prelude::*;
26 use pyo3::types::PyBytes;
27
28 use crate::http::client::{PythonCredentialProvider, PythonNegotiateProvider};
29 use crate::http::transport::{
30 http_transport_initializer_with_base, HttpTransport as PyHttpTransport,
31 };
32 use crate::map_transport_err_to_py_err;
33
34 /// Python-bound Rust WebDAV transport.
35 ///
36 /// Constructor mirrors the HTTP pyclass: `HttpDavTransport(base,
37 /// ca_certs=None, disable_verification=False, user_agent=None,
38 /// read_timeout_ms=0)`. The `+webdav` / `+urllib` scheme suffix is
39 /// accepted and stripped.
40 #[pyclass(
41 extends=PyHttpTransport,
42 subclass,
43 module = "dromedary._transport_rs.webdav",
44 )]
45 pub(crate) struct HttpDavTransport {
46 inner: Arc<RsHttpDavTransport>,
47 }
48
49 #[pymethods]
50 impl HttpDavTransport {
51 #[new]
52 #[pyo3(signature = (
53 base,
54 ca_certs=None,
55 disable_verification=false,
56 user_agent=None,
57 read_timeout_ms=0,
58 ))]
59 fn new(
60 base: &str,
61 ca_certs: Option<PathBuf>,
62 disable_verification: bool,
63 user_agent: Option<String>,
64 read_timeout_ms: i64,
65 ) -> PyResult<PyClassInitializer<Self>> {
66 let timeout = if read_timeout_ms > 0 {
67 Some(Duration::from_millis(read_timeout_ms as u64))
68 } else {
69 None
70 };
71 let cfg = HttpClientConfig {
72 ca_certs_path: ca_certs,
73 disable_verification,
74 user_agent,
75 read_timeout: timeout,
76 };
77 let mut client = HttpClient::with_providers(
78 cfg,
79 Box::new(PythonCredentialProvider),
80 Box::new(PythonNegotiateProvider) as Box<dyn NegotiateProvider>,
81 )
82 .map_err(|e| {
83 map_transport_err_to_py_err(
84 dromedary::Error::Io(std::io::Error::other(format!("{}", e))),
85 None,
86 Some(base),
87 )
88 })?;
89 client.set_auth_trace(Some(std::sync::Arc::new(|header: &str| {
90 crate::http::invoke_auth_header_trace(header);
91 })));
92 let rust = RsHttpDavTransport::new(base, Arc::new(client))
93 .map_err(|e| map_transport_err_to_py_err(e, None, Some(base)))?;
94 Ok(dav_transport_initializer(Arc::new(rust)))
95 }
96
97 /// Clone this transport at an optional offset, sharing the
98 /// underlying HttpClient. Returns an instance of the Rust-level
99 /// HttpDavTransport pyclass; Python subclasses override
100 /// `clone()` to rebrand via `_clone_from` (the
101 /// HttpTransport-inherited helper).
102 #[pyo3(signature = (offset=None))]
103 fn clone<'a>(
104 slf: PyRef<'a, Self>,
105 py: Python<'a>,
106 offset: Option<&str>,
107 ) -> PyResult<Bound<'a, HttpDavTransport>> {
108 let cloned = slf
109 .inner
110 .clone_concrete(offset)
111 .map_err(|e| map_transport_err_to_py_err(e, None, offset))?;
112 Bound::new(py, dav_transport_initializer(Arc::new(cloned)))
113 }
114
115 /// Replace this transport's inner state with a clone of
116 /// `source`. Mirrors `HttpTransport._clone_from`
117 /// but cascades down to refresh the DAV layer too, so the
118 /// Python subclass's `clone()` preserves subclass identity
119 /// while still sharing the HttpClient across siblings.
120 fn _clone_from(
121 mut slf: PyRefMut<Self>,
122 py: Python,
123 source: PyRef<HttpDavTransport>,
124 offset: Option<&str>,
125 ) -> PyResult<()> {
126 // When no offset is supplied, share the source's inner Arc
127 // directly — clone_concrete's raw_base/segment-parameter
128 // stripping (matching ConnectedTransport.clone semantics)
129 // is wrong for the ``__init__``-time TLS-config rebuild
130 // path that calls this helper with offset=None.
131 let new_inner = match offset {
132 None => source.inner.clone(),
133 Some(_) => {
134 let cloned = source
135 .inner
136 .clone_concrete(offset)
137 .map_err(|e| map_transport_err_to_py_err(e, None, offset))?;
138 Arc::new(cloned)
139 }
140 };
141 // Refresh every layer's dyn-Transport pointer so calls
142 // through each inheritance level see the cloned state.
143 let dav_box: Box<dyn dromedary::Transport> = Box::new(Clone::clone(&*new_inner));
144 let http_layer = slf.as_super();
145 // Update the HttpTransport parent's own HTTP-transport
146 // pointer so inherited methods (`request`, `_post`, ...) see
147 // the grafted state.
148 http_layer.inner = Arc::new(new_inner.http().clone());
149 let connected_layer = http_layer.as_super();
150 connected_layer.as_super().0 = dav_box;
151 slf.inner = new_inner;
152 let _ = py;
153 Ok(())
154 }
155
156 /// Eagerly-drained GET — returns the full response body as a
157 /// bytes object. Used by the Python subclass's `get()` override
158 /// (the DAV transport uses the inherited `request()` machinery
159 /// and wants the body materialised in one shot).
160 fn _get_bytes<'py>(&self, py: Python<'py>, relpath: &str) -> PyResult<Bound<'py, PyBytes>> {
161 let buf = py
162 .detach(|| -> Result<Vec<u8>, dromedary::Error> {
163 use dromedary::Transport as _;
164 let mut rf = self.inner.get(relpath)?;
165 let mut buf = Vec::new();
166 std::io::Read::read_to_end(&mut rf, &mut buf).map_err(dromedary::Error::Io)?;
167 Ok(buf)
168 })
169 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?;
170 Ok(PyBytes::new(py, &buf))
171 }
172
173 fn has(&self, py: Python, relpath: &str) -> PyResult<bool> {
174 use dromedary::Transport as _;
175 py.detach(|| self.inner.has(relpath))
176 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
177 }
178
179 fn mkdir(&self, py: Python, relpath: &str) -> PyResult<()> {
180 use dromedary::Transport as _;
181 py.detach(|| self.inner.mkdir(relpath, None))
182 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
183 }
184
185 fn rmdir(&self, py: Python, relpath: &str) -> PyResult<()> {
186 use dromedary::Transport as _;
187 py.detach(|| self.inner.rmdir(relpath))
188 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
189 }
190
191 fn rename(&self, py: Python, rel_from: &str, rel_to: &str) -> PyResult<()> {
192 use dromedary::Transport as _;
193 py.detach(|| self.inner.rename(rel_from, rel_to))
194 .map_err(|e| map_transport_err_to_py_err(e, None, Some(rel_from)))
195 }
196
197 fn delete(&self, py: Python, relpath: &str) -> PyResult<()> {
198 use dromedary::Transport as _;
199 py.detach(|| self.inner.delete(relpath))
200 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
201 }
202
203 fn copy(&self, py: Python, rel_from: &str, rel_to: &str) -> PyResult<()> {
204 use dromedary::Transport as _;
205 py.detach(|| self.inner.copy(rel_from, rel_to))
206 .map_err(|e| map_transport_err_to_py_err(e, None, Some(rel_from)))
207 }
208
209 /// PUT with the atomic temp+MOVE dance; returns `len(bytes)`.
210 fn put_bytes(&self, py: Python, relpath: &str, bytes: &[u8]) -> PyResult<u64> {
211 use dromedary::Transport as _;
212 py.detach(|| self.inner.put_bytes(relpath, bytes, None))
213 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?;
214 Ok(bytes.len() as u64)
215 }
216
217 /// Non-atomic PUT (bare, no temp-file dance). `create_parent_dir`
218 /// causes a 404/403/409 to retry after creating the missing
219 /// parent directory via MKCOL.
220 #[pyo3(signature = (relpath, bytes, create_parent_dir=false))]
221 fn put_bytes_non_atomic(
222 &self,
223 py: Python,
224 relpath: &str,
225 bytes: &[u8],
226 create_parent_dir: bool,
227 ) -> PyResult<()> {
228 use dromedary::Transport as _;
229 py.detach(|| {
230 self.inner
231 .put_bytes_non_atomic(relpath, bytes, None, Some(create_parent_dir), None)
232 })
233 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
234 }
235
236 /// Append `bytes` to the file at `relpath`, returning the file
237 /// size before the append. Picks between HEAD+ranged-PUT and
238 /// GET+modify+PUT based on the inherited range-hint state. The
239 /// ``mode`` argument is accepted for Transport-API parity — the
240 /// DAV backend has no way to set file modes server-side, so it's
241 /// ignored.
242 #[pyo3(signature = (relpath, bytes, mode=None))]
243 fn append_bytes(
244 &self,
245 py: Python,
246 relpath: &str,
247 bytes: &[u8],
248 mode: Option<Py<PyAny>>,
249 ) -> PyResult<u64> {
250 use dromedary::Transport as _;
251 let _ = mode;
252 py.detach(|| self.inner.append_bytes(relpath, bytes, None))
253 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
254 }
255
256 /// `stat(relpath)` — returns a Python object with `st_size` and
257 /// `st_mode` attributes, matching the shape the Python
258 /// `_DAVStat` had. Directories get `st_size=0` and a dir mode
259 /// (040644); regular files get their PROPFIND-reported size
260 /// and 100644 or 100755 depending on the `executable` flag.
261 fn stat<'py>(&self, py: Python<'py>, relpath: &str) -> PyResult<Bound<'py, PyAny>> {
262 use dromedary::Transport as _;
263 let stat = py
264 .detach(|| self.inner.stat(relpath))
265 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))?;
266 let dict = pyo3::types::PyDict::new(py);
267 dict.set_item("st_size", stat.size)?;
268 #[cfg(unix)]
269 dict.set_item("st_mode", stat.mode)?;
270 // Return a SimpleNamespace so callers use dotted access
271 // (bzr reads `st.st_mode`, not `st['st_mode']`).
272 let types = py.import("types")?;
273 let ns = types.getattr("SimpleNamespace")?.call((), Some(&dict))?;
274 Ok(ns)
275 }
276
277 /// List immediate children of `relpath`. Names are relative to
278 /// `relpath` (with any trailing slash stripped). Errors from
279 /// PROPFIND surface as Python exceptions on the caller's first
280 /// iteration; we materialise the list eagerly so `list_dir()`
281 /// behaves like a Python list rather than a lazy iterator.
282 fn list_dir(&self, py: Python, relpath: &str) -> PyResult<Vec<String>> {
283 use dromedary::Transport as _;
284 py.detach(|| -> Result<Vec<String>, dromedary::Error> {
285 let iter = self.inner.list_dir(relpath);
286 iter.collect::<Result<Vec<_>, _>>()
287 })
288 .map_err(|e| map_transport_err_to_py_err(e, None, Some(relpath)))
289 }
290
291 fn iter_files_recursive(&self, py: Python) -> PyResult<Vec<String>> {
292 use dromedary::Transport as _;
293 py.detach(|| -> Result<Vec<String>, dromedary::Error> {
294 let iter = self.inner.iter_files_recursive();
295 iter.collect::<Result<Vec<_>, _>>()
296 })
297 .map_err(|e| map_transport_err_to_py_err(e, None, None))
298 }
299 }
300
301 /// Build the four-layer `Transport → ConnectedTransport →
302 /// HttpTransport → HttpDavTransport` initializer.
303 ///
304 /// The `dyn Transport` installed at the base points at the *DAV*
305 /// transport, not the HTTP one it wraps. That matters because the
306 /// `Transport` pyclass's inherited Python helpers (notably `move`,
307 /// `copy_tree`, `copy_to`) dispatch to `self.0.r#move` etc. —
308 /// `self.0` being the base `Box<dyn Transport>`. If that dyn
309 /// pointed at the HTTP layer, those helpers would call the HTTP
310 /// `stat` (which returns `TransportNotPossible`) and fail. Pointing
311 /// at the DAV layer routes them through PROPFIND-backed stat and
312 /// the native WebDAV MOVE verb.
313 fn dav_transport_initializer(
314 inner: Arc<RsHttpDavTransport>,
315 ) -> PyClassInitializer<HttpDavTransport> {
316 let http_inner = Arc::new(inner.http().clone());
317 let dav_box: Box<dyn dromedary::Transport> = Box::new(Clone::clone(&*inner));
318 http_transport_initializer_with_base(http_inner, dav_box)
319 .add_subclass(HttpDavTransport { inner })
320 }