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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! Reading an input from its bound members (labels, query parameters,
//! headers) and its JSON body in one pass: a deserializer that presents both
//! as one map, so the typed input is built straight from the request with no
//! JSON value in between. An `@httpPayload` member is bound too: the body's
//! bytes, handed to the `Blob` without a copy.

use std::borrow::Cow;
use std::marker::PhantomData;

use bytes::Bytes;
use serde::de::value::{BorrowedStrDeserializer, CowStrDeserializer};
use serde::de::{
    self, DeserializeOwned, DeserializeSeed, Deserializer, IgnoredAny, IntoDeserializer, MapAccess,
    SeqAccess, Visitor,
};

use crate::object::Objects;
use crate::operation::{Location, MemberInfo, Scalar, TimestampFormat};
use crate::{blob, text, time};

/// A bound member's value, already checked against its kind, so a bad one
/// is a violation naming the parameter or header before deserializing starts.
#[derive(Debug, Clone, PartialEq)]
pub enum BoundValue<'a> {
    Text(Cow<'a, str>),
    Integer(i64),
    Float(f64),
    Number(serde_json::Number),
    Json(serde_json::Value),
    Boolean(bool),
    List(Vec<BoundValue<'a>>),
    /// A payload member: the whole body.
    Bytes(Bytes),
    /// A structure, union or document payload member: the whole body, JSON,
    /// read straight into the member's type.
    RawJson(&'a [u8]),
}

impl<'a> BoundValue<'a> {
    /// A bound member's text as its kind, or why it is not one: what a
    /// server reads from a label, query parameter or header, and a client
    /// from a response header.
    pub fn parse(text: Cow<'a, str>, scalar: Scalar) -> Result<Self, String> {
        match scalar {
            Scalar::String | Scalar::Json => Ok(Self::Text(text)),
            Scalar::BigInteger | Scalar::BigDecimal => {
                if scalar == Scalar::BigInteger {
                    text.parse::<crate::number::BigInteger>()
                        .map_err(|e| e.to_string())?;
                }
                text.parse()
                    .map(Self::Number)
                    .map_err(|error: serde_json::Error| error.to_string())
            }
            Scalar::Integer => text
                .parse::<i64>()
                .map(Self::Integer)
                .map_err(|_| "must be an integer".to_owned()),
            Scalar::EpochSeconds => {
                time::epoch_seconds::parse(&text)
                    .ok_or_else(|| "must be epoch seconds with nanosecond precision".to_owned())?;
                text.parse()
                    .map(Self::Number)
                    .map_err(|error: serde_json::Error| error.to_string())
            }
            Scalar::Float => text
                .parse::<f64>()
                .ok()
                .filter(|n| n.is_finite())
                .map(Self::Float)
                .ok_or_else(|| "must be a number".to_owned()),
            Scalar::Boolean => match &*text {
                "true" => Ok(Self::Boolean(true)),
                "false" => Ok(Self::Boolean(false)),
                _ => Err("must be true or false".to_owned()),
            },
            Scalar::DateTime => match time::parse_date_time(&text) {
                Some(_) => Ok(Self::Text(text)),
                None => Err("must be an RFC 3339 timestamp".to_owned()),
            },
            Scalar::HttpDate => match time::http_date::parse(&text) {
                Some(_) => Ok(Self::Text(text)),
                None => Err("must be an HTTP date".to_owned()),
            },
            Scalar::Timestamp { text: format, json } => {
                let time = time::parse(&text, format).ok_or_else(|| match format {
                    TimestampFormat::DateTime => "must be an RFC 3339 timestamp".to_owned(),
                    TimestampFormat::EpochSeconds => {
                        "must be epoch seconds with nanosecond precision".to_owned()
                    }
                    TimestampFormat::HttpDate => "must be an HTTP date".to_owned(),
                })?;
                Ok(match time::to_json(&time, json)? {
                    serde_json::Value::Number(number) => Self::Number(number),
                    serde_json::Value::String(text) => Self::Text(Cow::Owned(text)),
                    _ => unreachable!("timestamps are numbers or text"),
                })
            }
            Scalar::Base64 => {
                use base64::Engine;
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(text.as_bytes())
                    .map_err(|_| "must be base64".to_owned())?;
                String::from_utf8(bytes)
                    .map(|text| Self::Text(Cow::Owned(text)))
                    .map_err(|_| "must be base64 of UTF-8 text".to_owned())
            }
            Scalar::List(item) => if item.http_date() && !text.contains('"') {
                text::split_http_dates(&text)
            } else {
                text::split_header(&text)
            }
            .into_iter()
            .map(|item_text| Self::parse(Cow::Owned(item_text), *item))
            .collect::<Result<Vec<_>, _>>()
            .map(Self::List),
        }
    }
}

/// `T` from `body` (a JSON object, or empty for `{}`) with `bound` laid over
/// it. A body member that is also bound is ignored: the bound value wins.
pub fn read<'a, T: DeserializeOwned>(
    body: &'a [u8],
    bound: Vec<(&'static str, BoundValue<'a>)>,
) -> Result<T, serde_json::Error> {
    read_excluding(body, bound, &[], None)
}

/// Reads an HTTP input, keeping every member declared outside the body
/// out of the body even when its header, query parameter or payload is absent.
pub fn read_http<'a, T: DeserializeOwned>(
    body: &'a [u8],
    bound: Vec<(&'static str, BoundValue<'a>)>,
    members: &[MemberInfo],
) -> Result<T, serde_json::Error> {
    read_excluding(body, bound, members, None)
}

/// Reads an HTTP input while retaining the path of a deserialization failure.
pub fn read_http_tracked<'a, T: DeserializeOwned>(
    body: &'a [u8],
    bound: Vec<(&'static str, BoundValue<'a>)>,
    members: &[MemberInfo],
) -> Result<T, serde_path_to_error::Error<serde_json::Error>> {
    // HTTP has at most one JSON payload, carried outside the ordinary body.
    let payload = bound.iter().find_map(|(_, value)| match value {
        BoundValue::RawJson(json) => Some(*json),
        _ => None,
    });
    let mut track = serde_path_to_error::Track::new();
    read_excluding(body, bound, members, Some(&mut track)).map_err(|error| {
        // raw_json forwards syntax/EOF errors through de::Error::custom, losing
        // their category. On failure only, parse the payload to check syntax.
        // Value also validates UTF-8 and surrogates, which IgnoredAny skips.
        // Keep the original message, but omit a path for invalid JSON.
        let malformed_payload = payload.is_some_and(|json| {
            serde_json::from_slice::<serde_json::Value>(json)
                .is_err_and(|error| error.is_syntax() || error.is_eof())
        });
        let path = if malformed_payload {
            serde_path_to_error::Track::new().path()
        } else {
            track.path()
        };
        serde_path_to_error::Error::new(path, error)
    })
}

/// Body members named by `bound` or declared outside the body in `members`
/// are skipped; both are checked in place rather than collected per request.
fn read_excluding<'a, T: DeserializeOwned>(
    body: &'a [u8],
    bound: Vec<(&'static str, BoundValue<'a>)>,
    members: &[MemberInfo],
    track: Option<&mut serde_path_to_error::Track>,
) -> Result<T, serde_json::Error> {
    // A structure is read only from an object, in the body or a payload.
    if text::empty_json_body(body) {
        return deserialize_tracked(Objects(BoundOnly { bound }), track);
    }
    let mut json = serde_json::Deserializer::from_slice(body);
    let value = json.deserialize_map(Bridge {
        track,
        bound,
        members,
        target: PhantomData::<T>,
    })?;
    json.end()?;
    Ok(value)
}

fn deserialize_tracked<'de, T: serde::Deserialize<'de>, D: Deserializer<'de>>(
    deserializer: D,
    track: Option<&mut serde_path_to_error::Track>,
) -> Result<T, D::Error> {
    match track {
        Some(track) => T::deserialize(serde_path_to_error::Deserializer::new(deserializer, track)),
        None => T::deserialize(deserializer),
    }
}

/// Hands serde_json's map access to the target type, chained after the
/// bound members.
struct Bridge<'b, 'm, 't, T> {
    track: Option<&'t mut serde_path_to_error::Track>,
    bound: Vec<(&'static str, BoundValue<'b>)>,
    members: &'m [MemberInfo],
    target: PhantomData<T>,
}

impl<'de, T: DeserializeOwned> Visitor<'de> for Bridge<'de, '_, '_, T> {
    type Value = T;

    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("a JSON object")
    }

    fn visit_map<A: MapAccess<'de>>(self, json: A) -> Result<T, A::Error> {
        deserialize_tracked(
            Objects(Merged {
                access: Chain {
                    bound: self.bound,
                    next: 0,
                    members: self.members,
                    value: None,
                    json: Some(json),
                },
            }),
            self.track,
        )
    }
}

/// A deserializer over a ready map access: what the target type sees.
struct Merged<A> {
    access: A,
}

impl<'de, A: MapAccess<'de>> Deserializer<'de> for Merged<A> {
    type Error = A::Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, A::Error> {
        visitor.visit_map(self.access)
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
        option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum
        identifier ignored_any
    }
}

/// The bound members alone, for a request with no body.
struct BoundOnly<'b> {
    bound: Vec<(&'static str, BoundValue<'b>)>,
}

impl<'de> Deserializer<'de> for BoundOnly<'de> {
    type Error = serde_json::Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        visitor.visit_map(Chain::<'de, '_, NoBody> {
            bound: self.bound,
            next: 0,
            members: &[],
            value: None,
            json: None,
        })
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
        option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum
        identifier ignored_any
    }
}

/// The empty body's map access, so `Chain` has one shape.
struct NoBody;

impl<'de> MapAccess<'de> for NoBody {
    type Error = serde_json::Error;

    fn next_key_seed<K: DeserializeSeed<'de>>(
        &mut self,
        _: K,
    ) -> Result<Option<K::Value>, Self::Error> {
        Ok(None)
    }

    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, _: V) -> Result<V::Value, Self::Error> {
        Err(de::Error::custom("no value without a key"))
    }
}

/// Bound members first, then the body's members, skipping any the bound
/// members already gave.
struct Chain<'b, 'm, A> {
    /// Kept whole, not drained, so the body can be checked against the bound
    /// names after their values are handed out.
    bound: Vec<(&'static str, BoundValue<'b>)>,
    /// The next bound member to hand out.
    next: usize,
    members: &'m [MemberInfo],
    /// The bound value whose key was just handed out.
    value: Option<BoundValue<'b>>,
    json: Option<A>,
}

impl<'de, A: MapAccess<'de>> MapAccess<'de> for Chain<'de, '_, A> {
    type Error = A::Error;

    fn next_key_seed<K: DeserializeSeed<'de>>(
        &mut self,
        seed: K,
    ) -> Result<Option<K::Value>, A::Error> {
        if let Some((name, value)) = self.bound.get_mut(self.next) {
            self.next += 1;
            // The name stays for the body check; the value moves out, leaving
            // a placeholder nothing reads.
            self.value = Some(std::mem::replace(value, BoundValue::Boolean(false)));
            return seed
                .deserialize(BorrowedStrDeserializer::new(name))
                .map(Some);
        }
        let Some(json) = self.json.as_mut() else {
            return Ok(None);
        };
        loop {
            let Some(Key(key)) = json.next_key::<Key<'de>>()? else {
                return Ok(None);
            };
            if self.bound.iter().any(|(name, _)| *name == key)
                || self
                    .members
                    .iter()
                    .any(|member| member.location != Location::Body && member.name == key)
            {
                json.next_value::<IgnoredAny>()?;
                continue;
            }
            return seed.deserialize(CowStrDeserializer::new(key)).map(Some);
        }
    }

    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, A::Error> {
        match (self.value.take(), self.json.as_mut()) {
            (Some(value), _) => seed.deserialize(Bound::new(value)),
            (None, Some(json)) => json.next_value_seed(seed),
            (None, None) => Err(de::Error::custom("no value without a key")),
        }
    }
}

/// A map key, borrowed from the body when it has no escapes.
struct Key<'de>(Cow<'de, str>);

impl<'de> de::Deserialize<'de> for Key<'de> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct KeyVisitor;
        impl<'de> Visitor<'de> for KeyVisitor {
            type Value = Key<'de>;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a member name")
            }

            fn visit_borrowed_str<E: de::Error>(self, v: &'de str) -> Result<Key<'de>, E> {
                Ok(Key(Cow::Borrowed(v)))
            }

            fn visit_str<E: de::Error>(self, v: &str) -> Result<Key<'de>, E> {
                Ok(Key(Cow::Owned(v.to_owned())))
            }

            fn visit_string<E: de::Error>(self, v: String) -> Result<Key<'de>, E> {
                Ok(Key(Cow::Owned(v)))
            }
        }
        deserializer.deserialize_str(KeyVisitor)
    }
}

/// One bound value, deserialized as whatever the target member is.
struct Bound<'b, E> {
    value: BoundValue<'b>,
    error: PhantomData<E>,
}

impl<'b, E> Bound<'b, E> {
    fn new(value: BoundValue<'b>) -> Self {
        Self {
            value,
            error: PhantomData,
        }
    }
}

impl<'de, E: de::Error> Deserializer<'de> for Bound<'de, E> {
    type Error = E;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, E> {
        match self.value {
            BoundValue::Text(Cow::Borrowed(text)) => visitor.visit_borrowed_str(text),
            BoundValue::Text(Cow::Owned(text)) => visitor.visit_string(text),
            BoundValue::Integer(n) => visitor.visit_i64(n),
            BoundValue::Float(n) => visitor.visit_f64(n),
            BoundValue::Number(n) => n.deserialize_any(visitor).map_err(de::Error::custom),
            BoundValue::Json(value) => value.deserialize_any(visitor).map_err(de::Error::custom),
            BoundValue::Boolean(b) => visitor.visit_bool(b),
            BoundValue::List(items) => visitor.visit_seq(Items {
                items: items.into_iter(),
                error: PhantomData,
            }),
            BoundValue::Bytes(bytes) => visitor.visit_bytes(&bytes),
            BoundValue::RawJson(json) => raw_json(json, |de| de.deserialize_any(visitor)),
        }
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, E> {
        if let BoundValue::Float(value) = self.value {
            let narrowed = value as f32;
            // Guard the narrowing here rather than relying on Serde's float cast.
            if value.is_finite() && !narrowed.is_finite() {
                return Err(de::Error::custom("number out of range"));
            }
            visitor.visit_f32(narrowed)
        } else {
            self.deserialize_any(visitor)
        }
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        visitor: V,
    ) -> Result<V::Value, E> {
        match self.value {
            BoundValue::Bytes(bytes) if name == blob::TOKEN => {
                blob::hand_off(bytes, || visitor.visit_unit())
            }
            _ => self.deserialize_any(visitor),
        }
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, E> {
        match self.value {
            // A JSON payload reads as the same member would in a JSON body:
            // `null` is the member's explicit null (absent for a server
            // `Option`, `Field::Null` for a client), not a value of its type
            // made from null. Crucible JSON clients send an explicitly null
            // structure, union or document payload as `null`. A document
            // codec that keeps null reads the value without asking for an
            // option, so it still sees `Value::Null`.
            BoundValue::RawJson(json) => raw_json(json, |de| de.deserialize_option(visitor)),
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        name: &'static str,
        variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, E> {
        match self.value {
            BoundValue::Text(Cow::Borrowed(text)) => IntoDeserializer::<E>::into_deserializer(text)
                .deserialize_enum(name, variants, visitor),
            BoundValue::Text(Cow::Owned(text)) => IntoDeserializer::<E>::into_deserializer(text)
                .deserialize_enum(name, variants, visitor),
            BoundValue::RawJson(json) => {
                raw_json(json, |de| de.deserialize_enum(name, variants, visitor))
            }
            _ => Err(de::Error::custom("an enum value is text")),
        }
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f64 char str string bytes byte_buf
        unit unit_struct seq tuple tuple_struct map struct identifier ignored_any
    }
}

/// Reads all of `json` with `read`, refusing trailing data.
fn raw_json<'de, T, E: de::Error>(
    json: &'de [u8],
    read: impl FnOnce(
        &mut serde_json::Deserializer<serde_json::de::SliceRead<'de>>,
    ) -> Result<T, serde_json::Error>,
) -> Result<T, E> {
    let mut deserializer = serde_json::Deserializer::from_slice(json);
    let value = read(&mut deserializer).map_err(de::Error::custom)?;
    deserializer.end().map_err(de::Error::custom)?;
    Ok(value)
}

struct Items<'b, E> {
    items: std::vec::IntoIter<BoundValue<'b>>,
    error: PhantomData<E>,
}

impl<'de, E: de::Error> SeqAccess<'de> for Items<'de, E> {
    type Error = E;

    fn next_element_seed<T: DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, E> {
        self.items
            .next()
            .map(|item| seed.deserialize(Bound::new(item)))
            .transpose()
    }
}

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

    use super::*;

    #[test]
    fn bound_f32_overflow_is_rejected() {
        #[derive(Deserialize)]
        struct Single {
            value: f32,
        }
        for text in ["1e39", "-1e39"] {
            let value = BoundValue::parse(text.into(), Scalar::Float).unwrap();
            assert!(read::<Single>(b"", vec![("value", value)]).is_err());
        }
        let value = BoundValue::parse("0.1".into(), Scalar::Float).unwrap();
        assert_eq!(
            read::<Single>(b"", vec![("value", value)]).unwrap().value,
            0.1
        );
    }

    #[test]
    fn bound_non_finite_floats_are_refused() {
        for text in [
            "NaN",
            "Infinity",
            "-Infinity",
            "nan",
            "inf",
            "+Infinity",
            "1e400",
            "not-a-number",
        ] {
            assert!(
                BoundValue::parse(text.into(), Scalar::Float).is_err(),
                "{text}"
            );
        }
    }

    #[derive(Debug, Deserialize, PartialEq)]
    #[serde(rename_all = "camelCase")]
    enum Sky {
        Clear,
    }

    #[derive(Debug, Deserialize, PartialEq)]
    #[serde(rename_all = "camelCase")]
    struct Input {
        city_id: String,
        max_results: Option<i32>,
        tags: Option<Vec<String>>,
        sky: Option<Sky>,
        name: Option<String>,
        nested: Option<Nested>,
    }

    #[derive(Debug, Deserialize, PartialEq)]
    struct Nested {
        x: f64,
    }

    #[test]
    fn bound_members_and_body_read_as_one_object() {
        let bound = vec![
            ("cityId", BoundValue::Text(Cow::Borrowed("c-1"))),
            ("maxResults", BoundValue::Integer(5)),
            (
                "tags",
                BoundValue::List(vec![
                    BoundValue::Text("a".into()),
                    BoundValue::Text("b".into()),
                ]),
            ),
            ("sky", BoundValue::Text("clear".into())),
        ];
        let input: Input = read(
            br#"{"name":"Oslo","cityId":"ignored","nested":{"x":1.5}}"#,
            bound,
        )
        .unwrap();
        assert_eq!(
            input,
            Input {
                city_id: "c-1".into(),
                max_results: Some(5),
                tags: Some(vec!["a".into(), "b".into()]),
                sky: Some(Sky::Clear),
                name: Some("Oslo".into()),
                nested: Some(Nested { x: 1.5 }),
            }
        );
    }

    #[test]
    fn an_empty_body_reads_the_bound_members_alone() {
        let input: Input = read(b"", vec![("cityId", BoundValue::Text("c-2".into()))]).unwrap();
        assert_eq!(input.city_id, "c-2");
        assert_eq!(input.name, None);
    }

    #[test]
    fn http_read_excludes_absent_bindings_but_keeps_body_members() {
        use crate::operation::Redaction;
        let members = [
            MemberInfo {
                name: "cityId",
                location: Location::Label,
                scalar: Scalar::String,
                redaction: &Redaction::Public,
                traits: &[],
            },
            MemberInfo {
                name: "maxResults",
                location: Location::Query("max"),
                scalar: Scalar::Integer,
                redaction: &Redaction::Public,
                traits: &[],
            },
            MemberInfo {
                name: "name",
                location: Location::Body,
                scalar: Scalar::String,
                redaction: &Redaction::Public,
                traits: &[],
            },
        ];
        let input: Input = read_http(
            br#"{"cityId":"body-copy","maxResults":9,"name":"Oslo"}"#,
            vec![("cityId", BoundValue::Text("c-2".into()))],
            &members,
        )
        .unwrap();
        assert_eq!(input.city_id, "c-2");
        assert_eq!(input.max_results, None);
        assert_eq!(input.name.as_deref(), Some("Oslo"));
        assert!(read_http::<Input>(br#"{"cityId":"injected"}"#, vec![], &members).is_err());
    }

    #[test]
    fn ordinary_read_still_accepts_body_members_not_in_the_supplied_bindings() {
        let input: Input = read(br#"{"cityId":"c-2","maxResults":9}"#, vec![]).unwrap();
        assert_eq!(input.city_id, "c-2");
        assert_eq!(input.max_results, Some(9));
    }

    #[derive(Debug, Deserialize, PartialEq)]
    struct Upload {
        caption: Option<String>,
        photo: crate::blob::Blob,
        thumbnail: Option<crate::blob::Blob>,
    }

    #[test]
    fn a_payload_member_takes_the_body_without_copying_it() {
        let body = Bytes::from_static(b"\xff\x00{\"a\":1}");
        let upload: Upload = read(
            b"",
            vec![
                ("caption", BoundValue::Text("sea".into())),
                ("photo", BoundValue::Bytes(body.clone())),
            ],
        )
        .unwrap();
        assert_eq!(upload.photo.as_bytes(), &body[..]);
        assert_eq!(
            upload.photo.as_ptr(),
            body.as_ptr(),
            "shares the body's buffer"
        );
        assert_eq!(upload.caption.as_deref(), Some("sea"));
        assert_eq!(upload.thumbnail, None);
    }

    #[test]
    fn a_missing_payload_is_a_missing_member() {
        let error = read::<Upload>(b"", vec![]).unwrap_err();
        assert!(
            error.to_string().contains("missing field `photo`"),
            "{error}"
        );
    }

    #[test]
    fn media_type_headers_are_base64_of_utf8_text() {
        assert_eq!(
            BoundValue::parse("aMOpbGxv".into(), Scalar::Base64).unwrap(),
            BoundValue::Text("h\u{e9}llo".into())
        );
        assert!(BoundValue::parse("%%%".into(), Scalar::Base64).is_err());
        assert!(BoundValue::parse("/w==".into(), Scalar::Base64).is_err());
        assert_eq!(
            BoundValue::parse(r#"YSxi, """#.into(), Scalar::List(&Scalar::Base64)).unwrap(),
            BoundValue::List(vec![
                BoundValue::Text("a,b".into()),
                BoundValue::Text("".into())
            ])
        );
    }

    #[test]
    fn converted_timestamps_read_as_their_document_format() {
        const EPOCH: Scalar = Scalar::Timestamp {
            text: TimestampFormat::HttpDate,
            json: TimestampFormat::EpochSeconds,
        };
        let epoch = EPOCH;
        assert_eq!(
            BoundValue::parse("Wed, 31 Dec 1969 23:59:59 GMT".into(), epoch).unwrap(),
            BoundValue::Number("-1".parse().unwrap())
        );
        let list = BoundValue::parse(
            "Wed, 31 Dec 1969 23:59:59 GMT, Thu, 01 Jan 1970 00:00:01 GMT".into(),
            Scalar::List(&EPOCH),
        )
        .unwrap();
        assert_eq!(
            list,
            BoundValue::List(vec![
                BoundValue::Number("-1".parse().unwrap()),
                BoundValue::Number("1".parse().unwrap())
            ])
        );
        let date_time = Scalar::Timestamp {
            text: TimestampFormat::EpochSeconds,
            json: TimestampFormat::DateTime,
        };
        assert_eq!(
            BoundValue::parse("-0.25".into(), date_time).unwrap(),
            BoundValue::Text("1969-12-31T23:59:59.750Z".into())
        );
        assert!(BoundValue::parse("soon".into(), epoch).is_err());
    }

    #[test]
    fn tracked_payload_errors_drop_syntax_paths_but_keep_data_paths_and_messages() {
        for (json, expected) in [
            (b"not JSON".as_slice(), "."),
            (br#"{"x":"\uD800"}"#, "."),
            (b"{\"x\":\"\xff\"}", "."),
            (b"{", "."),
            (br#"{"x":"#, "."),
            (br#"{"x":[1,}}"#, "."),
            (br#"{"x":1} trailing"#, "."),
            (br#"{"x":"wrong"}"#, "nested.x"),
        ] {
            let bound = vec![
                ("cityId", BoundValue::Text("c".into())),
                ("nested", BoundValue::RawJson(json)),
            ];
            let original = read_http::<Input>(b"", bound.clone(), &[]).unwrap_err();
            let tracked = read_http_tracked::<Input>(b"", bound, &[]).unwrap_err();
            assert_eq!(tracked.path().to_string(), expected, "{json:?}");
            assert_eq!(tracked.inner().to_string(), original.to_string());
        }
    }

    #[test]
    fn a_json_payload_reads_straight_into_the_member() {
        let input: Input = read(
            b"",
            vec![
                ("cityId", BoundValue::Text("c".into())),
                ("nested", BoundValue::RawJson(br#" {"x":2.5} "#)),
            ],
        )
        .unwrap();
        assert_eq!(input.nested, Some(Nested { x: 2.5 }));
        assert!(
            read::<Input>(
                b"",
                vec![
                    ("cityId", BoundValue::Text("c".into())),
                    ("nested", BoundValue::RawJson(br#"{"x":2.5} []"#)),
                ],
            )
            .is_err()
        );
    }

    #[test]
    fn a_null_json_payload_is_the_members_null_as_in_a_body() {
        #[derive(Debug, Deserialize)]
        struct Payloads {
            nested: Option<Nested>,
            choice: Option<Sky>,
            document: Option<serde_json::Value>,
            #[serde(
                default,
                with = "crate::codec::Adapter::<crate::codec::OptionalDocument>"
            )]
            kept: Option<serde_json::Value>,
            #[serde(default)]
            field: crate::field::Field<Nested>,
        }
        for null in [&b"null"[..], b" \t\r\nnull \n"] {
            let payloads: Payloads = read(
                b"",
                ["nested", "choice", "document", "kept", "field"]
                    .into_iter()
                    .map(|name| (name, BoundValue::RawJson(null)))
                    .collect(),
            )
            .unwrap();
            assert_eq!(payloads.nested, None);
            assert_eq!(payloads.choice, None);
            assert_eq!(payloads.document, None);
            // A codec that keeps a document's null still reads it.
            assert_eq!(payloads.kept, Some(serde_json::Value::Null));
            assert!(payloads.field.is_null());
        }
        // A structure is still read, and a value after the null is trailing data.
        let payloads: Payloads = read(
            b"",
            vec![
                ("nested", BoundValue::RawJson(br#"{"x":1}"#)),
                ("field", BoundValue::RawJson(br#"{"x":2}"#)),
            ],
        )
        .unwrap();
        assert_eq!(payloads.nested, Some(Nested { x: 1.0 }));
        assert_eq!(payloads.field.value(), Some(&Nested { x: 2.0 }));
        for json in [&b"null null"[..], b"nul", b"null{}"] {
            assert!(
                read::<Payloads>(b"", vec![("nested", BoundValue::RawJson(json))]).is_err(),
                "{json:?}"
            );
        }
    }

    // serde's derived struct visitor also takes a sequence (#292): a
    // structure, in a body member or as a whole payload, is only an object.
    #[test]
    fn a_structure_from_a_json_array_is_refused_in_a_body_and_a_payload() {
        #[derive(Debug, Deserialize)]
        struct Payloads {
            nested: Option<Nested>,
            #[serde(default)]
            field: crate::field::Field<Nested>,
            document: Option<serde_json::Value>,
        }
        for json in [&b"[]"[..], b"[1]", b" [ 1 ] "] {
            for name in ["nested", "field"] {
                assert!(
                    read::<Payloads>(b"", vec![(name, BoundValue::RawJson(json))]).is_err(),
                    "{name}: {json:?}"
                );
            }
            // A document payload is any JSON value, arrays included.
            let payloads: Payloads =
                read(b"", vec![("document", BoundValue::RawJson(json))]).unwrap();
            assert!(payloads.document.unwrap().is_array());
            // The same structure as a body member, with and without bound
            // members beside it.
            let body = [&br#"{"cityId":"c","nested":"#[..], json, b"}"].concat();
            assert!(read::<Input>(&body, vec![]).is_err(), "{json:?}");
            let body = [&br#"{"nested":"#[..], json, b"}"].concat();
            assert!(
                read::<Input>(&body, vec![("cityId", BoundValue::Text("c".into()))]).is_err(),
                "{json:?}"
            );
        }
        let payloads: Payloads = read(
            b"",
            vec![
                ("nested", BoundValue::RawJson(br#"{"x":1}"#)),
                ("field", BoundValue::RawJson(br#"{"x":2}"#)),
            ],
        )
        .unwrap();
        assert_eq!(payloads.nested, Some(Nested { x: 1.0 }));
        assert_eq!(payloads.field.value(), Some(&Nested { x: 2.0 }));
    }

    #[test]
    fn a_body_that_is_not_an_object_fails() {
        assert!(read::<Input>(b"[1]", vec![("cityId", BoundValue::Text("c".into()))]).is_err());
    }
}