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

@@ -11,12 +11,15 @@ workspace = true
axum.workspace = true
prost.workspace = true
prost-reflect.workspace = true
prost-types.workspace = true
serde.workspace = true
serde_json.workspace = true
tracing.workspace = true
[build-dependencies]
prost.workspace = true
prost-build.workspace = true
prost-types.workspace = true
protox.workspace = true
[dev-dependencies]

View File

@@ -1,7 +1,9 @@
//! Compiles the `.proto` files into one descriptor set the crate reads at run time. protox is a
//! Compiles the `.proto` files into one descriptor set the crate reads at run time, and into Rust
//! structs (prost) that read the handlers' JSON straight into protobuf (#470). protox is a
//! compiler in Rust, so building needs no `protoc` on the host or in the image.
use prost::Message as _;
use std::fmt::Write as _;
fn main() {
let files = ["proto/ipx.proto", "proto/directory.proto", "proto/play.proto"];
@@ -11,4 +13,35 @@ fn main() {
let set = protox::compile(files, ["proto"]).unwrap_or_else(|e| panic!("{e:?}"));
let out = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets OUT_DIR"));
std::fs::write(out.join("wire.bin"), set.encode_to_vec()).expect("writing the descriptor set");
// Every message that reads from JSON with serde: all but the bodies holding Google's Value or
// ListValue, whose JSON serde cannot read; those go the slow way, through prost-reflect.
let mut config = prost_build::Config::new();
let mut fast = String::from(
"/// An answer's JSON as message `name` in protobuf, when `name` has a struct here.\n\
pub fn json_to_proto(name: &str, json: &[u8]) -> Option<Result<Vec<u8>, String>> {\n match name {\n",
);
for file in set.file.iter().filter(|f| f.package() != "google.protobuf") {
for m in &file.message_type {
if m.field.iter().any(|f| f.type_name().starts_with(".google.")) {
continue;
}
let path = format!(".{}.{}", file.package(), m.name());
// A list message is the JSON array itself.
let list = matches!(&m.field[..], [only] if only.name() == "items"
&& only.label() == prost_types::field_descriptor_proto::Label::Repeated);
let attrs = if list {
"#[derive(serde::Deserialize)] #[serde(transparent)]"
} else {
// Debug builds refuse a field the message lacks, as the slow way does.
"#[derive(serde::Deserialize)] #[serde(default)] #[cfg_attr(debug_assertions, serde(deny_unknown_fields))]"
};
config.type_attribute(&path, attrs);
writeln!(fast, " {:?} => Some(encode::<pb::{}::{}>(json)),", &path[1..], file.package(), m.name())
.expect("writing to a String");
}
}
fast.push_str(" _ => None,\n }\n}\n");
std::fs::write(out.join("fast.rs"), fast).expect("writing fast.rs");
config.out_dir(&out).compile_fds(set).unwrap_or_else(|e| panic!("{e:?}"));
}

View File

@@ -10,7 +10,7 @@
// An Option<Vec> in a body is one (Words), so leaving a list alone and emptying it differ.
// * A body field that takes null to clear it is a google.protobuf.Value: absent leaves it, null
// clears it, a value sets it.
// * An answer of JSON null is an empty message.
// * An answer of JSON null stays JSON null: the empty message would be a row of defaults.
syntax = "proto3";
package ipx;
@@ -249,8 +249,8 @@ message EntryPage {
repeated EntryRow entries = 2;
}
// POST /api/entries/{feed_id}/{guid}/flags, the body. The answer is the feed's FeedRow, or an
// empty one when the feed is not yours.
// POST /api/entries/{feed_id}/{guid}/flags, the body. The answer is the feed's FeedRow, or JSON
// null when the feed is not yours.
message Flags {
optional bool read = 1;
optional bool flagged = 2;

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");