eggfetch-python 0.3.0

Python sync and asyncio bindings for the eggfetch HTTP engine (Rust core via PyO3; Python users install from PyPI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Python multipart/file-upload support.
//!
//! Provides `PyFile` (the `eggfetch.File` wrapper) and helpers to convert
//! Python `files=` kwargs into a Rust `Multipart` body.

use std::path::PathBuf;

use bytes::Bytes;
use pyo3::prelude::*;
use pyo3::types::PyTuple;

use crate::conversion::extract_bytes_like;
use crate::conversion::python_headers_to_rust;
use crate::errors::map_err;
use eggfetch_core::multipart::{Multipart, Part, PartBody};

// ---------------------------------------------------------------------------
// PyFile — Python-visible File wrapper
// ---------------------------------------------------------------------------

/// A file path wrapper for multipart uploads.
///
/// Wraps a filesystem path so it can be passed as a value in the `files=`
/// kwarg. The file is read synchronously when the request is sent.
///
/// Args:
///     path: Filesystem path to the file.
///     filename: Override filename (default: basename of path).
///     `content_type`: Override content type (default: application/octet-stream).
#[pyclass(name = "File", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyFile {
    path: PathBuf,
    filename: String,
    content_type: String,
}

#[pymethods]
impl PyFile {
    #[new]
    #[pyo3(signature = (path, *, filename=None, content_type=None))]
    fn new(
        path: &Bound<'_, PyAny>,
        filename: Option<&str>,
        content_type: Option<&str>,
    ) -> PyResult<Self> {
        // Accept str, PathBuf, and path-like objects via `os.fspath`
        // (pathlib.Path). `extract::<String>` alone rejects Path.
        let pb: PathBuf = if let Ok(pb) = path.extract::<PathBuf>() {
            pb
        } else if let Ok(path_str) = path.extract::<String>() {
            PathBuf::from(&path_str)
        } else {
            let fspath = path
                .py()
                .import("os")
                .map_err(|_| {
                    PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                        "path must be a string or path-like object",
                    )
                })?
                .getattr("fspath")
                .map_err(|_| {
                    PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                        "path must be a string or path-like object",
                    )
                })?;
            let resolved = fspath.call1((path,)).map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                    "path must be a string or path-like object",
                )
            })?;
            resolved.extract::<PathBuf>().map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                    "path must be a string or path-like object",
                )
            })?
        };
        let default_filename = pb
            .file_name()
            .map_or_else(|| "file".to_owned(), |n| n.to_string_lossy().into_owned());
        // Fail early on CR/LF: core would reject these later as a generic
        // `RequestError` without naming the field.
        for (label, value) in [("filename", filename), ("content_type", content_type)] {
            if value.is_some_and(|v| v.contains(['\r', '\n'])) {
                return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "File {label} must not contain CR or LF"
                )));
            }
        }
        Ok(Self {
            path: pb,
            filename: filename.unwrap_or(&default_filename).to_owned(),
            content_type: content_type
                .unwrap_or("application/octet-stream")
                .to_owned(),
        })
    }

    /// The file path.
    #[getter]
    fn path(&self) -> String {
        self.path.to_string_lossy().into_owned()
    }

    /// The filename to use in the multipart form.
    #[getter]
    fn filename(&self) -> &str {
        &self.filename
    }

    /// The content type for this file.
    #[getter]
    fn content_type(&self) -> &str {
        &self.content_type
    }

    fn __repr__(&self) -> String {
        format!(
            "File(path={:?}, filename={:?}, content_type={:?})",
            self.path.display(),
            self.filename,
            self.content_type
        )
    }
}

// ---------------------------------------------------------------------------
// Multipart body builder
// ---------------------------------------------------------------------------

/// Build a multipart body from Python `data` and `files` kwargs.
///
/// Returns `(request_body, content_type)` where `content_type` includes the
/// boundary parameter.
pub fn build_multipart_body<'py>(
    py: Python<'py>,
    data: Option<&Bound<'py, PyAny>>,
    files: &Bound<'py, PyAny>,
) -> PyResult<(eggfetch_core::RequestBody, String)> {
    let mut multipart = Multipart::new();
    let boundary = multipart.boundary().clone();

    if let Some(d) = data {
        add_form_fields(&mut multipart, py, d)?;
    }

    add_file_parts(&mut multipart, py, files)?;

    let ct = format!("multipart/form-data; boundary={boundary}");
    let body = multipart.into_body();
    Ok((body, ct))
}

/// Extract a multipart string field with field context, rejecting CR/LF.
///
/// Core rejects control bytes later as a generic `RequestError`; failing
/// early here names the offending field.
fn extract_text_field(obj: &Bound<'_, PyAny>, field: &str) -> PyResult<String> {
    let s: String = obj.extract().map_err(|_| {
        PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!("{field} must be a string"))
    })?;
    if s.contains(['\r', '\n']) {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{field} must not contain CR or LF"
        )));
    }
    Ok(s)
}

/// Add form field parts from a dict or sequence of pairs.
fn add_form_fields(
    multipart: &mut Multipart,
    _py: Python<'_>,
    data: &Bound<'_, PyAny>,
) -> PyResult<()> {
    let items = if data.hasattr("__getitem__")? && data.hasattr("items")? {
        data.call_method0("items")?
    } else {
        data.clone()
    };
    for item in items.try_iter()? {
        let item = item?;
        let tuple: Bound<'_, PyTuple> = item.cast_into::<PyTuple>()?;
        if tuple.len() != 2 {
            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                "expected a mapping or sequence of 2-tuples",
            ));
        }
        let key = extract_text_field(&tuple.get_item(0)?, "multipart field name")?;
        let value = extract_text_field(&tuple.get_item(1)?, "multipart field value")?;
        *multipart = std::mem::replace(multipart, Multipart::new())
            .text(&key, &value)
            .map_err(map_err)?;
    }
    Ok(())
}

/// Add file parts from the `files=` kwarg.
///
/// Accepts:
/// - A mapping of `field_name` -> `file_spec`
/// - A sequence of (`field_name`, `file_spec`) pairs
///
/// File spec variants:
/// - `bytes` or `str`: bare data with `field_name` as filename
/// - `(filename, data)`: filename + data
/// - `(filename, data, content_type)`: filename + data + content type
/// - `(filename, data, content_type, headers)`: full spec
/// - `File` object: path-based file
fn add_file_parts(
    multipart: &mut Multipart,
    py: Python<'_>,
    files: &Bound<'_, PyAny>,
) -> PyResult<()> {
    let pairs = if files.hasattr("__getitem__")? && files.hasattr("items")? {
        let items = files.call_method0("items")?;
        let mut pairs = Vec::new();
        for item in items.try_iter()? {
            let item = item?;
            let tuple: Bound<'_, PyTuple> = item.cast_into::<PyTuple>()?;
            let field_name: String = tuple.get_item(0)?.extract()?;
            let file_spec = tuple.get_item(1)?;
            pairs.push((field_name, file_spec));
        }
        pairs
    } else {
        let mut pairs = Vec::new();
        for item in files.try_iter()? {
            let item = item?;
            let tuple: Bound<'_, PyTuple> = item.cast_into::<PyTuple>()?;
            if tuple.len() != 2 {
                return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                    "files sequence items must be 2-tuples of (field_name, file_spec)",
                ));
            }
            let field_name: String = tuple.get_item(0)?.extract()?;
            let file_spec = tuple.get_item(1)?;
            pairs.push((field_name, file_spec));
        }
        pairs
    };

    for (field_name, file_spec) in pairs {
        add_single_file_part(multipart, py, &field_name, &file_spec)?;
    }
    Ok(())
}

/// Add a single file part from a field name and file spec.
fn add_single_file_part(
    multipart: &mut Multipart,
    py: Python<'_>,
    field_name: &str,
    file_spec: &Bound<'_, PyAny>,
) -> PyResult<()> {
    if let Ok(py_file) = file_spec.extract::<PyFile>() {
        return add_path_file_part(multipart, field_name, &py_file);
    }

    // Same buffer protocol as `content=` (`bytes`, `bytearray`, `memoryview`).
    if let Some(b) = extract_bytes_like(file_spec)? {
        let filename = field_name.to_owned();
        *multipart = std::mem::replace(multipart, Multipart::new())
            .bytes(
                field_name,
                &filename,
                "application/octet-stream",
                Bytes::from(b),
            )
            .map_err(map_err)?;
        return Ok(());
    }

    if let Ok(s) = file_spec.extract::<String>() {
        let filename = field_name.to_owned();
        *multipart = std::mem::replace(multipart, Multipart::new())
            .bytes(
                field_name,
                &filename,
                "text/plain",
                Bytes::from(s.into_bytes()),
            )
            .map_err(map_err)?;
        return Ok(());
    }

    if let Ok(tuple) = file_spec.cast::<PyTuple>() {
        return add_tuple_file_part(multipart, py, field_name, tuple);
    }

    Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
        "unsupported file spec type for field {field_name}: {}",
        file_spec.get_type().name()?
    )))
}

/// Add a file part from a tuple spec.
fn add_tuple_file_part(
    multipart: &mut Multipart,
    py: Python<'_>,
    field_name: &str,
    tuple: &Bound<'_, PyTuple>,
) -> PyResult<()> {
    let len = tuple.len();
    if !(2..=4).contains(&len) {
        return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
            "file tuple must be (filename, data), (filename, data, content_type), or (filename, data, content_type, headers)",
        ));
    }

    let filename = extract_text_field(&tuple.get_item(0)?, "multipart filename")?;
    let data_bytes = extract_data_bytes(&tuple.get_item(1)?)?;
    let content_type: String = if len >= 3 {
        extract_text_field(&tuple.get_item(2)?, "multipart content_type")?
    } else {
        guess_content_type(&filename)
    };

    if len >= 4 {
        let headers_obj = tuple.get_item(3)?;
        if !headers_obj.is_none() {
            let headers = python_headers_to_rust(py, &headers_obj)?;
            let mut part =
                Part::new(field_name, PartBody::Bytes(data_bytes))
                    .filename(&filename)
                    .content_type(http::HeaderValue::from_str(&content_type).map_err(|e| {
                        PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string())
                    })?);
            for (name, value) in headers.iter() {
                part = part.header(name.as_str(), value.clone());
            }
            *multipart = std::mem::replace(multipart, Multipart::new())
                .part(part)
                .map_err(map_err)?;
            return Ok(());
        }
    }

    *multipart = std::mem::replace(multipart, Multipart::new())
        .bytes(field_name, &filename, &content_type, data_bytes)
        .map_err(map_err)?;
    Ok(())
}

/// Read a `File` wrapper into a `PartBody`.
fn add_path_file_part(
    multipart: &mut Multipart,
    field_name: &str,
    py_file: &PyFile,
) -> PyResult<()> {
    let data = std::fs::read(&py_file.path).map_err(|e| {
        // Map OS error kinds to the matching Python exception instead of
        // collapsing everything to `FileExistsError`.
        use pyo3::exceptions::{PyFileNotFoundError, PyOSError, PyPermissionError};
        use std::io::ErrorKind;
        let msg = format!("failed to read {}: {e}", py_file.path.display());
        match e.kind() {
            ErrorKind::NotFound => PyErr::new::<PyFileNotFoundError, _>(msg),
            ErrorKind::PermissionDenied => PyErr::new::<PyPermissionError, _>(msg),
            _ => PyErr::new::<PyOSError, _>(msg),
        }
    })?;
    *multipart = std::mem::replace(multipart, Multipart::new())
        .bytes(
            field_name,
            &py_file.filename,
            &py_file.content_type,
            Bytes::from(data),
        )
        .map_err(map_err)?;
    Ok(())
}

/// Extract bytes from a Python bytes-like or string object.
///
/// Accepts the same buffer protocol as `content=` (`bytes`, `bytearray`,
/// `memoryview`) plus `str`.
fn extract_data_bytes(obj: &Bound<'_, PyAny>) -> PyResult<Bytes> {
    if let Some(b) = extract_bytes_like(obj)? {
        return Ok(Bytes::from(b));
    }
    if let Ok(s) = obj.extract::<String>() {
        return Ok(Bytes::from(s.into_bytes()));
    }
    Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
        "file data must be bytes, bytearray, memoryview, or string",
    ))
}

/// Guess content type from filename extension.
fn guess_content_type(filename: &str) -> String {
    let ext = filename.rsplit('.').next().unwrap_or("").to_lowercase();
    match ext.as_str() {
        "txt" => "text/plain".to_owned(),
        "html" | "htm" => "text/html".to_owned(),
        "json" => "application/json".to_owned(),
        "xml" => "application/xml".to_owned(),
        "pdf" => "application/pdf".to_owned(),
        "png" => "image/png".to_owned(),
        "jpg" | "jpeg" => "image/jpeg".to_owned(),
        "gif" => "image/gif".to_owned(),
        "svg" => "image/svg+xml".to_owned(),
        "zip" => "application/zip".to_owned(),
        _ => "application/octet-stream".to_owned(),
    }
}