Protobuf beside JSON in ipx's, the directory's and ipx-play's APIs (#465); ipx's build touches crates/play (#466)
A client sending Accept: application/x-protobuf gets protobuf, and one sending Content-Type: application/x-protobuf may send its body so; JSON stays the default, so the page, the TUI and older iOS builds see nothing new. ipx's own calls to the directory and ipx-play now go in protobuf. The handlers are untouched. A new crate, ipx-wire, holds the .proto files (compiled by protox in build.rs, so no protoc anywhere) and one layer, negotiate, that converts JSON at the edge through prost-reflect, by a table of each route's messages. Writing prost structs beside every serde one would have doubled each type and every handler. Protobuf cannot tell absent from empty or from null, and the PATCH bodies depend on that: an Option<Vec> left out leaves the list, an empty one clears it, and null clears a folder. So a list in a body is a one-field message (absent or present), and null-to-clear is a google.protobuf.Value. Numbers in a Value come back whole, or 3.0 would not read as a usize. Debug builds convert every JSON answer strictly and answer 500 for a field missing from the .proto or a route missing from a table; the cargo tests and the browser suite (125 tests) ran clean that way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
310
crates/wire/src/lib.rs
Normal file
310
crates/wire/src/lib.rs
Normal file
@@ -0,0 +1,310 @@
|
||||
//! Protobuf beside JSON (#465). The handlers speak JSON, as they always have; a route's
|
||||
//! messages in `proto/` say what the same answer is in protobuf, and `negotiate` converts at the
|
||||
//! edge: a request body sent as `application/x-protobuf` becomes the JSON the handler reads, and
|
||||
//! an answer becomes protobuf for a client whose `Accept` asks for it. Anyone not asking gets JSON
|
||||
//! exactly as before.
|
||||
//!
|
||||
//! How a message stands for JSON is said at the top of `proto/ipx.proto`: names as in JSON, an
|
||||
//! Option `optional`, a message of only `repeated items` an array, null-to-clear a
|
||||
//! `google.protobuf.Value`.
|
||||
//!
|
||||
//! Debug builds convert every JSON answer of a route in the table, asked for or not, refusing
|
||||
//! fields the message lacks, and answer 500 when a route has no message: the cargo tests and the
|
||||
//! browser suite, which run debug builds, then fail on a field added in Rust and not in `proto/`.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use axum::body::{Body, to_bytes};
|
||||
use axum::extract::{MatchedPath, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use prost::Message as _;
|
||||
use prost_reflect::{DescriptorPool, DeserializeOptions, DynamicMessage, Kind, MessageDescriptor, SerializeOptions};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const PROTOBUF: &str = "application/x-protobuf";
|
||||
|
||||
/// The most read of a body either way: axum's own limit for `Json`.
|
||||
const LIMIT: usize = 2 << 20;
|
||||
|
||||
static POOL: LazyLock<DescriptorPool> = LazyLock::new(|| {
|
||||
DescriptorPool::decode(include_bytes!(concat!(env!("OUT_DIR"), "/wire.bin")).as_slice())
|
||||
.expect("build.rs wrote a valid descriptor set")
|
||||
});
|
||||
|
||||
/// Each route's method, its path as the router has it, the message its body is and the message
|
||||
/// it answers, by full name; "" where it takes or answers no JSON.
|
||||
pub type Routes = &'static [(&'static str, &'static str, &'static str, &'static str)];
|
||||
|
||||
/// A message by full name (`ipx.Feed`).
|
||||
pub fn message(name: &str) -> Option<MessageDescriptor> {
|
||||
POOL.get_message_by_name(name)
|
||||
}
|
||||
|
||||
fn is_list(d: &MessageDescriptor) -> bool {
|
||||
let mut f = d.fields();
|
||||
matches!((f.next(), f.next()), (Some(only), None) if only.name() == "items" && only.is_list())
|
||||
}
|
||||
|
||||
/// Each message field of `d` in `v`, with its descriptor, for `wrap` and `unwrap` to go down.
|
||||
/// Not maps, and not Google's own types, whose JSON is theirs.
|
||||
fn children<'a>(d: &MessageDescriptor, v: &'a mut Value) -> Vec<(MessageDescriptor, &'a mut Value)> {
|
||||
let Some(obj) = v.as_object_mut() else { return vec![] };
|
||||
let mut out = Vec::new();
|
||||
for (key, val) in obj.iter_mut() {
|
||||
let Some(f) = d.get_field_by_name(key) else { continue };
|
||||
let Kind::Message(m) = f.kind() else { continue };
|
||||
if f.is_map() || m.package_name() == "google.protobuf" {
|
||||
continue;
|
||||
}
|
||||
if f.is_list() {
|
||||
out.extend(val.as_array_mut().into_iter().flatten().map(|i| (m.clone(), i)));
|
||||
} else {
|
||||
out.push((m, val));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON array where a list message is, made that message.
|
||||
fn wrap(d: &MessageDescriptor, v: &mut Value) {
|
||||
if v.is_array() && is_list(d) {
|
||||
*v = serde_json::json!({ "items": v.take() });
|
||||
}
|
||||
for (m, c) in children(d, v) {
|
||||
wrap(&m, c);
|
||||
}
|
||||
}
|
||||
|
||||
/// A list message made the array it stands for; none sent is an empty one.
|
||||
fn unwrap(d: &MessageDescriptor, v: &mut Value) {
|
||||
for (m, c) in children(d, v) {
|
||||
unwrap(&m, c);
|
||||
}
|
||||
if is_list(d) {
|
||||
*v = match v["items"].take() {
|
||||
Value::Null => Value::Array(vec![]),
|
||||
items => items,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON to protobuf. `strict` refuses a field the message does not have, where otherwise it is
|
||||
/// left out, as a newer server's field is for an older client. JSON null is the empty message.
|
||||
pub fn to_proto(d: &MessageDescriptor, mut v: Value, strict: bool) -> Result<Vec<u8>, String> {
|
||||
if v.is_null() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
wrap(d, &mut v);
|
||||
let opts = DeserializeOptions::new().deny_unknown_fields(strict);
|
||||
let msg =
|
||||
DynamicMessage::deserialize_with_options(d.clone(), v, &opts).map_err(|e| format!("{}: {e}", d.full_name()))?;
|
||||
Ok(msg.encode_to_vec())
|
||||
}
|
||||
|
||||
/// Protobuf to the JSON the same struct reads: field names as written, 64-bit numbers as numbers,
|
||||
/// a field without presence always, so a default value reads as itself, and an `optional` or a
|
||||
/// message only when sent, so an absent one reads as None.
|
||||
pub fn from_proto(d: &MessageDescriptor, bytes: &[u8]) -> Result<Value, String> {
|
||||
let msg = DynamicMessage::decode(d.clone(), bytes).map_err(|e| format!("{}: {e}", d.full_name()))?;
|
||||
let opts =
|
||||
SerializeOptions::new().use_proto_field_name(true).stringify_64_bit_integers(false).skip_default_fields(false);
|
||||
let mut v = msg.serialize_with_options(serde_json::value::Serializer, &opts).map_err(|e| e.to_string())?;
|
||||
unwrap(d, &mut v);
|
||||
whole(&mut v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// A whole number as an integer: a google.protobuf.Value holds every number as a double, and
|
||||
/// `3.0` does not read as a usize where `3` reads as an f64 too.
|
||||
fn whole(v: &mut Value) {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
if let Some(f) = n.as_f64().filter(|f| n.is_f64() && f.fract() == 0.0 && f.abs() < 9e15) {
|
||||
*v = Value::from(f as i64);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(whole),
|
||||
Value::Object(o) => o.values_mut().for_each(whole),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A value as message `name`, for a client sending protobuf.
|
||||
pub fn encode<T: Serialize>(name: &str, value: &T) -> Result<Vec<u8>, String> {
|
||||
let d = message(name).ok_or_else(|| format!("no message {name}"))?;
|
||||
to_proto(&d, serde_json::to_value(value).map_err(|e| e.to_string())?, false)
|
||||
}
|
||||
|
||||
/// Message `name` as a value, for a client reading protobuf.
|
||||
pub fn decode<T: DeserializeOwned>(name: &str, bytes: &[u8]) -> Result<T, String> {
|
||||
let d = message(name).ok_or_else(|| format!("no message {name}"))?;
|
||||
serde_json::from_value(from_proto(&d, bytes)?).map_err(|e| format!("{name}: {e}"))
|
||||
}
|
||||
|
||||
fn is(headers: &HeaderMap, name: header::HeaderName, mime: &str) -> bool {
|
||||
// shortcut: a substring, not a parsed Accept, so `q=0` still counts; parse it if a client sends one.
|
||||
headers.get(name).and_then(|v| v.to_str().ok()).is_some_and(|v| v.contains(mime))
|
||||
}
|
||||
|
||||
fn refuse(code: StatusCode, msg: String) -> Response {
|
||||
(code, axum::Json(serde_json::json!({ "error": msg }))).into_response()
|
||||
}
|
||||
|
||||
/// The layer, as `route_layer(from_fn_with_state(ROUTES, ipx_wire::negotiate))`, inside any
|
||||
/// request decompression so it reads the body unpacked.
|
||||
pub async fn negotiate(State(routes): State<Routes>, path: MatchedPath, req: Request, next: Next) -> Response {
|
||||
let method = req.method().as_str().to_owned();
|
||||
let (takes, answers) =
|
||||
routes.iter().find(|r| r.0 == method && r.1 == path.as_str()).map(|r| (r.2, r.3)).unwrap_or(("", ""));
|
||||
|
||||
let req = if is(req.headers(), header::CONTENT_TYPE, PROTOBUF) {
|
||||
let Some(d) = message(takes) else {
|
||||
return refuse(StatusCode::UNSUPPORTED_MEDIA_TYPE, format!("{method} {} takes no protobuf", path.as_str()));
|
||||
};
|
||||
let (mut parts, body) = req.into_parts();
|
||||
let Ok(bytes) = to_bytes(body, LIMIT).await else {
|
||||
return refuse(StatusCode::PAYLOAD_TOO_LARGE, "the body is too large".into());
|
||||
};
|
||||
let json = match from_proto(&d, &bytes) {
|
||||
Ok(v) => v.to_string(),
|
||||
Err(e) => return refuse(StatusCode::BAD_REQUEST, format!("the body did not read as {e}")),
|
||||
};
|
||||
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Request::from_parts(parts, Body::from(json))
|
||||
} else {
|
||||
req
|
||||
};
|
||||
|
||||
let wants = is(req.headers(), header::ACCEPT, PROTOBUF);
|
||||
let mut resp = next.run(req).await;
|
||||
if !answers.is_empty() {
|
||||
resp.headers_mut().append(header::VARY, HeaderValue::from_static("accept"));
|
||||
}
|
||||
let json = resp.status().is_success() && is(resp.headers(), header::CONTENT_TYPE, "application/json");
|
||||
if !json || !(wants || cfg!(debug_assertions)) {
|
||||
return resp;
|
||||
}
|
||||
let Some(d) = message(answers) else {
|
||||
if cfg!(debug_assertions) {
|
||||
return refuse(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("{method} {} answers JSON with no message for it in ipx-wire", path.as_str()),
|
||||
);
|
||||
}
|
||||
return resp;
|
||||
};
|
||||
let (mut parts, body) = resp.into_parts();
|
||||
let Ok(bytes) = to_bytes(body, usize::MAX).await else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||
};
|
||||
let converted =
|
||||
serde_json::from_slice(&bytes).map_err(|e| e.to_string()).and_then(|v| to_proto(&d, v, cfg!(debug_assertions)));
|
||||
match converted {
|
||||
Ok(pb) if wants => {
|
||||
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(PROTOBUF));
|
||||
parts.headers.remove(header::CONTENT_LENGTH);
|
||||
Response::from_parts(parts, Body::from(pb))
|
||||
}
|
||||
Err(e) if cfg!(debug_assertions) => refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("not as protobuf: {e}")),
|
||||
// Asked for protobuf and it would not convert: the JSON, which says what it is.
|
||||
Err(e) => {
|
||||
tracing::warn!(route = path.as_str(), error = %e, "answer did not convert to protobuf");
|
||||
Response::from_parts(parts, Body::from(bytes))
|
||||
}
|
||||
Ok(_) => Response::from_parts(parts, Body::from(bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::routing::post;
|
||||
use serde_json::json;
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
fn round(name: &str, v: Value) -> Value {
|
||||
let d = message(name).unwrap();
|
||||
from_proto(&d, &to_proto(&d, v, true).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_message_named_in_a_table_exists() {
|
||||
// The tables live in the services; these are the names that would break a client first.
|
||||
for m in ["ipx.FeedRows", "ipx.EntryPage", "ipx.Me", "ipx.Position", "directory.Snapshot", "play.Shared"] {
|
||||
assert!(message(m).is_some(), "{m}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_and_lists_come_back_as_they_went() {
|
||||
let ep = json!({ "feed_url": "https://a/f", "guid": "g", "title": "T", "published": 1_700_000_000_000_i64,
|
||||
"audio_url": "https://a/1.mp3" });
|
||||
let back = round("play.Episode", ep.clone());
|
||||
assert_eq!(back, ep, "absent optionals stay absent, 64-bit numbers stay numbers");
|
||||
|
||||
let rows = json!([{ "id": "a", "url": "u", "subscribers": 2, "podcast": true }]);
|
||||
let back = round("directory.Listings", rows);
|
||||
assert_eq!(back[0]["id"], "a");
|
||||
assert_eq!(back[0]["subscribers"], 2);
|
||||
assert_eq!(round("directory.Listings", json!([])), json!([]), "an empty list is an empty array");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_tells_absent_from_empty_and_from_null() {
|
||||
assert_eq!(round("ipx.MePatch", json!({})), json!({}), "nothing sent changes nothing");
|
||||
assert_eq!(round("ipx.MePatch", json!({ "blocked": [] })), json!({ "blocked": [] }), "emptied");
|
||||
assert_eq!(round("ipx.MePatch", json!({ "typesafe_key": null })), json!({ "typesafe_key": null }), "cleared");
|
||||
assert_eq!(
|
||||
round("ipx.FeedPatch", json!({ "max_new_per_check": 3, "pinned": false })),
|
||||
json!({
|
||||
"max_new_per_check": 3, "pinned": false })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_refuses_a_field_the_message_lacks() {
|
||||
let d = message("play.Shared").unwrap();
|
||||
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), true).is_err());
|
||||
assert!(to_proto(&d, json!({ "id": "x", "url": "u", "new": 1 }), false).is_ok());
|
||||
assert_eq!(to_proto(&message("ipx.FeedRow").unwrap(), Value::Null, true).unwrap(), Vec::<u8>::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_layer_converts_only_for_who_asks() {
|
||||
const ROUTES: Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
|
||||
let app =
|
||||
axum::Router::new()
|
||||
.route(
|
||||
"/v1/shares",
|
||||
post(|axum::Json(e): axum::Json<Value>| async move {
|
||||
axum::Json(json!({ "id": e["guid"], "url": "u" }))
|
||||
}),
|
||||
)
|
||||
.route_layer(axum::middleware::from_fn_with_state(ROUTES, negotiate));
|
||||
let body = encode("play.Episode", &json!({ "feed_url": "f", "guid": "g1", "audio_url": "a" })).unwrap();
|
||||
let ask = |accept: &'static str| {
|
||||
Request::post("/v1/shares")
|
||||
.header(header::CONTENT_TYPE, PROTOBUF)
|
||||
.header(header::ACCEPT, accept)
|
||||
.body(Body::from(body.clone()))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let resp = app.clone().oneshot(ask(PROTOBUF)).await.unwrap();
|
||||
assert_eq!(resp.headers()[header::CONTENT_TYPE], PROTOBUF);
|
||||
let got: Value = decode("play.Shared", &to_bytes(resp.into_body(), LIMIT).await.unwrap()).unwrap();
|
||||
assert_eq!(got, json!({ "id": "g1", "url": "u" }));
|
||||
|
||||
let resp = app.clone().oneshot(ask("application/json")).await.unwrap();
|
||||
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/json");
|
||||
|
||||
let bad =
|
||||
Request::post("/v1/shares").header(header::CONTENT_TYPE, PROTOBUF).body(Body::from("\u{ff}")).unwrap();
|
||||
assert_eq!(app.oneshot(bad).await.unwrap().status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user