grpc-webnext 0.1.0

Full bidirectional gRPC for the browser — real HTTP/2 over WebSockets (h2ts), plus JSON, REST, and a single-stream Frame protocol — served in front of any gRPC service, in-process (wrap a tonic Router) or as a standalone proxy.
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
//! `google.api.http` transcoding: map REST-style `(HTTP method, path)` requests
//! onto gRPC methods, binding path segments, query params, and the request body
//! into the request message.
//!
//! This is a practical subset of the HttpRule spec — enough for the common
//! `get: "/v1/x/{id}"` / `post: "/v1/x" body: "*"` bindings:
//!   * verbs `get/put/post/delete/patch` and `custom{kind}`,
//!   * `additional_bindings` (one level),
//!   * path templates: literal segments, `{field}` / `{field=*}` single-segment
//!     captures, and `{field=**}` (or a trailing segment) capturing the rest,
//!     with dotted field paths (`{a.b}`) binding nested fields,
//!   * `body: "*"` (whole message), `body: "<field>"` (a sub-message field), or none,
//!   * query params bound to (possibly nested) scalar/repeated fields.
//!
//! Not yet handled (see BACKLOG): `response_body`, regex path patterns beyond
//! `*`/`**`, and non-scalar query binding.

use prost_reflect::prost::Message;
use prost_reflect::{DescriptorPool, DynamicMessage, Kind, MessageDescriptor, ReflectMessage, Value};

use crate::transcode::TranscodeError;

/// The extension full name that carries an HttpRule on a method.
const HTTP_EXT: &str = "google.api.http";

/// A parsed path-template segment.
#[derive(Debug, Clone)]
enum Segment {
    /// A fixed path component that must match exactly.
    Literal(String),
    /// `{field}` / `{field=*}` — captures exactly one path component into `field`
    /// (a dotted path into the request message).
    Single(Vec<String>),
    /// `{field=**}` — captures the remaining components (slashes preserved).
    Rest(Vec<String>),
}

/// How the request body maps onto the message.
#[derive(Debug, Clone)]
enum BodyRule {
    /// `body: "*"` — the whole JSON body is the request message.
    Wildcard,
    /// `body: "<field>"` — the JSON body is a single (message) field.
    Field(String),
    /// No body.
    None,
}

/// One compiled HTTP binding: `(method, template)` -> a gRPC method + how to build
/// its request message.
#[derive(Debug, Clone)]
struct Binding {
    http_method: String, // upper-case, e.g. "GET"
    segments: Vec<Segment>,
    body: BodyRule,
    grpc_method: String, // "/pkg.Service/Method"
    input: MessageDescriptor,
}

/// A captured path variable: the dotted field path it binds to, and its string value —
/// e.g. `(["user", "id"], "123")` for a `{user.id}` template segment.
type PathVar = (Vec<String>, String);

/// The transcoded call: which gRPC method to invoke and the encoded request.
pub struct HttpCall {
    pub grpc_method: String,
    pub message: Vec<u8>,
}

/// A WebSocket route resolved from an annotation URL: the target gRPC method plus
/// the path/query bindings, used to build each streamed request message.
pub struct WsBinding {
    binding: Binding,
    vars: Vec<PathVar>,
    query: Option<String>,
}

impl WsBinding {
    /// The gRPC method this annotation route maps to.
    pub fn grpc_method(&self) -> &str {
        &self.binding.grpc_method
    }

    /// Whether the route takes a request body. `false` for GET-style server-streams,
    /// where the request comes entirely from the URL (path + query).
    pub fn has_body(&self) -> bool {
        !matches!(self.binding.body, BodyRule::None)
    }

    /// Build a request message from a body payload, overlaying the URL path/query.
    pub fn build_message(&self, body: &[u8]) -> Result<Vec<u8>, TranscodeError> {
        build_message(&self.binding, &self.vars, self.query.as_deref(), body)
    }
}

/// A table of HTTP bindings compiled from a descriptor pool.
#[derive(Clone, Default)]
pub struct HttpRouter {
    bindings: Vec<Binding>,
}

impl HttpRouter {
    /// Compile all `google.api.http` bindings in the pool. Empty if the pool has
    /// no annotations (or the extension isn't present).
    pub fn from_pool(pool: &DescriptorPool) -> Self {
        let mut bindings = Vec::new();
        let Some(ext) = pool.get_extension_by_name(HTTP_EXT) else {
            return Self { bindings };
        };
        for service in pool.services() {
            for method in service.methods() {
                let opts = method.options();
                if !opts.has_extension(&ext) {
                    continue;
                }
                let grpc_method = format!("/{}/{}", service.full_name(), method.name());
                let input = method.input();
                let rule = opts.get_extension(&ext);
                if let Some(rule) = rule.as_message() {
                    collect_rule(&mut bindings, rule, &grpc_method, &input);
                }
            }
        }
        Self { bindings }
    }

    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty()
    }

    /// Match a WebSocket upgrade path against the annotation bindings. A WS upgrade
    /// is always an HTTP GET, so this matches on the path only (verb-agnostic).
    pub fn match_ws(&self, path: &str, query: Option<&str>) -> Option<WsBinding> {
        for b in &self.bindings {
            if let Some(vars) = match_segments(&b.segments, path) {
                return Some(WsBinding {
                    binding: b.clone(),
                    vars,
                    query: query.map(str::to_string),
                });
            }
        }
        None
    }

    /// Whether a gRPC method (`/pkg.Service/Method`) has any HTTP annotation.
    pub fn is_annotated(&self, grpc_method: &str) -> bool {
        self.bindings.iter().any(|b| b.grpc_method == grpc_method)
    }

    /// Find a binding matching `(method, path)` and return it plus the captured
    /// path variables (dotted field path -> value).
    fn match_request(&self, method: &str, path: &str) -> Option<(&Binding, Vec<PathVar>)> {
        let want = method.to_ascii_uppercase();
        for b in &self.bindings {
            if b.http_method != want {
                continue;
            }
            if let Some(vars) = match_segments(&b.segments, path) {
                return Some((b, vars));
            }
        }
        None
    }

    /// Transcode a REST request into a gRPC call, or `None` if no binding matches.
    pub fn transcode(
        &self,
        method: &str,
        path: &str,
        query: Option<&str>,
        body: &[u8],
    ) -> Result<Option<HttpCall>, TranscodeError> {
        let Some((binding, vars)) = self.match_request(method, path) else {
            return Ok(None);
        };
        let message = build_message(binding, &vars, query, body)?;
        Ok(Some(HttpCall { grpc_method: binding.grpc_method.clone(), message }))
    }
}

/// Push the top rule and any `additional_bindings` (one level) as bindings.
fn collect_rule(bindings: &mut Vec<Binding>, rule: &DynamicMessage, grpc_method: &str, input: &MessageDescriptor) {
    push_binding(bindings, rule, grpc_method, input);
    if let Some(list) = rule.get_field_by_name("additional_bindings") {
        if let Some(items) = list.as_list() {
            for item in items {
                if let Some(m) = item.as_message() {
                    push_binding(bindings, m, grpc_method, input);
                }
            }
        }
    }
}

fn push_binding(bindings: &mut Vec<Binding>, rule: &DynamicMessage, grpc_method: &str, input: &MessageDescriptor) {
    let Some((http_method, template)) = verb_and_path(rule) else {
        return;
    };
    bindings.push(Binding {
        http_method,
        segments: parse_template(&template),
        body: body_rule(rule),
        grpc_method: grpc_method.to_string(),
        input: input.clone(),
    });
}

/// Extract the verb + path from an HttpRule's `pattern` oneof.
fn verb_and_path(rule: &DynamicMessage) -> Option<(String, String)> {
    for (field, verb) in [("get", "GET"), ("put", "PUT"), ("post", "POST"), ("delete", "DELETE"), ("patch", "PATCH")] {
        if let Some(v) = rule.get_field_by_name(field) {
            if let Some(s) = v.as_str() {
                if !s.is_empty() {
                    return Some((verb.to_string(), s.to_string()));
                }
            }
        }
    }
    // custom { kind, path }
    if let Some(v) = rule.get_field_by_name("custom") {
        if let Some(m) = v.as_message() {
            let kind = m.get_field_by_name("kind").and_then(|k| k.as_str().map(str::to_string)).unwrap_or_default();
            let path = m.get_field_by_name("path").and_then(|p| p.as_str().map(str::to_string)).unwrap_or_default();
            if !kind.is_empty() {
                return Some((kind.to_ascii_uppercase(), path));
            }
        }
    }
    None
}

fn body_rule(rule: &DynamicMessage) -> BodyRule {
    match rule.get_field_by_name("body").and_then(|b| b.as_str().map(str::to_string)).unwrap_or_default().as_str() {
        "" => BodyRule::None,
        "*" => BodyRule::Wildcard,
        field => BodyRule::Field(field.to_string()),
    }
}

/// Parse a path template into segments. A trailing `:verb` is ignored.
fn parse_template(template: &str) -> Vec<Segment> {
    let path = template.split(':').next().unwrap_or(template);
    path.trim_matches('/')
        .split('/')
        .filter(|s| !s.is_empty())
        .map(|seg| {
            if let Some(inner) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
                let (field, pattern) = inner.split_once('=').unwrap_or((inner, "*"));
                let field_path: Vec<String> = field.split('.').map(str::to_string).collect();
                if pattern == "**" {
                    Segment::Rest(field_path)
                } else {
                    Segment::Single(field_path)
                }
            } else {
                Segment::Literal(seg.to_string())
            }
        })
        .collect()
}

/// Match a request path against a template, returning captured `(field_path, value)`.
fn match_segments(segments: &[Segment], path: &str) -> Option<Vec<PathVar>> {
    let parts: Vec<&str> = path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect();
    let mut vars = Vec::new();
    let mut i = 0;
    for seg in segments {
        match seg {
            Segment::Literal(lit) => {
                if parts.get(i) != Some(&lit.as_str()) {
                    return None;
                }
                i += 1;
            }
            Segment::Single(field) => {
                let part = parts.get(i)?;
                vars.push((field.clone(), percent_decode(part)));
                i += 1;
            }
            Segment::Rest(field) => {
                let rest: Vec<String> = parts[i..].iter().map(|p| percent_decode(p)).collect();
                vars.push((field.clone(), rest.join("/")));
                i = parts.len();
            }
        }
    }
    if i == parts.len() {
        Some(vars)
    } else {
        None
    }
}

/// Build the encoded request message from a matched binding + inputs.
fn build_message(
    binding: &Binding,
    vars: &[PathVar],
    query: Option<&str>,
    body: &[u8],
) -> Result<Vec<u8>, TranscodeError> {
    let mut msg = match &binding.body {
        BodyRule::Wildcard => deserialize_message(binding.input.clone(), body)?,
        BodyRule::None => DynamicMessage::new(binding.input.clone()),
        BodyRule::Field(field) => {
            let mut m = DynamicMessage::new(binding.input.clone());
            if !body.is_empty() {
                set_message_field(&mut m, field, body)?;
            }
            m
        }
    };

    for (field_path, value) in vars {
        set_by_path(&mut msg, field_path, value)?;
    }

    // Query params bind fields not carried by a wildcard body.
    if !matches!(binding.body, BodyRule::Wildcard) {
        if let Some(q) = query {
            for (key, value) in parse_query(q) {
                let field_path: Vec<String> = key.split('.').map(str::to_string).collect();
                if vars.iter().any(|(fp, _)| *fp == field_path) {
                    continue; // already set from the path
                }
                set_by_path(&mut msg, &field_path, &value)?;
            }
        }
    }

    Ok(msg.encode_to_vec())
}

fn deserialize_message(desc: MessageDescriptor, json: &[u8]) -> Result<DynamicMessage, TranscodeError> {
    if json.is_empty() {
        return Ok(DynamicMessage::new(desc));
    }
    let mut de = serde_json::Deserializer::from_slice(json);
    let msg = DynamicMessage::deserialize(desc, &mut de)?;
    de.end()?;
    Ok(msg)
}

/// Parse `json` into the (message-typed) field `name` and set it.
fn set_message_field(msg: &mut DynamicMessage, name: &str, json: &[u8]) -> Result<(), TranscodeError> {
    let field = msg
        .descriptor()
        .get_field_by_name(name)
        .ok_or_else(|| TranscodeError::Http(format!("unknown body field: {name}")))?;
    match field.kind() {
        Kind::Message(md) => {
            let sub = deserialize_message(md, json)?;
            msg.set_field(&field, Value::Message(sub));
            Ok(())
        }
        _ => Err(TranscodeError::Http(format!("body field {name} must be a message"))),
    }
}

/// Set a (possibly nested, possibly repeated) scalar field from a string value.
fn set_by_path(msg: &mut DynamicMessage, path: &[String], raw: &str) -> Result<(), TranscodeError> {
    let field = msg
        .descriptor()
        .get_field_by_name(&path[0])
        .ok_or_else(|| TranscodeError::Http(format!("unknown field: {}", path[0])))?;

    if path.len() == 1 {
        let value = coerce(&field, raw)?;
        if field.is_list() {
            if let Some(list) = msg.get_field_mut(&field).as_list_mut() {
                list.push(value);
            }
        } else {
            msg.set_field(&field, value);
        }
        Ok(())
    } else {
        let sub = msg
            .get_field_mut(&field)
            .as_message_mut()
            .ok_or_else(|| TranscodeError::Http(format!("field {} is not a message", path[0])))?;
        set_by_path(sub, &path[1..], raw)
    }
}

/// Coerce a string into a scalar `Value` per the field's protobuf kind.
fn coerce(field: &prost_reflect::FieldDescriptor, raw: &str) -> Result<Value, TranscodeError> {
    let num = |ok: Option<Value>| ok.ok_or_else(|| TranscodeError::Http(format!("invalid value for {}: {raw:?}", field.name())));
    Ok(match field.kind() {
        Kind::String => Value::String(raw.to_string()),
        Kind::Bool => match raw {
            "true" | "1" => Value::Bool(true),
            "false" | "0" => Value::Bool(false),
            _ => return Err(TranscodeError::Http(format!("invalid bool: {raw:?}"))),
        },
        Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => num(raw.parse().ok().map(Value::I32))?,
        Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => num(raw.parse().ok().map(Value::I64))?,
        Kind::Uint32 | Kind::Fixed32 => num(raw.parse().ok().map(Value::U32))?,
        Kind::Uint64 | Kind::Fixed64 => num(raw.parse().ok().map(Value::U64))?,
        Kind::Float => num(raw.parse().ok().map(Value::F32))?,
        Kind::Double => num(raw.parse().ok().map(Value::F64))?,
        Kind::Enum(e) => {
            if let Ok(n) = raw.parse::<i32>() {
                Value::EnumNumber(n)
            } else {
                let v = e
                    .values()
                    .find(|v| v.name() == raw)
                    .ok_or_else(|| TranscodeError::Http(format!("unknown enum value: {raw:?}")))?;
                Value::EnumNumber(v.number())
            }
        }
        Kind::Bytes => return Err(TranscodeError::Http("bytes fields cannot bind from path/query".into())),
        Kind::Message(_) => return Err(TranscodeError::Http("cannot bind a scalar to a message field".into())),
    })
}

/// Parse a query string into decoded key/value pairs.
fn parse_query(query: &str) -> Vec<(String, String)> {
    query
        .split('&')
        .filter(|p| !p.is_empty())
        .map(|pair| {
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
            (decode_query(k), decode_query(v))
        })
        .collect()
}

fn decode_query(s: &str) -> String {
    percent_decode(&s.replace('+', " "))
}

/// Minimal percent-decoding (`%XX`), lossy on invalid UTF-8.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(b) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
                out.push(b);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}