crucible-wire 0.10.0

What a crucible server and client share about the wire: operation descriptions, the error model, validation, timestamps and the JSON readers and writers
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Writing a structure as a JSON body with its header members taken out, in
//! one pass: the body goes straight to bytes, and each header member becomes
//! header text on the way. A structure with an `@httpPayload` member writes
//! that member's bytes as the body instead, raw.

use serde::ser::{self, Impossible, Serialize, SerializeStruct, Serializer};
use serde_json::Value;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;

use crate::operation::{Location, MemberInfo};

/// Writes `value` (a structure) into `out` as a JSON object without the
/// members `members` binds to headers, and returns those as (header, text).
/// With a payload member, `out` gets that member's bytes instead.
pub fn write<T: Serialize + ?Sized>(
    value: &T,
    members: &[MemberInfo],
    out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static str, String)>> {
    write_typed(value, members, None, out)
}

/// [`write`], with `"__type": type_name` appended when one is given: how an
/// error body names its error.
pub fn write_typed<T: Serialize + ?Sized>(
    value: &T,
    members: &[MemberInfo],
    type_name: Option<&'static str>,
    out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static str, String)>> {
    let mut taken = Vec::new();
    value.serialize(Split {
        members,
        take: Take::Headers,
        type_name,
        payload: Location::payload(members).is_some(),
        out,
        taken: &mut taken,
    })?;
    taken
        .into_iter()
        .filter_map(|(member, value)| match member.location {
            Location::Header(header) => Some(
                crate::text::header_text(&value, member.scalar)
                    .map(|text| (header, text))
                    .map_err(<serde_json::Error as ser::Error>::custom),
            ),
            _ => None,
        })
        .collect()
}

/// Writes `value` (an input) into `out` as a JSON object of its body
/// members only, and returns every bound member (label, query parameter or
/// header) with its value: what a client needs to build the request. With a
/// payload member, `out` gets that member's bytes instead.
pub fn write_bound<T: Serialize + ?Sized>(
    value: &T,
    members: &'static [MemberInfo],
    out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static MemberInfo, Value)>> {
    let mut taken = Vec::new();
    value.serialize(Split {
        members,
        take: Take::Bound,
        type_name: None,
        payload: Location::payload(members).is_some(),
        out,
        taken: &mut taken,
    })?;
    Ok(taken
        .into_iter()
        .map(|(member, value)| {
            let member = members
                .iter()
                .find(|m| m.name == member.name)
                .expect("taken members are this structure's");
            (member, value)
        })
        .collect())
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Take {
    Headers,
    Bound,
}

struct Split<'s> {
    members: &'s [MemberInfo],
    take: Take,
    type_name: Option<&'static str>,
    /// The structure has a payload member: `out` is its bytes, not JSON.
    payload: bool,
    out: &'s mut Vec<u8>,
    taken: &'s mut Vec<(MemberInfo, Value)>,
}

struct Fields<'s> {
    split: Split<'s>,
    first: bool,
}

impl SerializeStruct for Fields<'_> {
    type Ok = ();
    type Error = serde_json::Error;

    fn serialize_field<T: Serialize + ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> serde_json::Result<()> {
        if self.split.payload {
            let member = self.split.members.iter().find(|member| member.name == key);
            match member.map(|member| member.location) {
                Some(Location::Payload(_)) => {
                    return value.serialize(Raw {
                        out: &mut *self.split.out,
                    });
                }
                Some(Location::TextPayload(_)) => {
                    return match serde_json::to_value(value)? {
                        Value::String(text) => {
                            self.split.out.extend_from_slice(text.as_bytes());
                            Ok(())
                        }
                        Value::Null => Ok(()),
                        _ => Err(ser::Error::custom("a text payload member is a string")),
                    };
                }
                Some(Location::DocumentPayload(_)) => {
                    // Model serde owns omission; a serialized null is a
                    // present document value and must remain on the wire.
                    serde_json::to_writer(&mut *self.split.out, value)?;
                    return Ok(());
                }
                _ => {}
            }
        }
        let take = self.split.take;
        let taken = self.split.members.iter().find(|member| {
            member.name == key
                && matches!(
                    (take, member.location),
                    (_, Location::Header(_)) | (Take::Bound, Location::Label | Location::Query(_))
                )
        });
        if let Some(member) = taken {
            let value = serde_json::to_value(value)?;
            let empty = matches!(&value, Value::Array(items) if items.is_empty());
            if !value.is_null() && !empty {
                self.split.taken.push((*member, value));
            }
            return Ok(());
        }
        if self.split.payload {
            return Err(beside_payload());
        }
        if !self.first {
            self.split.out.push(b',');
        }
        self.first = false;
        serde_json::to_writer(&mut *self.split.out, key)?;
        self.split.out.push(b':');
        serde_json::to_writer(&mut *self.split.out, value)
    }

    fn end(self) -> serde_json::Result<()> {
        if self.split.payload {
            return Ok(());
        }
        if let Some(name) = self.split.type_name {
            if !self.first {
                self.split.out.push(b',');
            }
            self.split.out.extend_from_slice(b"\"__type\":");
            serde_json::to_writer(&mut *self.split.out, name)?;
        }
        self.split.out.push(b'}');
        Ok(())
    }
}

/// A map with string keys (a JSON object value), written like a structure.
struct Entries<'s> {
    fields: Fields<'s>,
    key: Option<String>,
}

impl ser::SerializeMap for Entries<'_> {
    type Ok = ();
    type Error = serde_json::Error;

    fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> serde_json::Result<()> {
        match serde_json::to_value(key)? {
            Value::String(key) => {
                self.key = Some(key);
                Ok(())
            }
            _ => Err(ser::Error::custom("a member name is text")),
        }
    }

    fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> serde_json::Result<()> {
        let key = self.key.take().unwrap_or_default();
        // Header members are matched by name; a key that is no member's is
        // written to the body like any other.
        match self.fields.split.members.iter().find(|m| m.name == key) {
            Some(member) => SerializeStruct::serialize_field(&mut self.fields, member.name, value),
            None if self.fields.split.payload => Err(beside_payload()),
            None => {
                if !self.fields.first {
                    self.fields.split.out.push(b',');
                }
                self.fields.first = false;
                serde_json::to_writer(&mut *self.fields.split.out, &key)?;
                self.fields.split.out.push(b':');
                serde_json::to_writer(&mut *self.fields.split.out, value)
            }
        }
    }

    fn end(self) -> serde_json::Result<()> {
        SerializeStruct::end(self.fields)
    }
}

/// A header member's value as header text: a list is comma-separated.
pub fn text(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Array(items) => crate::text::join_header(items.iter().map(text)),
        other => other.to_string(),
    }
}

fn beside_payload() -> serde_json::Error {
    ser::Error::custom("a structure with a payload member has no body members")
}

fn not_a_structure() -> serde_json::Error {
    ser::Error::custom("an output with header members is a structure")
}

impl<'s> Serializer for Split<'s> {
    type Ok = ();
    type Error = serde_json::Error;
    type SerializeSeq = Impossible<(), serde_json::Error>;
    type SerializeTuple = Impossible<(), serde_json::Error>;
    type SerializeTupleStruct = Impossible<(), serde_json::Error>;
    type SerializeTupleVariant = Impossible<(), serde_json::Error>;
    type SerializeMap = Entries<'s>;
    type SerializeStruct = Fields<'s>;
    type SerializeStructVariant = Impossible<(), serde_json::Error>;

    fn serialize_struct(self, _: &'static str, _: usize) -> serde_json::Result<Fields<'s>> {
        if !self.payload {
            self.out.push(b'{');
        }
        Ok(Fields {
            split: self,
            first: true,
        })
    }

    fn serialize_unit(self) -> serde_json::Result<()> {
        if !self.payload {
            self.out.extend_from_slice(b"{}");
        }
        Ok(())
    }

    fn serialize_bool(self, _: bool) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_i8(self, _: i8) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_i16(self, _: i16) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_i32(self, _: i32) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_i64(self, _: i64) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_u8(self, _: u8) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_u16(self, _: u16) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_u32(self, _: u32) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_u64(self, _: u64) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_f32(self, _: f32) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_f64(self, _: f64) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_char(self, _: char) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_str(self, _: &str) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_bytes(self, _: &[u8]) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_none(self) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_some<T: Serialize + ?Sized>(self, _: &T) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_unit_struct(self, _: &'static str) -> serde_json::Result<()> {
        self.serialize_unit()
    }
    fn serialize_unit_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
    ) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_newtype_struct<T: Serialize + ?Sized>(
        self,
        _: &'static str,
        value: &T,
    ) -> serde_json::Result<()> {
        value.serialize(self)
    }
    fn serialize_newtype_variant<T: Serialize + ?Sized>(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: &T,
    ) -> serde_json::Result<()> {
        Err(not_a_structure())
    }
    fn serialize_seq(self, _: Option<usize>) -> serde_json::Result<Self::SerializeSeq> {
        Err(not_a_structure())
    }
    fn serialize_tuple(self, _: usize) -> serde_json::Result<Self::SerializeTuple> {
        Err(not_a_structure())
    }
    fn serialize_tuple_struct(
        self,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeTupleStruct> {
        Err(not_a_structure())
    }
    fn serialize_tuple_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeTupleVariant> {
        Err(not_a_structure())
    }
    fn serialize_map(self, _: Option<usize>) -> serde_json::Result<Self::SerializeMap> {
        if !self.payload {
            self.out.push(b'{');
        }
        Ok(Entries {
            fields: Fields {
                split: self,
                first: true,
            },
            key: None,
        })
    }
    fn serialize_struct_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeStructVariant> {
        Err(not_a_structure())
    }
}

/// Writes a payload member's bytes, raw. A `Blob` gives its bytes to a
/// serializer that is not human-readable; a JSON value of one (the default
/// `Output::write_json_split`) is base64 text, decoded here.
struct Raw<'s> {
    out: &'s mut Vec<u8>,
}

fn not_a_blob() -> serde_json::Error {
    ser::Error::custom("a payload member is a blob")
}

impl Serializer for Raw<'_> {
    type Ok = ();
    type Error = serde_json::Error;
    type SerializeSeq = Impossible<(), serde_json::Error>;
    type SerializeTuple = Impossible<(), serde_json::Error>;
    type SerializeTupleStruct = Impossible<(), serde_json::Error>;
    type SerializeTupleVariant = Impossible<(), serde_json::Error>;
    type SerializeMap = Impossible<(), serde_json::Error>;
    type SerializeStruct = Impossible<(), serde_json::Error>;
    type SerializeStructVariant = Impossible<(), serde_json::Error>;

    fn is_human_readable(&self) -> bool {
        false
    }

    fn serialize_bytes(self, bytes: &[u8]) -> serde_json::Result<()> {
        self.out.extend_from_slice(bytes);
        Ok(())
    }
    fn serialize_str(self, text: &str) -> serde_json::Result<()> {
        STANDARD
            .decode_vec(text, self.out)
            .map_err(|_| ser::Error::custom("a payload's JSON value is base64"))
    }
    fn serialize_none(self) -> serde_json::Result<()> {
        Ok(())
    }
    fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> serde_json::Result<()> {
        value.serialize(self)
    }
    fn serialize_unit(self) -> serde_json::Result<()> {
        Ok(())
    }
    fn serialize_newtype_struct<T: Serialize + ?Sized>(
        self,
        _: &'static str,
        value: &T,
    ) -> serde_json::Result<()> {
        value.serialize(self)
    }

    fn serialize_bool(self, _: bool) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_i8(self, _: i8) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_i16(self, _: i16) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_i32(self, _: i32) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_i64(self, _: i64) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_u8(self, _: u8) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_u16(self, _: u16) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_u32(self, _: u32) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_u64(self, _: u64) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_f32(self, _: f32) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_f64(self, _: f64) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_char(self, _: char) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_unit_struct(self, _: &'static str) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_unit_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
    ) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_newtype_variant<T: Serialize + ?Sized>(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: &T,
    ) -> serde_json::Result<()> {
        Err(not_a_blob())
    }
    fn serialize_seq(self, _: Option<usize>) -> serde_json::Result<Self::SerializeSeq> {
        Err(not_a_blob())
    }
    fn serialize_tuple(self, _: usize) -> serde_json::Result<Self::SerializeTuple> {
        Err(not_a_blob())
    }
    fn serialize_tuple_struct(
        self,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeTupleStruct> {
        Err(not_a_blob())
    }
    fn serialize_tuple_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeTupleVariant> {
        Err(not_a_blob())
    }
    fn serialize_map(self, _: Option<usize>) -> serde_json::Result<Self::SerializeMap> {
        Err(not_a_blob())
    }
    fn serialize_struct(
        self,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeStruct> {
        Err(not_a_blob())
    }
    fn serialize_struct_variant(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: usize,
    ) -> serde_json::Result<Self::SerializeStructVariant> {
        Err(not_a_blob())
    }
}

#[cfg(test)]
mod tests {
    use serde::Serialize;

    use super::*;
    use crate::operation::Scalar;

    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    struct Output {
        city: &'static str,
        #[serde(skip_serializing_if = "Option::is_none")]
        forecast: Option<u32>,
        request_id: Option<&'static str>,
        tags: Vec<&'static str>,
    }

    const MEMBERS: &[MemberInfo] = &[
        MemberInfo {
            name: "city",
            location: Location::Body,
            scalar: Scalar::Json,
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        },
        MemberInfo {
            name: "requestId",
            location: Location::Header("x-request-id"),
            scalar: Scalar::String,
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        },
        MemberInfo {
            name: "tags",
            location: Location::Header("x-tags"),
            scalar: Scalar::List(&Scalar::String),
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        },
    ];

    #[test]
    fn header_members_leave_the_body_as_header_text() {
        let output = Output {
            city: "Oslo",
            forecast: None,
            request_id: Some("r-1"),
            tags: vec!["a", "b,c"],
        };
        let mut body = Vec::new();
        let headers = write(&output, MEMBERS, &mut body).unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), r#"{"city":"Oslo"}"#);
        assert_eq!(
            headers,
            [
                ("x-request-id", "r-1".to_owned()),
                ("x-tags", "a, \"b,c\"".to_owned())
            ]
        );
    }

    #[test]
    fn an_absent_or_empty_header_member_sends_no_header() {
        let output = Output {
            city: "Oslo",
            forecast: Some(3),
            request_id: None,
            tags: vec![],
        };
        let mut body = Vec::new();
        let headers = write(&output, MEMBERS, &mut body).unwrap();
        assert_eq!(
            std::str::from_utf8(&body).unwrap(),
            r#"{"city":"Oslo","forecast":3}"#
        );
        assert!(headers.is_empty(), "{headers:?}");
    }

    #[derive(Serialize)]
    struct Upload {
        caption: Option<&'static str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        photo: Option<crate::blob::Blob>,
    }

    const UPLOAD: &[MemberInfo] = &[
        MemberInfo {
            name: "caption",
            location: Location::Header("x-caption"),
            scalar: Scalar::String,
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        },
        MemberInfo {
            name: "photo",
            location: Location::Payload("image/jpeg"),
            scalar: Scalar::Json,
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        },
    ];

    #[test]
    fn a_payload_member_is_the_body_raw() {
        let bytes: &'static [u8] = b"\xff\xd8{\"not\":\"json\"}";
        let upload = Upload {
            caption: Some("sea"),
            photo: Some(bytes.into()),
        };
        let mut body = Vec::new();
        let headers = write(&upload, UPLOAD, &mut body).unwrap();
        assert_eq!(body, bytes);
        assert_eq!(headers, [("x-caption", "sea".to_owned())]);

        // Through a JSON value, the default `Output` path, the bytes are the same.
        let mut body = Vec::new();
        write(&serde_json::to_value(&upload).unwrap(), UPLOAD, &mut body).unwrap();
        assert_eq!(body, bytes);

        let mut body = Vec::new();
        let bound = write_bound(&upload, UPLOAD, &mut body).unwrap();
        assert_eq!(body, bytes);
        assert_eq!(bound.len(), 1);
        assert_eq!(bound[0].0.name, "caption");
    }

    #[derive(Serialize)]
    struct Kinds {
        #[serde(skip_serializing_if = "Option::is_none")]
        text: Option<&'static str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        record: Option<serde_json::Value>,
    }

    fn kind(location: Location, name: &'static str) -> MemberInfo {
        MemberInfo {
            name,
            location,
            scalar: Scalar::Json,
            redaction: &crate::operation::Redaction::Public,
            traits: &[],
        }
    }

    #[test]
    fn text_and_document_payloads_are_the_body() {
        let text = [
            kind(Location::TextPayload("text/plain"), "text"),
            kind(Location::Body, "record"),
        ];
        let mut body = Vec::new();
        let value = Kinds {
            text: Some("h\u{e9}llo"),
            record: None,
        };
        write(&value, &text, &mut body).unwrap();
        assert_eq!(body, "h\u{e9}llo".as_bytes());

        let document = [
            kind(Location::Body, "text"),
            kind(Location::DocumentPayload("application/json"), "record"),
        ];
        for (record, expected) in [
            (
                Some(serde_json::json!({"a":[1,null]})),
                &br#"{"a":[1,null]}"#[..],
            ),
            (Some(serde_json::Value::Null), &b"null"[..]),
            (None, &b""[..]),
        ] {
            let mut body = Vec::new();
            let value = Kinds { text: None, record };
            write(&value, &document, &mut body).unwrap();
            assert_eq!(body, expected);
        }
    }

    #[test]
    fn an_absent_payload_writes_no_body() {
        let upload = Upload {
            caption: None,
            photo: None,
        };
        let mut body = Vec::new();
        assert!(write(&upload, UPLOAD, &mut body).unwrap().is_empty());
        assert!(body.is_empty());
    }
}