Answers in protobuf from generated structs, and the page reads them (#470)

ipx-wire converted every protobuf answer at run time through
prost-reflect and serde_json::Value, so protobuf cost more than the JSON
it replaced: decoding 1,488 feeds took 1.50 ms that way against 0.37 ms
for serde_json and 0.09 ms for prost's own structs, and GET /api/feeds as
protobuf answered about 4 ms after JSON.

build.rs now generates those structs (prost-build from protox's
descriptors, still no protoc). An answer's JSON goes straight into its
struct with serde and out with prost, byte for byte what the runtime
path wrote (a test says so); bodies holding a google.protobuf.Value keep
the runtime path, as they are only ever read. ipx's calls to the
directory and ipx-play build and read the structs directly, through
From conversions beside the directory's own types.

The page asks for protobuf too, to see what it does in practice. It
reads it with web/src/wire.ts, about seventy lines and no library:
protobufjs alone was larger gzipped than all protobuf saves the page.
build.mts reads the .proto files into a table for it, and the answer
names its message in its Content-Type, so the page keeps no table of
routes. An answer of null stays JSON, since the empty message would be a
feed row of defaults. The offline worker decodes a kept answer to mark
what was read offline, and hands the page JSON.

The decoder's test caught `pos += varint()[0]`, which adds the length
to pos as it was before the varint was read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 00:21:41 +00:00
parent baa6661622
commit 236bd02d88
22 changed files with 497 additions and 68 deletions

View File

@@ -19,14 +19,38 @@ 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";
/// For a client to encode and decode the structs in `pb` without naming prost itself.
pub use prost::Message;
/// The messages as Rust structs, which the answers go into from their JSON and which a client
/// in Rust reads and writes (#470): prost's own encoding, several times faster than going through
/// the descriptors at run time.
#[allow(clippy::all, clippy::pedantic, missing_docs)]
pub mod pb {
pub mod directory {
include!(concat!(env!("OUT_DIR"), "/directory.rs"));
}
pub mod ipx {
include!(concat!(env!("OUT_DIR"), "/ipx.rs"));
}
pub mod play {
include!(concat!(env!("OUT_DIR"), "/play.rs"));
}
}
include!(concat!(env!("OUT_DIR"), "/fast.rs"));
/// The JSON an answer was into its struct, and that into protobuf.
fn encode<T: DeserializeOwned + prost::Message>(json: &[u8]) -> Result<Vec<u8>, String> {
Ok(serde_json::from_slice::<T>(json).map_err(|e| e.to_string())?.encode_to_vec())
}
/// The most read of a body either way: axum's own limit for `Json`.
const LIMIT: usize = 2 << 20;
@@ -133,18 +157,6 @@ fn whole(v: &mut Value) {
}
}
/// 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))
@@ -202,11 +214,19 @@ pub async fn negotiate(State(routes): State<Routes>, path: MatchedPath, req: Req
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)));
// None stays JSON null: as protobuf it would be the empty message, which is also every field
// at its default, and a client could not tell "no feed row" from a blank one.
if bytes.trim_ascii() == b"null" {
return Response::from_parts(parts, Body::from(bytes));
}
let converted = json_to_proto(answers, &bytes).unwrap_or_else(|| {
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));
// Which message it is, for a client with no table of routes (the page).
let ct = format!("{PROTOBUF}; messageType={answers}");
parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_str(&ct).expect("a message name is ASCII"));
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, Body::from(pb))
}
@@ -266,6 +286,19 @@ mod tests {
);
}
#[test]
fn the_structs_encode_as_the_descriptors_do() {
let feeds = json!([{ "id": "a", "url": "u", "title": null, "keywords": ["k"], "every_mins": 60,
"failing": { "reason": "gone", "new_url": null }, "subscribers": 2, "private": true }]);
let slow = to_proto(&message("ipx.FeedRows").unwrap(), feeds.clone(), false).unwrap();
let fast = json_to_proto("ipx.FeedRows", feeds.to_string().as_bytes()).unwrap().unwrap();
assert_eq!(fast, slow);
assert!(json_to_proto("ipx.FeedPatch", b"{}").is_none(), "a body with a Value goes the slow way");
if cfg!(debug_assertions) {
assert!(json_to_proto("play.Shared", br#"{"id":"x","url":"u","new":1}"#).unwrap().is_err());
}
}
#[test]
fn strict_refuses_a_field_the_message_lacks() {
let d = message("play.Shared").unwrap();
@@ -286,7 +319,9 @@ mod tests {
}),
)
.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 ep =
pb::play::Episode { feed_url: "f".into(), guid: "g1".into(), audio_url: "a".into(), ..Default::default() };
let body = ep.encode_to_vec();
let ask = |accept: &'static str| {
Request::post("/v1/shares")
.header(header::CONTENT_TYPE, PROTOBUF)
@@ -296,9 +331,9 @@ mod tests {
};
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" }));
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/x-protobuf; messageType=play.Shared");
let got = pb::play::Shared::decode(to_bytes(resp.into_body(), LIMIT).await.unwrap()).unwrap();
assert_eq!((got.id.as_str(), got.url.as_str()), ("g1", "u"));
let resp = app.clone().oneshot(ask("application/json")).await.unwrap();
assert_eq!(resp.headers()[header::CONTENT_TYPE], "application/json");