ctb_formats_multipart/
multipart.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Multipart form utilities. The meat of this is the `build_multipart`
21//! function. The serialization code was needed to make it be able to tell a
22//! `Vec<u8>` apart from other arrays. `Vec<u8>` are specifically assumed to be
23//! file uploads.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32use anyhow::{Result, anyhow};
33use reqwest::blocking::multipart::Part;
34
35use crate::utilities::reader::reader_to_bytes;
36use crate::utilities::serde_value::to_html_form_string;
37use serde::Serialize;
38
39/// Internal captured representation of a struct field for multipart building.
40enum CapturedField {
41    Bytes(Vec<u8>),
42    Array(Vec<serde_json::Value>),
43    Scalar(serde_json::Value),
44}
45
46/// Internal serializer error used to implement `serde::ser::Error` without panicking.
47#[derive(Debug)]
48struct CaptureError(anyhow::Error);
49
50impl CaptureError {
51    pub fn custom(msg: impl std::fmt::Display) -> Self {
52        CaptureError(anyhow!(msg.to_string()))
53    }
54}
55
56impl std::fmt::Display for CaptureError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        self.0.fmt(f)
59    }
60}
61
62impl std::error::Error for CaptureError {}
63
64impl serde::ser::Error for CaptureError {
65    fn custom<T: std::fmt::Display>(msg: T) -> Self {
66        CaptureError(anyhow::anyhow!(msg.to_string()))
67    }
68}
69
70use serde::ser::{SerializeSeq, SerializeStruct, Serializer};
71
72/// Serializer that captures a struct into a key -> `CapturedField` map.
73struct TopSerializer<'a> {
74    out: &'a mut std::collections::BTreeMap<String, CapturedField>,
75}
76
77impl<'a> Serializer for TopSerializer<'a> {
78    type Ok = ();
79    type Error = CaptureError;
80    type SerializeSeq = serde::ser::Impossible<(), CaptureError>; // Changed to avoid type mismatch since sequences are not supported at top-level
81    type SerializeTuple = serde::ser::Impossible<(), CaptureError>;
82    type SerializeTupleStruct = serde::ser::Impossible<(), CaptureError>;
83    type SerializeTupleVariant = serde::ser::Impossible<(), CaptureError>;
84    type SerializeMap = serde::ser::Impossible<(), CaptureError>;
85    type SerializeStruct = StructCapture<'a>;
86    type SerializeStructVariant = serde::ser::Impossible<(), CaptureError>;
87
88    fn serialize_struct(
89        self,
90        _name: &'static str,
91        _len: usize,
92    ) -> Result<Self::SerializeStruct, Self::Error> {
93        Ok(StructCapture { out: self.out })
94    }
95
96    // All other entry points at top-level are unsupported; we expect a struct.
97    fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
98        Err(CaptureError::custom("expected struct at top-level"))
99    }
100    fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
101        Err(CaptureError::custom("expected struct at top-level"))
102    }
103    fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
104        Err(CaptureError::custom("expected struct at top-level"))
105    }
106    fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
107        Err(CaptureError::custom("expected struct at top-level"))
108    }
109    fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
110        Err(CaptureError::custom("expected struct at top-level"))
111    }
112    fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
113        Err(CaptureError::custom("expected struct at top-level"))
114    }
115    fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
116        Err(CaptureError::custom("expected struct at top-level"))
117    }
118    fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
119        Err(CaptureError::custom("expected struct at top-level"))
120    }
121    fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
122        Err(CaptureError::custom("expected struct at top-level"))
123    }
124    fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
125        Err(CaptureError::custom("expected struct at top-level"))
126    }
127    fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
128        Err(CaptureError::custom("expected struct at top-level"))
129    }
130    fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
131        Err(CaptureError::custom("expected struct at top-level"))
132    }
133    fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
134        Err(CaptureError::custom("expected struct at top-level"))
135    }
136    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
137        Err(CaptureError::custom("expected struct at top-level"))
138    }
139    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
140        Err(CaptureError::custom("expected struct at top-level"))
141    }
142    fn serialize_some<T: ?Sized + Serialize>(
143        self,
144        _value: &T,
145    ) -> Result<Self::Ok, Self::Error> {
146        Err(CaptureError::custom("expected struct at top-level"))
147    }
148    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
149        Err(CaptureError::custom("expected struct at top-level"))
150    }
151    fn serialize_unit_struct(
152        self,
153        _name: &'static str,
154    ) -> Result<Self::Ok, Self::Error> {
155        Err(CaptureError::custom("expected struct at top-level"))
156    }
157    fn serialize_unit_variant(
158        self,
159        _name: &'static str,
160        _variant_index: u32,
161        _variant: &'static str,
162    ) -> Result<Self::Ok, Self::Error> {
163        Err(CaptureError::custom("expected struct at top-level"))
164    }
165    fn serialize_newtype_struct<T: ?Sized + Serialize>(
166        self,
167        _name: &'static str,
168        _value: &T,
169    ) -> Result<Self::Ok, Self::Error> {
170        Err(CaptureError::custom("expected struct at top-level"))
171    }
172    fn serialize_newtype_variant<T: ?Sized + Serialize>(
173        self,
174        _name: &'static str,
175        _variant_index: u32,
176        _variant: &'static str,
177        _value: &T,
178    ) -> Result<Self::Ok, Self::Error> {
179        Err(CaptureError::custom("expected struct at top-level"))
180    }
181    fn serialize_seq(
182        self,
183        _len: Option<usize>,
184    ) -> Result<Self::SerializeSeq, Self::Error> {
185        Err(CaptureError::custom("expected struct at top-level"))
186    }
187    fn serialize_tuple(
188        self,
189        _len: usize,
190    ) -> Result<Self::SerializeTuple, Self::Error> {
191        Err(CaptureError::custom("expected struct at top-level"))
192    }
193    fn serialize_tuple_struct(
194        self,
195        _name: &'static str,
196        _len: usize,
197    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
198        Err(CaptureError::custom("expected struct at top-level"))
199    }
200    fn serialize_tuple_variant(
201        self,
202        _name: &'static str,
203        _variant_index: u32,
204        _variant: &'static str,
205        _len: usize,
206    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
207        Err(CaptureError::custom("expected struct at top-level"))
208    }
209    fn serialize_map(
210        self,
211        _len: Option<usize>,
212    ) -> Result<Self::SerializeMap, Self::Error> {
213        Err(CaptureError::custom("expected struct at top-level"))
214    }
215    fn serialize_struct_variant(
216        self,
217        _name: &'static str,
218        _variant_index: u32,
219        _variant: &'static str,
220        _len: usize,
221    ) -> Result<Self::SerializeStructVariant, Self::Error> {
222        Err(CaptureError::custom("expected struct at top-level"))
223    }
224}
225
226struct StructCapture<'a> {
227    out: &'a mut std::collections::BTreeMap<String, CapturedField>,
228}
229
230impl SerializeStruct for StructCapture<'_> {
231    type Ok = ();
232    type Error = CaptureError;
233
234    fn serialize_field<T: ?Sized + Serialize>(
235        &mut self,
236        key: &'static str,
237        value: &T,
238    ) -> Result<(), Self::Error> {
239        let captured = FieldSerializer::capture(value)?;
240        self.out.insert(key.to_string(), captured);
241        Ok(())
242    }
243
244    fn end(self) -> Result<Self::Ok, Self::Error> {
245        Ok(())
246    }
247}
248
249/// Serializer that captures a single field into a `CapturedField`.
250struct FieldSerializer;
251
252impl FieldSerializer {
253    fn capture<T: ?Sized + Serialize>(
254        value: &T,
255    ) -> Result<CapturedField, CaptureError> {
256        value.serialize(Self)
257    }
258}
259
260impl Serializer for FieldSerializer {
261    type Ok = CapturedField;
262    type Error = CaptureError;
263    type SerializeSeq = SeqCapture;
264    type SerializeTuple = serde::ser::Impossible<CapturedField, CaptureError>;
265    type SerializeTupleStruct =
266        serde::ser::Impossible<CapturedField, CaptureError>;
267    type SerializeTupleVariant =
268        serde::ser::Impossible<CapturedField, CaptureError>;
269    type SerializeMap = serde::ser::Impossible<CapturedField, CaptureError>;
270    type SerializeStruct = serde::ser::Impossible<CapturedField, CaptureError>;
271    type SerializeStructVariant =
272        serde::ser::Impossible<CapturedField, CaptureError>;
273
274    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
275        Ok(CapturedField::Scalar(serde_json::Value::Bool(v)))
276    }
277    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
278        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
279    }
280    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
281        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
282    }
283    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
284        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
285    }
286    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
287        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
288    }
289    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
290        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
291    }
292    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
293        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
294    }
295    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
296        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
297    }
298    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
299        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
300    }
301    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
302        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
303    }
304    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
305        Ok(CapturedField::Scalar(serde_json::Value::Number(v.into())))
306    }
307    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
308        let n = serde_json::Number::from_f64(f64::from(v))
309            .ok_or_else(|| CaptureError::custom("invalid f32"))?;
310        Ok(CapturedField::Scalar(serde_json::Value::Number(n)))
311    }
312    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
313        let n = serde_json::Number::from_f64(v)
314            .ok_or_else(|| CaptureError::custom("invalid f64"))?;
315        Ok(CapturedField::Scalar(serde_json::Value::Number(n)))
316    }
317    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
318        Ok(CapturedField::Scalar(serde_json::Value::String(
319            v.to_string(),
320        )))
321    }
322    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
323        Ok(CapturedField::Scalar(serde_json::Value::String(
324            v.to_string(),
325        )))
326    }
327    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
328        Ok(CapturedField::Bytes(v.to_vec()))
329    }
330    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
331        Ok(CapturedField::Scalar(serde_json::Value::Null))
332    }
333    fn serialize_some<T: ?Sized + Serialize>(
334        self,
335        value: &T,
336    ) -> Result<Self::Ok, Self::Error> {
337        // Represent Option<T>::Some as the inner value
338        FieldSerializer::capture(value)
339    }
340    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
341        Ok(CapturedField::Scalar(serde_json::Value::Null))
342    }
343    fn serialize_unit_struct(
344        self,
345        _name: &'static str,
346    ) -> Result<Self::Ok, Self::Error> {
347        Ok(CapturedField::Scalar(serde_json::Value::Null))
348    }
349    fn serialize_unit_variant(
350        self,
351        _name: &'static str,
352        _variant_index: u32,
353        variant: &'static str,
354    ) -> Result<Self::Ok, Self::Error> {
355        Ok(CapturedField::Scalar(serde_json::Value::String(
356            variant.to_string(),
357        )))
358    }
359    fn serialize_newtype_struct<T: ?Sized + Serialize>(
360        self,
361        _name: &'static str,
362        value: &T,
363    ) -> Result<Self::Ok, Self::Error> {
364        FieldSerializer::capture(value)
365    }
366    fn serialize_newtype_variant<T: ?Sized + Serialize>(
367        self,
368        _name: &'static str,
369        _variant_index: u32,
370        variant: &'static str,
371        value: &T,
372    ) -> Result<Self::Ok, Self::Error> {
373        // Represent as a simple map { variant: value } as a scalar JSON object
374        let mut map = serde_json::Map::new();
375        map.insert(
376            variant.to_string(),
377            serde_json::to_value(value)
378                .map_err(|e| CaptureError(anyhow!(e)))?,
379        );
380        Ok(CapturedField::Scalar(serde_json::Value::Object(map)))
381    }
382    fn serialize_seq(
383        self,
384        _len: Option<usize>,
385    ) -> Result<Self::SerializeSeq, Self::Error> {
386        Ok(SeqCapture { elems: Vec::new() })
387    }
388    fn serialize_tuple(
389        self,
390        _len: usize,
391    ) -> Result<Self::SerializeTuple, Self::Error> {
392        Err(CaptureError::custom("tuple not supported"))
393    }
394    fn serialize_tuple_struct(
395        self,
396        _name: &'static str,
397        _len: usize,
398    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
399        Err(CaptureError::custom("tuple struct not supported"))
400    }
401    fn serialize_tuple_variant(
402        self,
403        _name: &'static str,
404        _variant_index: u32,
405        _variant: &'static str,
406        _len: usize,
407    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
408        Err(CaptureError::custom("tuple variant not supported"))
409    }
410    fn serialize_map(
411        self,
412        _len: Option<usize>,
413    ) -> Result<Self::SerializeMap, Self::Error> {
414        // Fallback: capture as scalar JSON object
415        Err(CaptureError::custom(
416            "map capture at field level not supported",
417        ))
418    }
419    fn serialize_struct(
420        self,
421        _name: &'static str,
422        _len: usize,
423    ) -> Result<Self::SerializeStruct, Self::Error> {
424        Err(CaptureError::custom("nested struct capture not supported"))
425    }
426    fn serialize_struct_variant(
427        self,
428        _name: &'static str,
429        _variant_index: u32,
430        _variant: &'static str,
431        _len: usize,
432    ) -> Result<Self::SerializeStructVariant, Self::Error> {
433        Err(CaptureError::custom("struct variant not supported"))
434    }
435}
436
437enum SeqElem {
438    U8(u8),
439    Other(serde_json::Value),
440}
441
442struct SeqCapture {
443    elems: Vec<SeqElem>,
444}
445
446impl SerializeSeq for SeqCapture {
447    type Ok = CapturedField;
448    type Error = CaptureError;
449
450    fn serialize_element<T: ?Sized + Serialize>(
451        &mut self,
452        value: &T,
453    ) -> Result<(), Self::Error> {
454        // Capture each element, distinguishing u8 from everything else.
455        value.serialize(ElemCapture {
456            elems: &mut self.elems,
457        })
458    }
459
460    fn end(self) -> Result<Self::Ok, Self::Error> {
461        // If all elements are U8, treat the whole sequence as bytes; else as a
462        // JSON array.
463        //
464        // Important: for an empty sequence, we *cannot* infer the element type.
465        // Treating it as bytes would cause unrelated empty Vecs (e.g.
466        // `Vec<u64>`) to serialize as an empty multipart field, which strict
467        // typed-multipart parsing will (correctly) reject.
468        if self.elems.is_empty() {
469            return Ok(CapturedField::Array(Vec::new()));
470        }
471
472        if self.elems.iter().all(|e| matches!(e, SeqElem::U8(_))) {
473            let bytes = self
474                .elems
475                .into_iter()
476                .map(|e| match e {
477                    SeqElem::U8(b) => b,
478                    SeqElem::Other(_v) => 0,
479                })
480                .collect::<Vec<u8>>();
481            Ok(CapturedField::Bytes(bytes))
482        } else {
483            let arr = self
484                .elems
485                .into_iter()
486                .map(|e| match e {
487                    SeqElem::U8(b) => serde_json::Value::Number(b.into()),
488                    SeqElem::Other(v) => v,
489                })
490                .collect::<Vec<_>>();
491            Ok(CapturedField::Array(arr))
492        }
493    }
494}
495
496struct ElemCapture<'a> {
497    elems: &'a mut Vec<SeqElem>,
498}
499
500impl Serializer for ElemCapture<'_> {
501    type Ok = ();
502    type Error = CaptureError;
503    type SerializeSeq = serde::ser::Impossible<(), CaptureError>;
504    type SerializeTuple = serde::ser::Impossible<(), CaptureError>;
505    type SerializeTupleStruct = serde::ser::Impossible<(), CaptureError>;
506    type SerializeTupleVariant = serde::ser::Impossible<(), CaptureError>;
507    type SerializeMap = serde::ser::Impossible<(), CaptureError>;
508    type SerializeStruct = serde::ser::Impossible<(), CaptureError>;
509    type SerializeStructVariant = serde::ser::Impossible<(), CaptureError>;
510
511    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
512        self.elems.push(SeqElem::U8(v));
513        Ok(())
514    }
515
516    // For all other primitives, push as a JSON value for later to_html_form_string conversion.
517    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
518        self.elems.push(SeqElem::Other(serde_json::Value::Bool(v)));
519        Ok(())
520    }
521    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
522        self.elems
523            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
524        Ok(())
525    }
526    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
527        self.elems
528            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
529        Ok(())
530    }
531    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
532        self.elems
533            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
534        Ok(())
535    }
536    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
537        self.elems
538            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
539        Ok(())
540    }
541    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
542        self.elems
543            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
544        Ok(())
545    }
546    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
547        self.elems
548            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
549        Ok(())
550    }
551    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
552        self.elems
553            .push(SeqElem::Other(serde_json::Value::Number(v.into())));
554        Ok(())
555    }
556    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
557        let n = serde_json::Number::from_f64(f64::from(v))
558            .ok_or_else(|| CaptureError::custom("invalid f32"))?;
559        self.elems
560            .push(SeqElem::Other(serde_json::Value::Number(n)));
561        Ok(())
562    }
563    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
564        let n = serde_json::Number::from_f64(v)
565            .ok_or_else(|| CaptureError::custom("invalid f64"))?;
566        self.elems
567            .push(SeqElem::Other(serde_json::Value::Number(n)));
568        Ok(())
569    }
570    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
571        self.elems
572            .push(SeqElem::Other(serde_json::Value::String(v.to_string())));
573        Ok(())
574    }
575    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
576        self.elems
577            .push(SeqElem::Other(serde_json::Value::String(v.to_string())));
578        Ok(())
579    }
580    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
581        // Represent as JSON array of numbers when used as element; bytes here is uncommon.
582        let arr = v
583            .iter()
584            .copied()
585            .map(|b| serde_json::Value::Number(b.into()))
586            .collect();
587        self.elems
588            .push(SeqElem::Other(serde_json::Value::Array(arr)));
589        Ok(())
590    }
591    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
592        self.elems.push(SeqElem::Other(serde_json::Value::Null));
593        Ok(())
594    }
595    fn serialize_some<T: ?Sized + Serialize>(
596        self,
597        value: &T,
598    ) -> Result<Self::Ok, Self::Error> {
599        // Represent as the inner value
600        value.serialize(self)
601    }
602    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
603        self.elems.push(SeqElem::Other(serde_json::Value::Null));
604        Ok(())
605    }
606    fn serialize_unit_struct(
607        self,
608        _name: &'static str,
609    ) -> Result<Self::Ok, Self::Error> {
610        self.elems.push(SeqElem::Other(serde_json::Value::Null));
611        Ok(())
612    }
613    fn serialize_unit_variant(
614        self,
615        _name: &'static str,
616        _variant_index: u32,
617        variant: &'static str,
618    ) -> Result<Self::Ok, Self::Error> {
619        self.elems.push(SeqElem::Other(serde_json::Value::String(
620            variant.to_string(),
621        )));
622        Ok(())
623    }
624    fn serialize_newtype_struct<T: ?Sized + Serialize>(
625        self,
626        _name: &'static str,
627        value: &T,
628    ) -> Result<Self::Ok, Self::Error> {
629        // Serialize inner as JSON value
630        let v = serde_json::to_value(value)
631            .map_err(|e| CaptureError(anyhow!(e)))?;
632        self.elems.push(SeqElem::Other(v));
633        Ok(())
634    }
635    fn serialize_newtype_variant<T: ?Sized + Serialize>(
636        self,
637        _name: &'static str,
638        _variant_index: u32,
639        variant: &'static str,
640        value: &T,
641    ) -> Result<Self::Ok, Self::Error> {
642        let mut map = serde_json::Map::new();
643        map.insert(
644            variant.to_string(),
645            serde_json::to_value(value)
646                .map_err(|e| CaptureError(anyhow!(e)))?,
647        );
648        self.elems
649            .push(SeqElem::Other(serde_json::Value::Object(map)));
650        Ok(())
651    }
652    fn serialize_seq(
653        self,
654        _len: Option<usize>,
655    ) -> Result<Self::SerializeSeq, Self::Error> {
656        // Nested sequences as elements are uncommon; represent as error to keep implementation small.
657        Err(CaptureError::custom("nested sequences not supported"))
658    }
659    fn serialize_tuple(
660        self,
661        _len: usize,
662    ) -> Result<Self::SerializeTuple, Self::Error> {
663        Err(CaptureError::custom("tuple elements not supported"))
664    }
665    fn serialize_tuple_struct(
666        self,
667        _name: &'static str,
668        _len: usize,
669    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
670        Err(CaptureError::custom("tuple struct elements not supported"))
671    }
672    fn serialize_tuple_variant(
673        self,
674        _name: &'static str,
675        _variant_index: u32,
676        _variant: &'static str,
677        _len: usize,
678    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
679        Err(CaptureError::custom("tuple variant elements not supported"))
680    }
681    fn serialize_map(
682        self,
683        _len: Option<usize>,
684    ) -> Result<Self::SerializeMap, Self::Error> {
685        Err(CaptureError::custom("map elements not supported"))
686    }
687    fn serialize_struct(
688        self,
689        _name: &'static str,
690        _len: usize,
691    ) -> Result<Self::SerializeStruct, Self::Error> {
692        Err(CaptureError::custom("struct elements not supported"))
693    }
694    fn serialize_struct_variant(
695        self,
696        _name: &'static str,
697        _variant_index: u32,
698        _variant: &'static str,
699        _len: usize,
700    ) -> Result<Self::SerializeStructVariant, Self::Error> {
701        Err(CaptureError::custom(
702            "struct variant elements not supported",
703        ))
704    }
705}
706
707pub fn build_multipart<T: Serialize>(data: &T) -> Result<(Vec<u8>, String)> {
708    // Build multipart body
709    let mut multipart = reqwest::blocking::multipart::Form::new();
710
711    // Capture fields with type-aware Vec<u8> detection.
712    let mut fields = std::collections::BTreeMap::<String, CapturedField>::new();
713    data.serialize(TopSerializer { out: &mut fields })
714        .map_err(|e| anyhow!(e.to_string()))?;
715
716    for (k, captured) in fields {
717        match captured {
718            CapturedField::Bytes(bytes) => {
719                let bytes_part = Part::bytes(bytes);
720                multipart = multipart.part(k.clone(), bytes_part);
721            }
722            CapturedField::Array(arr) => {
723                for item in arr {
724                    let val = to_html_form_string(&item)?;
725                    if let Some(v_str) = val {
726                        multipart = multipart.text(k.clone(), v_str);
727                    }
728                    // Skip None values
729                }
730            }
731            CapturedField::Scalar(v) => {
732                // Convert serde_json::Value to a string representation suitable for HTML forms
733                let val = to_html_form_string(&v)?;
734                if val.is_none() {
735                    // Skip None values (e.g., unchecked checkboxes)
736                    continue;
737                }
738                if let Some(vs) = val {
739                    multipart = multipart.text(k, vs);
740                } else {
741                    return Err(anyhow!(
742                        "Unsupported value type for field {k}: {v:?}"
743                    ));
744                }
745            }
746        }
747    }
748
749    let boundary = multipart.boundary().to_owned();
750    let reader = multipart.into_reader();
751    let buffer = reader_to_bytes(reader)?;
752    let content_type = format!("multipart/form-data; boundary={boundary}");
753    Ok((buffer, content_type))
754}
755
756#[cfg(test)]
757#[allow(
758    clippy::panic,
759    clippy::expect_used,
760    clippy::unwrap_used,
761    clippy::unwrap_in_result,
762    clippy::panic_in_result_fn,
763    clippy::indexing_slicing,
764    clippy::arithmetic_side_effects,
765    reason = "Standard repository test boilerplate"
766)]
767mod tests {
768    use super::*;
769    use serde::Serialize;
770
771    #[crate::ctb_test]
772    fn test_build_multipart() {
773        #[derive(Serialize)]
774        struct TestData {
775            bytes_array: Vec<u8>,
776            admin_users: Vec<u64>,
777            fixed_port: u16,
778            server_address: String,
779        }
780
781        let data = TestData {
782            bytes_array: vec![1, 2, 3],
783            admin_users: vec![12, 13],
784            fixed_port: 5678,
785            server_address: "bar".to_string(),
786        };
787
788        let result = build_multipart(&data);
789        assert!(result.is_ok());
790        let (buffer, content_type) = result.unwrap();
791        assert!(content_type.starts_with("multipart/form-data; boundary="));
792        // The buffer should contain the fields; exact boundary varies, so check for presence
793        let buffer_str = String::from_utf8_lossy(&buffer);
794        assert!(
795            buffer_str.contains("\"bytes_array\"\r\n\r\n\x01\x02\x03"),
796            "Buffer not contains expected: {buffer_str}"
797        );
798        assert!(
799            buffer_str.contains("\"admin_users\"\r\n\r\n12"),
800            "Buffer not contains expected: {buffer_str}"
801        );
802        assert!(
803            buffer_str.contains("\"admin_users\"\r\n\r\n13"),
804            "Buffer not contains expected: {buffer_str}"
805        );
806        assert!(
807            buffer_str.contains("\"fixed_port\"\r\n\r\n5678"),
808            "Buffer not contains expected: {buffer_str}"
809        );
810        assert!(
811            buffer_str.contains("\"server_address\"\r\n\r\nbar"),
812            "Buffer not contains expected: {buffer_str}"
813        );
814    }
815
816    #[crate::ctb_test]
817    fn test_build_multipart_omits_empty_vec_fields() {
818        #[derive(Serialize)]
819        struct TestData {
820            admin_users: Vec<u64>,
821            fixed_port: u16,
822        }
823
824        let data = TestData {
825            admin_users: Vec::new(),
826            fixed_port: 5678,
827        };
828
829        let (buffer, _content_type) = build_multipart(&data).unwrap();
830        let buffer_str = String::from_utf8_lossy(&buffer);
831
832        // Empty Vecs should serialize like browsers typically do for checkbox
833        // groups: the field is absent.
834        assert!(!buffer_str.contains("\"admin_users\""), "{buffer_str}");
835        assert!(buffer_str.contains("\"fixed_port\""), "{buffer_str}");
836    }
837}