structured-proxy 8.1.5

Universal gRPC→REST transcoding proxy — config-driven, works with any gRPC service
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! Request message construction for REST→gRPC transcoding.
//!
//! Builds the gRPC request message from three `google.api.http` sources, in
//! precedence order: path parameters (highest), the request body, then query
//! parameters (lowest, fill only). A JSON body is deserialized straight into
//! the message; path and query values arrive as strings and are converted to
//! each field's proto type as they are set.

mod presence;

use std::borrow::Cow;
use std::collections::HashMap;

use prost_reflect::{
    DynamicMessage, FieldDescriptor, Kind, MessageDescriptor, ReflectMessage, Value,
};
use serde::de::value::StrDeserializer;
use serde::Deserializer;
use serde_json::Value as JsonValue;

pub(crate) use presence::has_special_json;
use presence::{OneEntry, Presence, Recording};

/// The path parameters of a request: each dotted field path the path binds,
/// with its value.
pub(crate) trait PathFields {
    fn fields(&self) -> impl Iterator<Item = (&str, &str)>;

    fn is_empty(&self) -> bool {
        self.fields().next().is_none()
    }
}

impl PathFields for HashMap<String, String> {
    fn fields(&self) -> impl Iterator<Item = (&str, &str)> {
        self.iter()
            .map(|(key, value)| (key.as_str(), value.as_str()))
    }
}

impl PathFields for [(&str, Cow<'_, str>)] {
    fn fields(&self) -> impl Iterator<Item = (&str, &str)> {
        self.iter().map(|(key, value)| (*key, value.as_ref()))
    }
}

/// How the HTTP request body maps onto the gRPC request message.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BodyMapping {
    /// No body is read; fields come from path + query (typical for GET/DELETE).
    None,
    /// The entire body maps to the message root (`body: "*"`).
    Root,
    /// The body maps to a single named field of the message (`body: "field"`).
    Field(String),
}

impl BodyMapping {
    /// Parse the `body` value of a `google.api.http` rule.
    ///
    /// `""` (absent) → [`BodyMapping::None`], `"*"` → [`BodyMapping::Root`],
    /// any other string → [`BodyMapping::Field`].
    pub fn parse(raw: &str) -> Self {
        match raw {
            "" => BodyMapping::None,
            "*" => BodyMapping::Root,
            field => BodyMapping::Field(field.to_string()),
        }
    }
}

/// The HTTP request body the [`BodyMapping`] reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Body<'a> {
    /// No body is read. Under [`BodyMapping::Field`] the field still belongs
    /// to the body (a raw `google.api.HttpBody` filled afterwards), so query
    /// parameters leave it alone.
    Absent,
    /// A JSON body (ProtoJSON of the mapped message or field). Empty means
    /// `{}`.
    Json(&'a [u8]),
    /// An `application/x-www-form-urlencoded` body, bound field by field like
    /// query parameters.
    Form(&'a [u8]),
}

impl<'a> Body<'a> {
    /// The body as its media type (no parameters) says: a form for
    /// `application/x-www-form-urlencoded`, JSON otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use structured_proxy::transcode::request::Body;
    ///
    /// let form = Body::new(Some("application/x-www-form-urlencoded"), b"a=1");
    /// assert_eq!(form, Body::Form(b"a=1"));
    /// assert_eq!(Body::new(None, b"{}"), Body::Json(b"{}"));
    /// ```
    pub fn new(content_type: Option<&str>, bytes: &'a [u8]) -> Self {
        match content_type {
            Some(ct) if ct.starts_with("application/x-www-form-urlencoded") => Body::Form(bytes),
            _ => Body::Json(bytes),
        }
    }
}

/// Build the request message from the body mapping, path params, and query.
///
/// Path-bound fields win over the body, and the body wins over query parameters
/// (query only fills fields the body did not set, even to their default).
/// Unknown query, form and path keys are dropped rather than rejected,
/// matching common transcoder behavior; an unknown key in a JSON body is an
/// error, as ProtoJSON has it.
///
/// # Errors
/// A body that is not the ProtoJSON of the mapped message or field, a form
/// body mapped onto a field that is not a message, or a path, query or form
/// value that is not a valid value of its field. The message is meant for the
/// client, as the text of an `INVALID_ARGUMENT` answer.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use prost_reflect::{MessageDescriptor, Value};
/// use structured_proxy::transcode::request::{build_request_message, Body, BodyMapping};
///
/// // message Page { int32 size = 1; string cursor = 2; }
/// # fn page() -> MessageDescriptor {
/// #     use prost_reflect::prost::Message;
/// #     use prost_reflect::prost_types::{
/// #         field_descriptor_proto::{Label, Type},
/// #         DescriptorProto, FieldDescriptorProto, FileDescriptorProto, FileDescriptorSet,
/// #     };
/// #     let field = |name: &str, number, ty: Type| FieldDescriptorProto {
/// #         name: Some(name.into()),
/// #         number: Some(number),
/// #         label: Some(Label::Optional as i32),
/// #         r#type: Some(ty as i32),
/// #         ..Default::default()
/// #     };
/// #     let file = FileDescriptorProto {
/// #         name: Some("page.proto".into()),
/// #         package: Some("example".into()),
/// #         message_type: vec![DescriptorProto {
/// #             name: Some("Page".into()),
/// #             field: vec![field("size", 1, Type::Int32), field("cursor", 2, Type::String)],
/// #             ..Default::default()
/// #         }],
/// #         syntax: Some("proto3".into()),
/// #         ..Default::default()
/// #     };
/// #     let set = FileDescriptorSet { file: vec![file] };
/// #     prost_reflect::DescriptorPool::decode(set.encode_to_vec().as_slice())
/// #         .unwrap()
/// #         .get_message_by_name("example.Page")
/// #         .unwrap()
/// # }
/// let message = build_request_message(
///     &page(),
///     &BodyMapping::Root,
///     Body::Json(br#"{"size": 0}"#),
///     &HashMap::new(),
///     Some("size=50&cursor=abc"),
/// )
/// .unwrap();
/// // The body set `size`, to its default: the query cannot replace it.
/// assert_eq!(message.get_field_by_name("size").unwrap().as_i32(), Some(0));
/// // It left `cursor` out: the query fills it.
/// assert_eq!(
///     *message.get_field_by_name("cursor").unwrap(),
///     Value::String("abc".into())
/// );
/// ```
pub fn build_request_message(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    body: Body<'_>,
    path_params: &HashMap<String, String>,
    raw_query: Option<&str>,
) -> Result<DynamicMessage, String> {
    build_message(input, mapping, body, path_params, raw_query)
}

/// [`build_request_message`] for any form of the path parameters.
pub(crate) fn build_message<P: PathFields + ?Sized>(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    body: Body<'_>,
    path_params: &P,
    raw_query: Option<&str>,
) -> Result<DynamicMessage, String> {
    // Parsed without allocating wherever nothing needs unescaping.
    let query: Vec<(Cow<'_, str>, Cow<'_, str>)> = match raw_query {
        Some(q) => url::form_urlencoded::parse(q.as_bytes()).collect(),
        None => Vec::new(),
    };
    build(input, mapping, body, path_params, &query)
}

/// Which source a string value comes from, and so whether it overwrites.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Binding {
    /// Path parameters and form fields set their field.
    Set,
    /// Query parameters fill only what nothing else set.
    Fill,
}

fn build<P: PathFields + ?Sized>(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    body: Body<'_>,
    path_params: &P,
    query: &[(Cow<'_, str>, Cow<'_, str>)],
) -> Result<DynamicMessage, String> {
    // What the body and the path set matters only when a query can fill.
    let body_len = match body {
        Body::Json(bytes) | Body::Form(bytes) => bytes.len(),
        Body::Absent => 0,
    };
    let mut presence = (!query.is_empty()).then(|| Presence::for_body(body_len));
    // The fields of the path being bound, reused across keys.
    let mut path = Vec::new();

    // Whether a field inside a well-known type was set from a string.
    let mut inside = false;

    let mut message = match (mapping, body) {
        (BodyMapping::None, _) => DynamicMessage::new(input.clone()),
        (BodyMapping::Field(name), Body::Absent) => {
            if let (Some(presence), Some(field)) = (&mut presence, input.get_field_by_name(name)) {
                presence.record_path(&[field], false);
            }
            DynamicMessage::new(input.clone())
        }
        (BodyMapping::Root, Body::Absent) => DynamicMessage::new(input.clone()),
        // An empty body is `{}`, whatever its media type.
        (_, Body::Json(bytes) | Body::Form(bytes)) if bytes.is_empty() => {
            json_body(input, mapping, b"{}", path_params, presence.as_mut())?
        }
        (_, Body::Json(bytes)) => json_body(input, mapping, bytes, path_params, presence.as_mut())?,
        (_, Body::Form(bytes)) => {
            let pairs: Vec<(Cow<'_, str>, Cow<'_, str>)> =
                url::form_urlencoded::parse(bytes).collect();
            let form = Form {
                pairs: &pairs,
                path_params,
            };
            let (message, form_inside) =
                form_body(input, mapping, form, presence.as_mut(), &mut path)?;
            inside = form_inside;
            message
        }
    };

    let root_inside = has_special_json(input);
    // Path params win over everything (the router already matched them).
    for (key, raw) in path_params.fields() {
        let target = Target {
            root: input,
            inside: root_inside,
            prefix: None,
            key,
            values: &[raw],
        };
        inside |= bind(
            &mut message,
            target,
            Binding::Set,
            presence.as_mut(),
            &mut path,
        )?;
    }

    if let Some(presence) = &mut presence {
        let start = Start {
            root: input,
            inside: root_inside,
            prefix: None,
        };
        inside |= bind_pairs(
            &mut message,
            query,
            start,
            Binding::Fill,
            Some(presence),
            None::<&P>,
            &mut path,
        )?;
    }
    if inside {
        check_well_known(&message)?;
    }
    Ok(message)
}

/// Refuse a well-known type set field by field whose value its JSON form
/// could not hold: a Timestamp's `nanos` past 999999999, a Duration whose
/// `seconds` and `nanos` differ in sign, an `Any` of an unknown type.
/// Checked once all keys are bound, as they arrive in any order.
fn check_well_known(message: &DynamicMessage) -> Result<(), String> {
    let invalid = |e: &dyn std::fmt::Display| format!("invalid value for a well-known type: {e}");
    check_time_ranges(message).map_err(|e| invalid(&e))?;
    // Writing the ProtoJSON checks the rest (an `Any` must name a known type
    // and decode as it, a `FieldMask` path must round-trip through camelCase,
    // a `Value` number must be finite); the text is not kept.
    serde_json::to_writer(std::io::sink(), message).map_err(|e| invalid(&e))
}

/// Check every `Timestamp` and `Duration` in `message` against the ranges
/// their definitions set. prost-reflect's writer checks only part of them and
/// carries excess nanos into seconds, which would change the value.
fn check_time_ranges(message: &DynamicMessage) -> Result<(), &'static str> {
    let field = |name| message.get_field_by_name(name);
    match message.descriptor().full_name() {
        // google/protobuf/timestamp.proto: seconds from 0001-01-01T00:00:00Z
        // to 9999-12-31T23:59:59Z, nanos in [0, 999999999].
        "google.protobuf.Timestamp" => {
            let seconds = field("seconds").and_then(|v| v.as_i64()).unwrap_or(0);
            let nanos = field("nanos").and_then(|v| v.as_i32()).unwrap_or(0);
            if !(-62_135_596_800..=253_402_300_799).contains(&seconds)
                || !(0..=999_999_999).contains(&nanos)
            {
                return Err("timestamp out of range");
            }
        }
        // google/protobuf/duration.proto: seconds within +-315576000000,
        // nanos within +-999999999, and nanos of the same sign as a non-zero
        // seconds.
        "google.protobuf.Duration" => {
            let seconds = field("seconds").and_then(|v| v.as_i64()).unwrap_or(0);
            let nanos = field("nanos").and_then(|v| v.as_i32()).unwrap_or(0);
            if seconds.unsigned_abs() > 315_576_000_000
                || nanos.unsigned_abs() > 999_999_999
                || (seconds > 0 && nanos < 0)
                || (seconds < 0 && nanos > 0)
            {
                return Err("duration out of range");
            }
        }
        _ => {}
    }
    for (_, value) in message.fields() {
        check_value_time_ranges(value)?;
    }
    Ok(())
}

fn check_value_time_ranges(value: &Value) -> Result<(), &'static str> {
    match value {
        Value::Message(inner) => check_time_ranges(inner),
        Value::List(items) => items.iter().try_for_each(check_value_time_ranges),
        Value::Map(entries) => entries.values().try_for_each(check_value_time_ranges),
        _ => Ok(()),
    }
}

/// Where string values go: the field at the dotted path `key`, below the
/// message field `prefix` of `root` when there is one, below `root` otherwise.
#[derive(Clone, Copy)]
struct Target<'a> {
    root: &'a MessageDescriptor,
    /// Whether the message the key starts in is a well-known type.
    inside: bool,
    prefix: Option<&'a FieldDescriptor>,
    key: &'a str,
    /// Every value of the key, in request order.
    values: &'a [&'a str],
}

/// Deserialize a JSON body in one pass.
///
/// The path wins over the body, so a body value for a field the path binds
/// never decides the request, even when it is not a valid value of that field.
/// Such a body fails the one pass; it is then read again without those keys.
/// Only a failing body pays for the second read.
fn json_body<P: PathFields + ?Sized>(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    bytes: &[u8],
    path_params: &P,
    mut presence: Option<&mut Presence>,
) -> Result<DynamicMessage, String> {
    // A `null` body sets nothing, like `{}`.
    if matches!(mapping, BodyMapping::Root) && trim_json_whitespace(bytes) == b"null" {
        return Ok(DynamicMessage::new(input.clone()));
    }
    let mut de = serde_json::Deserializer::from_slice(bytes);
    let first = deserialize(input, mapping, &mut de, presence.as_deref_mut())
        .and_then(|message| de.end().map(|()| message));
    let error = match first {
        Ok(message) => return Ok(message),
        Err(error) => error,
    };
    let fail = |e: serde_json::Error| format!("failed to decode request body: {e}");
    if path_params.is_empty() {
        return Err(fail(error));
    }
    // Not JSON at all: the path cannot change that.
    let Ok(mut value) = serde_json::from_slice::<JsonValue>(bytes) else {
        return Err(fail(error));
    };
    strip_path_fields(&mut value, input, mapping, path_params);
    if let Some(presence) = presence.as_deref_mut() {
        presence.clear();
    }
    deserialize(input, mapping, value, presence).map_err(fail)
}

/// Remove from `body` every key the path binds, under its JSON or proto name:
/// the path sets those fields whatever the body holds.
fn strip_path_fields<P: PathFields + ?Sized>(
    body: &mut JsonValue,
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    path_params: &P,
) {
    for (key, _) in path_params.fields() {
        let mut segments = key.split('.');
        let desc = match mapping {
            BodyMapping::Root => input.clone(),
            // Under `body: "field"` the body is that field's value, so only
            // the path keys below the field reach into it.
            BodyMapping::Field(name) => {
                if segments.next() != Some(name.as_str()) {
                    continue;
                }
                match input.get_field_by_name(name).map(|f| f.kind()) {
                    Some(Kind::Message(inner)) => inner,
                    _ => continue,
                }
            }
            BodyMapping::None => return,
        };
        remove_path(body, desc, segments);
    }
}

/// Remove the field at `segments` below `desc` from the JSON object `value`.
fn remove_path<'k>(
    mut value: &mut JsonValue,
    mut desc: MessageDescriptor,
    segments: impl Iterator<Item = &'k str>,
) {
    let mut segments = segments.peekable();
    while let Some(segment) = segments.next() {
        let Some(field) = field_named(&desc, segment, &mut false) else {
            return;
        };
        let Some(object) = value.as_object_mut() else {
            return;
        };
        if segments.peek().is_none() {
            object.remove(field.json_name());
            object.remove(field.name());
            return;
        }
        let Kind::Message(inner) = field.kind() else {
            return;
        };
        let key = if object.contains_key(field.json_name()) {
            field.json_name()
        } else {
            field.name()
        };
        let Some(next) = object.get_mut(key) else {
            return;
        };
        value = next;
        desc = inner;
    }
}

fn trim_json_whitespace(bytes: &[u8]) -> &[u8] {
    let ws = |b: &u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r');
    let start = bytes.iter().position(|b| !ws(b)).unwrap_or(bytes.len());
    let end = bytes.iter().rposition(|b| !ws(b)).map_or(start, |i| i + 1);
    &bytes[start..end]
}

/// Deserialize `body` as the mapping says: the whole input message, or the
/// value of one of its fields.
fn deserialize<'de, D: Deserializer<'de>>(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    body: D,
    presence: Option<&mut Presence>,
) -> Result<DynamicMessage, D::Error> {
    match mapping {
        BodyMapping::Field(name) => {
            // Keyed by the JSON name, which prost-reflect looks up first, so
            // no other field's JSON name can shadow it.
            let field = input.get_field_by_name(name);
            let key = field.as_ref().map_or(name.as_str(), |f| f.json_name());
            deserialize_input(input, OneEntry { key, value: body }, presence)
        }
        _ => deserialize_input(input, body, presence),
    }
}

fn deserialize_input<'de, D: Deserializer<'de>>(
    input: &MessageDescriptor,
    de: D,
    presence: Option<&mut Presence>,
) -> Result<DynamicMessage, D::Error> {
    let Some(presence) = presence else {
        return DynamicMessage::deserialize(input.clone(), de);
    };
    if has_special_json(input) {
        presence.record_whole();
        return DynamicMessage::deserialize(input.clone(), de);
    }
    DynamicMessage::deserialize(input.clone(), Recording::root(de, presence))
}

/// Bind a form body field by field, into the input message or the message
/// field the mapping names.
fn form_body<P: PathFields + ?Sized>(
    input: &MessageDescriptor,
    mapping: &BodyMapping,
    form: Form<'_, '_, P>,
    mut presence: Option<&mut Presence>,
    path: &mut Vec<FieldDescriptor>,
) -> Result<(DynamicMessage, bool), String> {
    let Form { pairs, path_params } = form;
    let mut message = DynamicMessage::new(input.clone());
    let (prefix, start_inside) = match mapping {
        BodyMapping::Field(name) => {
            let (field, inner) = input
                .get_field_by_name(name)
                .filter(|f| !f.is_list() && !f.is_map())
                .and_then(|f| match f.kind() {
                    Kind::Message(inner) => Some((f, inner)),
                    _ => None,
                })
                .ok_or_else(|| format!("a form body cannot fill field `{name}`"))?;
            // The field is the body's even when the form is empty of it.
            message.get_field_mut(&field);
            if let Some(presence) = presence.as_deref_mut() {
                presence.record_path(std::slice::from_ref(&field), true);
            }
            (Some(field), has_special_json(&inner))
        }
        _ => (None, has_special_json(input)),
    };
    let start = Start {
        root: input,
        inside: start_inside,
        prefix: prefix.as_ref(),
    };
    let inside = bind_pairs(
        &mut message,
        pairs,
        start,
        Binding::Set,
        presence,
        Some(path_params),
        path,
    )?;
    Ok((message, inside))
}

/// A form body and the path parameters that override it.
struct Form<'p, 'q, P: ?Sized> {
    pairs: &'p [(Cow<'q, str>, Cow<'q, str>)],
    path_params: &'p P,
}

/// Whether the dotted path key `bound` names the field at the end of `path`
/// or one above it. Path keys start at the input message, as `path` does.
fn covers(bound: &str, path: &[FieldDescriptor]) -> bool {
    let mut fields = path.iter();
    bound.split('.').all(|segment| {
        fields
            .next()
            .is_some_and(|f| segment == f.name() || segment == f.json_name())
    })
}

/// Where the keys of a query or form start: `root`, or its message field
/// `prefix`; `inside` when that message is a well-known type.
#[derive(Clone, Copy)]
struct Start<'a> {
    root: &'a MessageDescriptor,
    inside: bool,
    prefix: Option<&'a FieldDescriptor>,
}

/// Bind every key of `pairs` to its field, with all the values of that field
/// in request order, and tell whether a field inside a well-known type was
/// set. A key the path binds (`path_params`, for a form) is left to the path.
///
/// Keys are grouped by the field they name, not by spelling: `tag_ids` and
/// `tagIds` are one field, and binding them apart would let one replace the
/// other's values.
fn bind_pairs<P: PathFields + ?Sized>(
    message: &mut DynamicMessage,
    pairs: &[(Cow<'_, str>, Cow<'_, str>)],
    start: Start<'_>,
    binding: Binding,
    mut presence: Option<&mut Presence>,
    path_params: Option<&P>,
    path: &mut Vec<FieldDescriptor>,
) -> Result<bool, String> {
    // A stable sort keeps the values of each spelling in request order.
    let mut order: Vec<usize> = (0..pairs.len()).collect();
    order.sort_by(|&a, &b| pairs[a].0.cmp(&pairs[b].0));
    let mut values = Vec::new();
    let mut inside = false;
    // Spellings that used a JSON name, by the proto-name key they stand for.
    // Only a request that mixes the two spellings of a field pays for this.
    let mut aliased: Vec<(String, &[usize])> = Vec::new();
    // Spellings whose own values failed to bind, with the error.
    let mut failed: Vec<(&str, String)> = Vec::new();
    for run in order.chunk_by(|&a, &b| pairs[a].0 == pairs[b].0) {
        values.clear();
        values.extend(run.iter().map(|&i| pairs[i].1.as_ref()));
        let target = Target {
            root: start.root,
            inside: start.inside,
            prefix: start.prefix,
            key: &pairs[run[0]].0,
            values: &values,
        };
        let Some(resolved) = resolve(target, path) else {
            continue;
        };
        if resolved.aliased {
            let own = &path[usize::from(start.prefix.is_some())..];
            let canonical = own.iter().map(|f| f.name()).collect::<Vec<_>>().join(".");
            aliased.push((canonical, run));
            continue;
        }
        let bound = bind_resolved(
            message,
            path,
            &values,
            binding,
            presence.as_deref_mut(),
            path_params,
        );
        match bound {
            Ok(set) => inside |= set && resolved.inside,
            // A failed assignment leaves the message as it was (parsing and
            // the oneof check come before any write). The error is held: when
            // the field also came under its JSON name, the values of both
            // spellings decide the outcome below, not this spelling alone.
            Err(e) => failed.push((pairs[run[0]].0.as_ref(), e)),
        }
    }
    aliased.sort_by(|a, b| a.0.cmp(&b.0));
    // Failures come in key order; the first one no merge below redoes wins.
    let covered = |key: &str| {
        aliased
            .binary_search_by(|(c, _)| c.as_str().cmp(key))
            .is_ok()
    };
    if let Some((_, e)) = failed.into_iter().find(|(key, _)| !covered(key)) {
        return Err(e);
    }
    if aliased.is_empty() {
        return Ok(inside);
    }
    let mut indices = Vec::new();
    for group in aliased.chunk_by(|a, b| a.0 == b.0) {
        let canonical = group[0].0.as_str();
        indices.clear();
        for (_, run) in group {
            indices.extend_from_slice(run);
        }
        // The proto-name spelling, bound above with its own values only.
        let from = order.partition_point(|&i| pairs[i].0.as_ref() < canonical);
        let to = order.partition_point(|&i| pairs[i].0.as_ref() <= canonical);
        indices.extend_from_slice(&order[from..to]);
        indices.sort_unstable();
        values.clear();
        values.extend(indices.iter().map(|&i| pairs[i].1.as_ref()));
        let target = Target {
            root: start.root,
            inside: start.inside,
            prefix: start.prefix,
            key: canonical,
            values: &values,
        };
        let Some(resolved) = resolve(target, path) else {
            continue;
        };
        inside |= bind_resolved(
            message,
            path,
            &values,
            binding,
            presence.as_deref_mut(),
            path_params,
        )? && resolved.inside;
    }
    Ok(inside)
}

/// Assign `values` to the resolved `path` unless a path parameter binds it.
/// True when it was assigned.
fn bind_resolved<P: PathFields + ?Sized>(
    message: &mut DynamicMessage,
    path: &[FieldDescriptor],
    values: &[&str],
    binding: Binding,
    presence: Option<&mut Presence>,
    path_params: Option<&P>,
) -> Result<bool, String> {
    // The path sets these fields whatever the form holds, so their form
    // values are never decoded, as a JSON body's are not.
    if path_params.is_some_and(|bound| bound.fields().any(|(key, _)| covers(key, path))) {
        return Ok(false);
    }
    assign(message, path, values, binding, presence)?;
    Ok(true)
}

/// Set the field `target` names to its values (see [`resolve`] and
/// [`assign`]). `path` is a buffer for the fields on the way. True when the
/// field lies inside a well-known type.
fn bind(
    message: &mut DynamicMessage,
    target: Target<'_>,
    binding: Binding,
    presence: Option<&mut Presence>,
    path: &mut Vec<FieldDescriptor>,
) -> Result<bool, String> {
    let Some(resolved) = resolve(target, path) else {
        return Ok(false);
    };
    assign(message, path, target.values, binding, presence)?;
    Ok(resolved.inside)
}

/// What [`resolve`] found besides the fields on the way.
#[derive(Clone, Copy)]
struct Resolved {
    /// The field lies inside a well-known type.
    inside: bool,
    /// A segment named its field by a JSON name that is not its proto name.
    aliased: bool,
}

/// Resolve the dotted key of `target` into the fields on the way, in `path`,
/// and tell whether the field lies inside a well-known type.
///
/// Each segment names a field by its proto name or its JSON name, as
/// ProtoJSON reads a key. `None` when the key is dropped: it names no field,
/// or passes through a field that is not a singular message. A field inside
/// a well-known type (`at.nanos` of a Timestamp) is bound like any other, and
/// the value it leaves is checked once the request is built (see
/// [`check_well_known`]).
fn resolve(target: Target<'_>, path: &mut Vec<FieldDescriptor>) -> Option<Resolved> {
    path.clear();
    let mut inside = target.inside;
    let mut aliased = false;
    let mut owned;
    let mut desc = match target.prefix {
        Some(field) => {
            let Kind::Message(inner) = field.kind() else {
                return None;
            };
            path.push(field.clone());
            owned = inner;
            &owned
        }
        None => target.root,
    };
    let mut segments = target.key.split('.');
    let mut leaf = segments.next().unwrap_or_default();
    for next in segments {
        let field = field_named(desc, leaf, &mut aliased)?;
        let Kind::Message(inner) = field.kind() else {
            return None;
        };
        if field.is_list() || field.is_map() {
            return None;
        }
        inside |= has_special_json(&inner);
        path.push(field);
        owned = inner;
        desc = &owned;
        leaf = next;
    }
    path.push(field_named(desc, leaf, &mut aliased)?);
    Some(Resolved { inside, aliased })
}

/// The field of `desc` named `name`, by its proto name or else its JSON name;
/// `aliased` is set when only the JSON name matched.
fn field_named(
    desc: &MessageDescriptor,
    name: &str,
    aliased: &mut bool,
) -> Option<FieldDescriptor> {
    if let Some(field) = desc.get_field_by_name(name) {
        return Some(field);
    }
    let field = desc.get_field_by_json_name(name)?;
    *aliased = true;
    Some(field)
}

/// Set the field at the end of `path` to `values`: all of them for a repeated
/// field, the last one otherwise. A [`Binding::Fill`] leaves a field the body
/// or the path set, or one below a field they set to a non-object, alone.
fn assign(
    message: &mut DynamicMessage,
    path: &[FieldDescriptor],
    values: &[&str],
    binding: Binding,
    mut presence: Option<&mut Presence>,
) -> Result<(), String> {
    if binding == Binding::Fill && presence.as_deref_mut().is_some_and(|p| p.blocks(path)) {
        return Ok(());
    }

    let (field, parents) = path
        .split_last()
        .expect("a resolved path ends in its field");
    let value = field_value(field, values)?;
    let mut holder = message;
    for parent in parents {
        check_oneof(holder, parent)?;
        holder = match holder.get_field_mut(parent) {
            Value::Message(inner) => inner,
            _ => unreachable!("a singular message field holds a message"),
        };
    }
    check_oneof(holder, field)?;
    holder.set_field(field, value);
    if binding == Binding::Set {
        if let Some(presence) = presence {
            presence.record_path(path, false);
        }
    }
    Ok(())
}

/// Refuse to set `field` over another member of its oneof, as ProtoJSON
/// refuses a body naming two of them.
fn check_oneof(message: &DynamicMessage, field: &FieldDescriptor) -> Result<(), String> {
    let Some(oneof) = field.containing_oneof() else {
        return Ok(());
    };
    if oneof
        .fields()
        .any(|other| other.number() != field.number() && message.has_field(&other))
    {
        return Err(format!(
            "multiple fields provided for oneof '{}'",
            oneof.name()
        ));
    }
    Ok(())
}

/// The value of `field` from its string forms.
fn field_value(field: &FieldDescriptor, raw: &[&str]) -> Result<Value, String> {
    let invalid = |e: String| format!("invalid value for field `{}`: {e}", field.name());
    if field.is_map() {
        return Err(invalid("a map field cannot be set from a string".into()));
    }
    let kind = field.kind();
    if field.is_list() {
        return raw
            .iter()
            .map(|raw| scalar(&kind, raw))
            .collect::<Result<Vec<_>, _>>()
            .map(Value::List)
            .map_err(invalid);
    }
    let raw = raw.last().expect("a bound key has a value");
    scalar(&kind, raw).map_err(invalid)
}

/// A string as a value of `kind`, read as the ProtoJSON of that value would
/// be: numbers in decimal (floats also `NaN`, `Infinity`, `-Infinity`), bools
/// as `true`/`false`, enums by name, bytes as base64, and a message type from
/// its JSON string form (a `Timestamp`, `Duration`, `FieldMask`, wrapper).
fn scalar(kind: &Kind, raw: &str) -> Result<Value, String> {
    Ok(match kind {
        Kind::Double => Value::F64(parse_f64(raw)?),
        Kind::Float => Value::F32(parse_f32(raw)?),
        Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => Value::I32(parse(raw)?),
        Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => Value::I64(parse(raw)?),
        Kind::Uint32 | Kind::Fixed32 => Value::U32(parse(raw)?),
        Kind::Uint64 | Kind::Fixed64 => Value::U64(parse(raw)?),
        Kind::Bool => Value::Bool(parse(raw)?),
        Kind::String => Value::String(raw.to_owned()),
        Kind::Bytes => Value::Bytes(decode_base64(raw)?.into()),
        Kind::Enum(desc) => Value::EnumNumber(
            desc.get_value_by_name(raw)
                .ok_or_else(|| format!("unrecognized enum value '{raw}'"))?
                .number(),
        ),
        Kind::Message(desc) => Value::Message(
            DynamicMessage::deserialize(
                desc.clone(),
                StrDeserializer::<serde::de::value::Error>::new(raw),
            )
            .map_err(|e| e.to_string())?,
        ),
    })
}

fn parse<T: std::str::FromStr>(raw: &str) -> Result<T, String>
where
    T::Err: std::fmt::Display,
{
    raw.parse().map_err(|e: T::Err| e.to_string())
}

/// Special float names of ProtoJSON.
fn special_float(raw: &str) -> Option<f64> {
    match raw {
        "Infinity" => Some(f64::INFINITY),
        "-Infinity" => Some(f64::NEG_INFINITY),
        "NaN" => Some(f64::NAN),
        _ => None,
    }
}

/// A ProtoJSON double: one of the special names, or a decimal with a finite
/// value. Rust's parser also reads `inf`, `nan` and `infinity` in any case,
/// and an overflowing decimal as infinity; ProtoJSON has none of those
/// (protobuf JSON mapping, "float, double").
fn parse_f64(raw: &str) -> Result<f64, String> {
    if let Some(special) = special_float(raw) {
        return Ok(special);
    }
    match raw.parse::<f64>() {
        Ok(value) if value.is_finite() => Ok(value),
        Ok(_) => Err("value out of range, or not a decimal number".to_string()),
        Err(e) => Err(e.to_string()),
    }
}

/// A ProtoJSON float: a special name, or a finite decimal within the `f32`
/// range.
fn parse_f32(raw: &str) -> Result<f32, String> {
    let wide = parse_f64(raw)?;
    if wide.is_finite() && (wide < f64::from(f32::MIN) || wide > f64::from(f32::MAX)) {
        return Err("float value out of range".to_string());
    }
    // A special value casts to itself; a finite one is in range, so the cast
    // rounds instead of saturating.
    Ok(wide as f32)
}

/// Base64 as ProtoJSON reads it: the standard or the URL-safe alphabet,
/// padded or not.
fn decode_base64(raw: &str) -> Result<Vec<u8>, String> {
    use base64::alphabet;
    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
    use base64::{DecodeError, Engine};

    const CONFIG: GeneralPurposeConfig = GeneralPurposeConfig::new()
        .with_decode_allow_trailing_bits(true)
        .with_decode_padding_mode(DecodePaddingMode::Indifferent);
    const STANDARD: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, CONFIG);
    const URL_SAFE: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, CONFIG);

    let mut buf = Vec::new();
    match STANDARD.decode_vec(raw, &mut buf) {
        Ok(()) => Ok(buf),
        Err(DecodeError::InvalidByte(_, b'-' | b'_')) => {
            buf.clear();
            URL_SAFE
                .decode_vec(raw, &mut buf)
                .map(|()| buf)
                .map_err(|e| format!("invalid base64: {e}"))
        }
        Err(e) => Err(format!("invalid base64: {e}")),
    }
}

#[cfg(test)]
mod tests;