Skip to main content

crucible_wire/
split.rs

1//! Writing a structure as a JSON body with its header members taken out, in
2//! one pass: the body goes straight to bytes, and each header member becomes
3//! header text on the way. A structure with an `@httpPayload` member writes
4//! that member's bytes as the body instead, raw.
5
6use serde::ser::{self, Impossible, Serialize, SerializeStruct, Serializer};
7use serde_json::Value;
8
9use base64::Engine;
10use base64::engine::general_purpose::STANDARD;
11
12use crate::operation::{Location, MemberInfo};
13
14/// Writes `value` (a structure) into `out` as a JSON object without the
15/// members `members` binds to headers, and returns those as (header, text).
16/// With a payload member, `out` gets that member's bytes instead.
17pub fn write<T: Serialize + ?Sized>(
18    value: &T,
19    members: &[MemberInfo],
20    out: &mut Vec<u8>,
21) -> serde_json::Result<Vec<(&'static str, String)>> {
22    write_typed(value, members, None, out)
23}
24
25/// [`write`], with `"__type": type_name` appended when one is given: how an
26/// error body names its error.
27pub fn write_typed<T: Serialize + ?Sized>(
28    value: &T,
29    members: &[MemberInfo],
30    type_name: Option<&'static str>,
31    out: &mut Vec<u8>,
32) -> serde_json::Result<Vec<(&'static str, String)>> {
33    let mut taken = Vec::new();
34    value.serialize(Split {
35        members,
36        take: Take::Headers,
37        type_name,
38        payload: Location::payload(members).is_some(),
39        out,
40        taken: &mut taken,
41    })?;
42    taken
43        .into_iter()
44        .filter_map(|(member, value)| match member.location {
45            Location::Header(header) => Some(
46                crate::text::header_text(&value, member.scalar)
47                    .map(|text| (header, text))
48                    .map_err(<serde_json::Error as ser::Error>::custom),
49            ),
50            _ => None,
51        })
52        .collect()
53}
54
55/// Writes `value` (an input) into `out` as a JSON object of its body
56/// members only, and returns every bound member (label, query parameter or
57/// header) with its value: what a client needs to build the request. With a
58/// payload member, `out` gets that member's bytes instead.
59pub fn write_bound<T: Serialize + ?Sized>(
60    value: &T,
61    members: &'static [MemberInfo],
62    out: &mut Vec<u8>,
63) -> serde_json::Result<Vec<(&'static MemberInfo, Value)>> {
64    let mut taken = Vec::new();
65    value.serialize(Split {
66        members,
67        take: Take::Bound,
68        type_name: None,
69        payload: Location::payload(members).is_some(),
70        out,
71        taken: &mut taken,
72    })?;
73    Ok(taken
74        .into_iter()
75        .map(|(member, value)| {
76            let member = members
77                .iter()
78                .find(|m| m.name == member.name)
79                .expect("taken members are this structure's");
80            (member, value)
81        })
82        .collect())
83}
84
85#[derive(Clone, Copy, PartialEq, Eq)]
86enum Take {
87    Headers,
88    Bound,
89}
90
91struct Split<'s> {
92    members: &'s [MemberInfo],
93    take: Take,
94    type_name: Option<&'static str>,
95    /// The structure has a payload member: `out` is its bytes, not JSON.
96    payload: bool,
97    out: &'s mut Vec<u8>,
98    taken: &'s mut Vec<(MemberInfo, Value)>,
99}
100
101struct Fields<'s> {
102    split: Split<'s>,
103    first: bool,
104}
105
106impl SerializeStruct for Fields<'_> {
107    type Ok = ();
108    type Error = serde_json::Error;
109
110    fn serialize_field<T: Serialize + ?Sized>(
111        &mut self,
112        key: &'static str,
113        value: &T,
114    ) -> serde_json::Result<()> {
115        if self.split.payload {
116            let member = self.split.members.iter().find(|member| member.name == key);
117            match member.map(|member| member.location) {
118                Some(Location::Payload(_)) => {
119                    return value.serialize(Raw {
120                        out: &mut *self.split.out,
121                    });
122                }
123                Some(Location::TextPayload(_)) => {
124                    return match serde_json::to_value(value)? {
125                        Value::String(text) => {
126                            self.split.out.extend_from_slice(text.as_bytes());
127                            Ok(())
128                        }
129                        Value::Null => Ok(()),
130                        _ => Err(ser::Error::custom("a text payload member is a string")),
131                    };
132                }
133                Some(Location::DocumentPayload(_)) => {
134                    // Model serde owns omission; a serialized null is a
135                    // present document value and must remain on the wire.
136                    serde_json::to_writer(&mut *self.split.out, value)?;
137                    return Ok(());
138                }
139                _ => {}
140            }
141        }
142        let take = self.split.take;
143        let taken = self.split.members.iter().find(|member| {
144            member.name == key
145                && matches!(
146                    (take, member.location),
147                    (_, Location::Header(_)) | (Take::Bound, Location::Label | Location::Query(_))
148                )
149        });
150        if let Some(member) = taken {
151            let value = serde_json::to_value(value)?;
152            let empty = matches!(&value, Value::Array(items) if items.is_empty());
153            if !value.is_null() && !empty {
154                self.split.taken.push((*member, value));
155            }
156            return Ok(());
157        }
158        if self.split.payload {
159            return Err(beside_payload());
160        }
161        if !self.first {
162            self.split.out.push(b',');
163        }
164        self.first = false;
165        serde_json::to_writer(&mut *self.split.out, key)?;
166        self.split.out.push(b':');
167        serde_json::to_writer(&mut *self.split.out, value)
168    }
169
170    fn end(self) -> serde_json::Result<()> {
171        if self.split.payload {
172            return Ok(());
173        }
174        if let Some(name) = self.split.type_name {
175            if !self.first {
176                self.split.out.push(b',');
177            }
178            self.split.out.extend_from_slice(b"\"__type\":");
179            serde_json::to_writer(&mut *self.split.out, name)?;
180        }
181        self.split.out.push(b'}');
182        Ok(())
183    }
184}
185
186/// A map with string keys (a JSON object value), written like a structure.
187struct Entries<'s> {
188    fields: Fields<'s>,
189    key: Option<String>,
190}
191
192impl ser::SerializeMap for Entries<'_> {
193    type Ok = ();
194    type Error = serde_json::Error;
195
196    fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> serde_json::Result<()> {
197        match serde_json::to_value(key)? {
198            Value::String(key) => {
199                self.key = Some(key);
200                Ok(())
201            }
202            _ => Err(ser::Error::custom("a member name is text")),
203        }
204    }
205
206    fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> serde_json::Result<()> {
207        let key = self.key.take().unwrap_or_default();
208        // Header members are matched by name; a key that is no member's is
209        // written to the body like any other.
210        match self.fields.split.members.iter().find(|m| m.name == key) {
211            Some(member) => SerializeStruct::serialize_field(&mut self.fields, member.name, value),
212            None if self.fields.split.payload => Err(beside_payload()),
213            None => {
214                if !self.fields.first {
215                    self.fields.split.out.push(b',');
216                }
217                self.fields.first = false;
218                serde_json::to_writer(&mut *self.fields.split.out, &key)?;
219                self.fields.split.out.push(b':');
220                serde_json::to_writer(&mut *self.fields.split.out, value)
221            }
222        }
223    }
224
225    fn end(self) -> serde_json::Result<()> {
226        SerializeStruct::end(self.fields)
227    }
228}
229
230/// A header member's value as header text: a list is comma-separated.
231pub fn text(value: &Value) -> String {
232    match value {
233        Value::String(text) => text.clone(),
234        Value::Array(items) => crate::text::join_header(items.iter().map(text)),
235        other => other.to_string(),
236    }
237}
238
239fn beside_payload() -> serde_json::Error {
240    ser::Error::custom("a structure with a payload member has no body members")
241}
242
243fn not_a_structure() -> serde_json::Error {
244    ser::Error::custom("an output with header members is a structure")
245}
246
247impl<'s> Serializer for Split<'s> {
248    type Ok = ();
249    type Error = serde_json::Error;
250    type SerializeSeq = Impossible<(), serde_json::Error>;
251    type SerializeTuple = Impossible<(), serde_json::Error>;
252    type SerializeTupleStruct = Impossible<(), serde_json::Error>;
253    type SerializeTupleVariant = Impossible<(), serde_json::Error>;
254    type SerializeMap = Entries<'s>;
255    type SerializeStruct = Fields<'s>;
256    type SerializeStructVariant = Impossible<(), serde_json::Error>;
257
258    fn serialize_struct(self, _: &'static str, _: usize) -> serde_json::Result<Fields<'s>> {
259        if !self.payload {
260            self.out.push(b'{');
261        }
262        Ok(Fields {
263            split: self,
264            first: true,
265        })
266    }
267
268    fn serialize_unit(self) -> serde_json::Result<()> {
269        if !self.payload {
270            self.out.extend_from_slice(b"{}");
271        }
272        Ok(())
273    }
274
275    fn serialize_bool(self, _: bool) -> serde_json::Result<()> {
276        Err(not_a_structure())
277    }
278    fn serialize_i8(self, _: i8) -> serde_json::Result<()> {
279        Err(not_a_structure())
280    }
281    fn serialize_i16(self, _: i16) -> serde_json::Result<()> {
282        Err(not_a_structure())
283    }
284    fn serialize_i32(self, _: i32) -> serde_json::Result<()> {
285        Err(not_a_structure())
286    }
287    fn serialize_i64(self, _: i64) -> serde_json::Result<()> {
288        Err(not_a_structure())
289    }
290    fn serialize_u8(self, _: u8) -> serde_json::Result<()> {
291        Err(not_a_structure())
292    }
293    fn serialize_u16(self, _: u16) -> serde_json::Result<()> {
294        Err(not_a_structure())
295    }
296    fn serialize_u32(self, _: u32) -> serde_json::Result<()> {
297        Err(not_a_structure())
298    }
299    fn serialize_u64(self, _: u64) -> serde_json::Result<()> {
300        Err(not_a_structure())
301    }
302    fn serialize_f32(self, _: f32) -> serde_json::Result<()> {
303        Err(not_a_structure())
304    }
305    fn serialize_f64(self, _: f64) -> serde_json::Result<()> {
306        Err(not_a_structure())
307    }
308    fn serialize_char(self, _: char) -> serde_json::Result<()> {
309        Err(not_a_structure())
310    }
311    fn serialize_str(self, _: &str) -> serde_json::Result<()> {
312        Err(not_a_structure())
313    }
314    fn serialize_bytes(self, _: &[u8]) -> serde_json::Result<()> {
315        Err(not_a_structure())
316    }
317    fn serialize_none(self) -> serde_json::Result<()> {
318        Err(not_a_structure())
319    }
320    fn serialize_some<T: Serialize + ?Sized>(self, _: &T) -> serde_json::Result<()> {
321        Err(not_a_structure())
322    }
323    fn serialize_unit_struct(self, _: &'static str) -> serde_json::Result<()> {
324        self.serialize_unit()
325    }
326    fn serialize_unit_variant(
327        self,
328        _: &'static str,
329        _: u32,
330        _: &'static str,
331    ) -> serde_json::Result<()> {
332        Err(not_a_structure())
333    }
334    fn serialize_newtype_struct<T: Serialize + ?Sized>(
335        self,
336        _: &'static str,
337        value: &T,
338    ) -> serde_json::Result<()> {
339        value.serialize(self)
340    }
341    fn serialize_newtype_variant<T: Serialize + ?Sized>(
342        self,
343        _: &'static str,
344        _: u32,
345        _: &'static str,
346        _: &T,
347    ) -> serde_json::Result<()> {
348        Err(not_a_structure())
349    }
350    fn serialize_seq(self, _: Option<usize>) -> serde_json::Result<Self::SerializeSeq> {
351        Err(not_a_structure())
352    }
353    fn serialize_tuple(self, _: usize) -> serde_json::Result<Self::SerializeTuple> {
354        Err(not_a_structure())
355    }
356    fn serialize_tuple_struct(
357        self,
358        _: &'static str,
359        _: usize,
360    ) -> serde_json::Result<Self::SerializeTupleStruct> {
361        Err(not_a_structure())
362    }
363    fn serialize_tuple_variant(
364        self,
365        _: &'static str,
366        _: u32,
367        _: &'static str,
368        _: usize,
369    ) -> serde_json::Result<Self::SerializeTupleVariant> {
370        Err(not_a_structure())
371    }
372    fn serialize_map(self, _: Option<usize>) -> serde_json::Result<Self::SerializeMap> {
373        if !self.payload {
374            self.out.push(b'{');
375        }
376        Ok(Entries {
377            fields: Fields {
378                split: self,
379                first: true,
380            },
381            key: None,
382        })
383    }
384    fn serialize_struct_variant(
385        self,
386        _: &'static str,
387        _: u32,
388        _: &'static str,
389        _: usize,
390    ) -> serde_json::Result<Self::SerializeStructVariant> {
391        Err(not_a_structure())
392    }
393}
394
395/// Writes a payload member's bytes, raw. A `Blob` gives its bytes to a
396/// serializer that is not human-readable; a JSON value of one (the default
397/// `Output::write_json_split`) is base64 text, decoded here.
398struct Raw<'s> {
399    out: &'s mut Vec<u8>,
400}
401
402fn not_a_blob() -> serde_json::Error {
403    ser::Error::custom("a payload member is a blob")
404}
405
406impl Serializer for Raw<'_> {
407    type Ok = ();
408    type Error = serde_json::Error;
409    type SerializeSeq = Impossible<(), serde_json::Error>;
410    type SerializeTuple = Impossible<(), serde_json::Error>;
411    type SerializeTupleStruct = Impossible<(), serde_json::Error>;
412    type SerializeTupleVariant = Impossible<(), serde_json::Error>;
413    type SerializeMap = Impossible<(), serde_json::Error>;
414    type SerializeStruct = Impossible<(), serde_json::Error>;
415    type SerializeStructVariant = Impossible<(), serde_json::Error>;
416
417    fn is_human_readable(&self) -> bool {
418        false
419    }
420
421    fn serialize_bytes(self, bytes: &[u8]) -> serde_json::Result<()> {
422        self.out.extend_from_slice(bytes);
423        Ok(())
424    }
425    fn serialize_str(self, text: &str) -> serde_json::Result<()> {
426        STANDARD
427            .decode_vec(text, self.out)
428            .map_err(|_| ser::Error::custom("a payload's JSON value is base64"))
429    }
430    fn serialize_none(self) -> serde_json::Result<()> {
431        Ok(())
432    }
433    fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> serde_json::Result<()> {
434        value.serialize(self)
435    }
436    fn serialize_unit(self) -> serde_json::Result<()> {
437        Ok(())
438    }
439    fn serialize_newtype_struct<T: Serialize + ?Sized>(
440        self,
441        _: &'static str,
442        value: &T,
443    ) -> serde_json::Result<()> {
444        value.serialize(self)
445    }
446
447    fn serialize_bool(self, _: bool) -> serde_json::Result<()> {
448        Err(not_a_blob())
449    }
450    fn serialize_i8(self, _: i8) -> serde_json::Result<()> {
451        Err(not_a_blob())
452    }
453    fn serialize_i16(self, _: i16) -> serde_json::Result<()> {
454        Err(not_a_blob())
455    }
456    fn serialize_i32(self, _: i32) -> serde_json::Result<()> {
457        Err(not_a_blob())
458    }
459    fn serialize_i64(self, _: i64) -> serde_json::Result<()> {
460        Err(not_a_blob())
461    }
462    fn serialize_u8(self, _: u8) -> serde_json::Result<()> {
463        Err(not_a_blob())
464    }
465    fn serialize_u16(self, _: u16) -> serde_json::Result<()> {
466        Err(not_a_blob())
467    }
468    fn serialize_u32(self, _: u32) -> serde_json::Result<()> {
469        Err(not_a_blob())
470    }
471    fn serialize_u64(self, _: u64) -> serde_json::Result<()> {
472        Err(not_a_blob())
473    }
474    fn serialize_f32(self, _: f32) -> serde_json::Result<()> {
475        Err(not_a_blob())
476    }
477    fn serialize_f64(self, _: f64) -> serde_json::Result<()> {
478        Err(not_a_blob())
479    }
480    fn serialize_char(self, _: char) -> serde_json::Result<()> {
481        Err(not_a_blob())
482    }
483    fn serialize_unit_struct(self, _: &'static str) -> serde_json::Result<()> {
484        Err(not_a_blob())
485    }
486    fn serialize_unit_variant(
487        self,
488        _: &'static str,
489        _: u32,
490        _: &'static str,
491    ) -> serde_json::Result<()> {
492        Err(not_a_blob())
493    }
494    fn serialize_newtype_variant<T: Serialize + ?Sized>(
495        self,
496        _: &'static str,
497        _: u32,
498        _: &'static str,
499        _: &T,
500    ) -> serde_json::Result<()> {
501        Err(not_a_blob())
502    }
503    fn serialize_seq(self, _: Option<usize>) -> serde_json::Result<Self::SerializeSeq> {
504        Err(not_a_blob())
505    }
506    fn serialize_tuple(self, _: usize) -> serde_json::Result<Self::SerializeTuple> {
507        Err(not_a_blob())
508    }
509    fn serialize_tuple_struct(
510        self,
511        _: &'static str,
512        _: usize,
513    ) -> serde_json::Result<Self::SerializeTupleStruct> {
514        Err(not_a_blob())
515    }
516    fn serialize_tuple_variant(
517        self,
518        _: &'static str,
519        _: u32,
520        _: &'static str,
521        _: usize,
522    ) -> serde_json::Result<Self::SerializeTupleVariant> {
523        Err(not_a_blob())
524    }
525    fn serialize_map(self, _: Option<usize>) -> serde_json::Result<Self::SerializeMap> {
526        Err(not_a_blob())
527    }
528    fn serialize_struct(
529        self,
530        _: &'static str,
531        _: usize,
532    ) -> serde_json::Result<Self::SerializeStruct> {
533        Err(not_a_blob())
534    }
535    fn serialize_struct_variant(
536        self,
537        _: &'static str,
538        _: u32,
539        _: &'static str,
540        _: usize,
541    ) -> serde_json::Result<Self::SerializeStructVariant> {
542        Err(not_a_blob())
543    }
544}
545
546#[cfg(test)]
547mod tests {
548    use serde::Serialize;
549
550    use super::*;
551    use crate::operation::Scalar;
552
553    #[derive(Serialize)]
554    #[serde(rename_all = "camelCase")]
555    struct Output {
556        city: &'static str,
557        #[serde(skip_serializing_if = "Option::is_none")]
558        forecast: Option<u32>,
559        request_id: Option<&'static str>,
560        tags: Vec<&'static str>,
561    }
562
563    const MEMBERS: &[MemberInfo] = &[
564        MemberInfo {
565            name: "city",
566            location: Location::Body,
567            scalar: Scalar::Json,
568            redaction: &crate::operation::Redaction::Public,
569            traits: &[],
570        },
571        MemberInfo {
572            name: "requestId",
573            location: Location::Header("x-request-id"),
574            scalar: Scalar::String,
575            redaction: &crate::operation::Redaction::Public,
576            traits: &[],
577        },
578        MemberInfo {
579            name: "tags",
580            location: Location::Header("x-tags"),
581            scalar: Scalar::List(&Scalar::String),
582            redaction: &crate::operation::Redaction::Public,
583            traits: &[],
584        },
585    ];
586
587    #[test]
588    fn header_members_leave_the_body_as_header_text() {
589        let output = Output {
590            city: "Oslo",
591            forecast: None,
592            request_id: Some("r-1"),
593            tags: vec!["a", "b,c"],
594        };
595        let mut body = Vec::new();
596        let headers = write(&output, MEMBERS, &mut body).unwrap();
597        assert_eq!(std::str::from_utf8(&body).unwrap(), r#"{"city":"Oslo"}"#);
598        assert_eq!(
599            headers,
600            [
601                ("x-request-id", "r-1".to_owned()),
602                ("x-tags", "a, \"b,c\"".to_owned())
603            ]
604        );
605    }
606
607    #[test]
608    fn an_absent_or_empty_header_member_sends_no_header() {
609        let output = Output {
610            city: "Oslo",
611            forecast: Some(3),
612            request_id: None,
613            tags: vec![],
614        };
615        let mut body = Vec::new();
616        let headers = write(&output, MEMBERS, &mut body).unwrap();
617        assert_eq!(
618            std::str::from_utf8(&body).unwrap(),
619            r#"{"city":"Oslo","forecast":3}"#
620        );
621        assert!(headers.is_empty(), "{headers:?}");
622    }
623
624    #[derive(Serialize)]
625    struct Upload {
626        caption: Option<&'static str>,
627        #[serde(skip_serializing_if = "Option::is_none")]
628        photo: Option<crate::blob::Blob>,
629    }
630
631    const UPLOAD: &[MemberInfo] = &[
632        MemberInfo {
633            name: "caption",
634            location: Location::Header("x-caption"),
635            scalar: Scalar::String,
636            redaction: &crate::operation::Redaction::Public,
637            traits: &[],
638        },
639        MemberInfo {
640            name: "photo",
641            location: Location::Payload("image/jpeg"),
642            scalar: Scalar::Json,
643            redaction: &crate::operation::Redaction::Public,
644            traits: &[],
645        },
646    ];
647
648    #[test]
649    fn a_payload_member_is_the_body_raw() {
650        let bytes: &'static [u8] = b"\xff\xd8{\"not\":\"json\"}";
651        let upload = Upload {
652            caption: Some("sea"),
653            photo: Some(bytes.into()),
654        };
655        let mut body = Vec::new();
656        let headers = write(&upload, UPLOAD, &mut body).unwrap();
657        assert_eq!(body, bytes);
658        assert_eq!(headers, [("x-caption", "sea".to_owned())]);
659
660        // Through a JSON value, the default `Output` path, the bytes are the same.
661        let mut body = Vec::new();
662        write(&serde_json::to_value(&upload).unwrap(), UPLOAD, &mut body).unwrap();
663        assert_eq!(body, bytes);
664
665        let mut body = Vec::new();
666        let bound = write_bound(&upload, UPLOAD, &mut body).unwrap();
667        assert_eq!(body, bytes);
668        assert_eq!(bound.len(), 1);
669        assert_eq!(bound[0].0.name, "caption");
670    }
671
672    #[derive(Serialize)]
673    struct Kinds {
674        #[serde(skip_serializing_if = "Option::is_none")]
675        text: Option<&'static str>,
676        #[serde(skip_serializing_if = "Option::is_none")]
677        record: Option<serde_json::Value>,
678    }
679
680    fn kind(location: Location, name: &'static str) -> MemberInfo {
681        MemberInfo {
682            name,
683            location,
684            scalar: Scalar::Json,
685            redaction: &crate::operation::Redaction::Public,
686            traits: &[],
687        }
688    }
689
690    #[test]
691    fn text_and_document_payloads_are_the_body() {
692        let text = [
693            kind(Location::TextPayload("text/plain"), "text"),
694            kind(Location::Body, "record"),
695        ];
696        let mut body = Vec::new();
697        let value = Kinds {
698            text: Some("h\u{e9}llo"),
699            record: None,
700        };
701        write(&value, &text, &mut body).unwrap();
702        assert_eq!(body, "h\u{e9}llo".as_bytes());
703
704        let document = [
705            kind(Location::Body, "text"),
706            kind(Location::DocumentPayload("application/json"), "record"),
707        ];
708        for (record, expected) in [
709            (
710                Some(serde_json::json!({"a":[1,null]})),
711                &br#"{"a":[1,null]}"#[..],
712            ),
713            (Some(serde_json::Value::Null), &b"null"[..]),
714            (None, &b""[..]),
715        ] {
716            let mut body = Vec::new();
717            let value = Kinds { text: None, record };
718            write(&value, &document, &mut body).unwrap();
719            assert_eq!(body, expected);
720        }
721    }
722
723    #[test]
724    fn an_absent_payload_writes_no_body() {
725        let upload = Upload {
726            caption: None,
727            photo: None,
728        };
729        let mut body = Vec::new();
730        assert!(write(&upload, UPLOAD, &mut body).unwrap().is_empty());
731        assert!(body.is_empty());
732    }
733}