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

@@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `/v1` answers in protobuf for a client that asks for it (`Accept: application/x-protobuf`) and takes a snapshot sent so; JSON stays the default. The messages are in `crates/wire/proto/directory.proto` (#465).
- `/v1` answers in protobuf for a client that asks for it (`Accept: application/x-protobuf`) and takes a snapshot sent so; JSON stays the default. The messages are in `crates/wire/proto/directory.proto`, and answers go through structs generated from them (#465, #470).
- A `robots.txt` and a sitemap listing the home page, A to Z, every category and every feed, so search engines find the pages, not only the links between them (#380).
- `/metrics` counts its requests and their times by route and status, the feeds it checks and those that failed, and the snapshots it takes (#370).
- Its log lines inside a trace carry the trace's and span's ids, as ipx's do, so a failed feed check leads to its trace (#375).

View File

@@ -97,3 +97,98 @@ pub struct Blocked {
/// The most a snapshot may list: far more than one server's subscriptions, few enough that one
/// request cannot hold the database for long.
pub const MAX_SNAPSHOT: usize = 20_000;
// The same in protobuf (#470): ipx reads and writes these through ipx-wire's structs, which
// mirror the ones above field for field.
use ipx_wire::pb::directory as pb;
impl From<pb::Listing> for Listing {
fn from(l: pb::Listing) -> Self {
Listing {
id: l.id,
url: l.url,
title: l.title,
image: l.image,
category: l.category,
subcategory: l.subcategory,
podcast: l.podcast,
subscribers: l.subscribers,
}
}
}
impl From<pb::Item> for Item {
fn from(i: pb::Item) -> Self {
Item {
guid: i.guid,
title: i.title,
link: i.link,
published: i.published,
duration: i.duration,
description: i.description,
}
}
}
impl From<pb::FeedPage> for FeedPage {
fn from(p: pb::FeedPage) -> Self {
FeedPage {
listing: Listing {
id: p.id,
url: p.url,
title: p.title,
image: p.image,
category: p.category,
subcategory: p.subcategory,
podcast: p.podcast,
subscribers: p.subscribers,
},
description: p.description,
failing: p.failing,
items: p.items.into_iter().map(Item::from).collect(),
}
}
}
impl TryFrom<pb::Me> for Me {
type Error = String;
fn try_from(m: pb::Me) -> Result<Self, String> {
let access = match m.access.as_str() {
"ro" => Access::Ro,
"rw" => Access::Rw,
"rwa" => Access::Rwa,
other => return Err(format!("an access level not known here: {other:?}")),
};
Ok(Me { name: m.name, access })
}
}
impl From<pb::Instance> for Instance {
fn from(i: pb::Instance) -> Self {
Instance { name: i.name, feeds: i.feeds, subscribers: i.subscribers }
}
}
impl From<pb::Blocked> for Blocked {
fn from(b: pb::Blocked) -> Self {
Blocked { id: b.id, url: b.url, title: b.title, at: b.at }
}
}
impl From<pb::SnapshotResult> for SnapshotResult {
fn from(r: pb::SnapshotResult) -> Self {
let n = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
SnapshotResult {
accepted: n(r.accepted),
refused_private: n(r.refused_private),
refused_blocked: n(r.refused_blocked),
refused_invalid: n(r.refused_invalid),
}
}
}
impl From<&SnapshotEntry> for pb::SnapshotEntry {
fn from(e: &SnapshotEntry) -> Self {
pb::SnapshotEntry { url: e.url.clone(), subscribers: e.subscribers, category: e.category.clone() }
}
}

View File

@@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- The API answers in protobuf as well as JSON: a client that sends `Accept: application/x-protobuf` gets protobuf, and one that sends `Content-Type: application/x-protobuf` may send its body so; JSON stays the default, so the page and older clients see nothing new. The messages are in `crates/wire/proto/ipx.proto`. ipx's own calls to the directory and ipx-play go in protobuf too, so both need their protobuf releases first (#465).
- The API answers in protobuf as well as JSON: a client that sends `Accept: application/x-protobuf` gets protobuf, and one that sends `Content-Type: application/x-protobuf` may send its body so; JSON stays the default for a client that does not ask, and an answer of null stays JSON. The messages are in `crates/wire/proto/ipx.proto`. ipx's own calls to the directory and ipx-play go in protobuf too, so both need their protobuf releases first. Answers and those calls go through structs generated from the `.proto` files, about four times quicker to read than the JSON (#465, #470).
- Sharing an episode gives a link to its page on ipx-play, which anyone can open and play, set up in Admin, Directory, Sharing episodes; private and paid feeds still share their own address (#447).
- The iOS app's icon count stays right with the app closed: with `[push]` set to an APNs key, ipx sends each registered phone (`POST /api/push/devices`, removed with `DELETE`) its All Subscriptions unread count through Apple's push service, within a minute of a change (#433). The push also wakes the app for a moment, for its widget to show the same count (#428).
- A place in an episode saved from DeadAir's shortened version names its file (`deadair` in `POST .../position`), so it is read in that version's clock even when ipx never handed out its playlist, as for a copy kept on the device or after a restart (#412).

View File

@@ -5,6 +5,8 @@
use std::collections::{HashMap, HashSet};
use ipx_directory::{FeedPage, Listing, Me, SnapshotEntry, SnapshotResult};
use ipx_wire::Message as _;
use ipx_wire::pb::directory as pb;
use serde::de::DeserializeOwned;
use crate::catalogue::Sub;
@@ -65,6 +67,13 @@ pub fn configured(cfg: &config::Config) -> bool {
target(cfg).is_some()
}
/// How an answer in protobuf becomes what the caller wants (#470).
type Decode<T> = fn(&[u8]) -> Result<T, String>;
fn listings(b: &[u8]) -> Result<Vec<Listing>, String> {
Ok(pb::Listings::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Listing::from).collect())
}
/// A span the whole call, its answer read and parsed included: the directory's own span ends when it
/// has answered, so a slow read of a large answer showed under no span (#250).
#[tracing::instrument(name = "directory_call", skip_all, fields(http.request.method = %method, url.path = %path.split('?').next().unwrap_or(path), http.response.body.size))]
@@ -73,7 +82,7 @@ async fn call<T: DeserializeOwned>(
method: reqwest::Method,
path: &str,
body: Option<&[SnapshotEntry]>,
answer: &str,
answer: Option<Decode<T>>,
) -> Result<T, DirError> {
let (base, token) = target(&ctx.cfg()).ok_or(DirError::NotConfigured)?;
let mut req =
@@ -83,13 +92,13 @@ async fn call<T: DeserializeOwned>(
req = req.header("traceparent", tp);
}
// Protobuf both ways (#465), where the answer has a message: a smaller body to read.
if !answer.is_empty() {
if answer.is_some() {
req = req.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF);
}
// A snapshot is about 100 KB, sent gzipped; the directory unpacks it (#253).
if let Some(b) = body {
use std::io::Write as _;
let pb = ipx_wire::encode("directory.Snapshot", &b).map_err(DirError::Unreachable)?;
let pb = pb::Snapshot { items: b.iter().map(pb::SnapshotEntry::from).collect() }.encode_to_vec();
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&pb).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
let packed = gz.finish().map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
@@ -116,9 +125,8 @@ async fn call<T: DeserializeOwned>(
// A removal or an unblock answers 204, with nothing to read: that reads as null, which is ().
let body = resp.bytes().await.map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
tracing::Span::current().record("http.response.body.size", body.len());
if protobuf {
return ipx_wire::decode(answer, &body)
.map_err(|e| DirError::Unreachable(format!("its answer did not read: {e}")));
if let Some(decode) = answer.filter(|_| protobuf) {
return decode(&body).map_err(|e| DirError::Unreachable(format!("its answer did not read: {e}")));
}
serde_json::from_slice(if body.is_empty() { b"null" } else { &body })
.map_err(|e| DirError::Unreachable(format!("its answer did not read: {e:#}")))
@@ -129,24 +137,31 @@ fn seg(s: &str) -> percent_encoding::PercentEncode<'_> {
}
pub async fn me(ctx: &Ctx) -> Result<Me, DirError> {
call(ctx, reqwest::Method::GET, "/v1/me", None, "directory.Me").await
call(ctx, reqwest::Method::GET, "/v1/me", None, Some(|b| pb::Me::decode(b).map_err(|e| e.to_string())?.try_into()))
.await
}
pub async fn feeds(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None, "directory.Listings").await?;
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None, Some(listings)).await?;
note_art(got.iter());
Ok(got)
}
pub async fn popular(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None, "directory.Listings").await?;
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None, Some(listings)).await?;
note_art(got.iter());
Ok(got)
}
pub async fn page(ctx: &Ctx, id: &str) -> Result<FeedPage, DirError> {
let got: FeedPage =
call(ctx, reqwest::Method::GET, &format!("/v1/feeds/{}", seg(id)), None, "directory.FeedPage").await?;
let got: FeedPage = call(
ctx,
reqwest::Method::GET,
&format!("/v1/feeds/{}", seg(id)),
None,
Some(|b| pb::FeedPage::decode(b).map(FeedPage::from).map_err(|e| e.to_string())),
)
.await?;
note_art(std::iter::once(&got.listing));
Ok(got)
}
@@ -171,29 +186,45 @@ pub fn listed_art(url: &str) -> bool {
/// Removes a feed and blocks it, so no snapshot brings it back.
pub async fn remove(ctx: &Ctx, id: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None, "").await
call(ctx, reqwest::Method::DELETE, &format!("/v1/feeds/{}", seg(id)), None, None).await
}
pub async fn refresh(ctx: &Ctx, id: &str) -> Result<serde::de::IgnoredAny, DirError> {
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None, "").await
call(ctx, reqwest::Method::POST, &format!("/v1/feeds/{}/refresh", seg(id)), None, None).await
}
pub async fn blocked(ctx: &Ctx) -> Result<Vec<ipx_directory::Blocked>, DirError> {
call(ctx, reqwest::Method::GET, "/v1/blocked", None, "directory.BlockedList").await
call(
ctx,
reqwest::Method::GET,
"/v1/blocked",
None,
Some(|b| {
Ok(pb::BlockedList::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())
}),
)
.await
}
pub async fn unblock(ctx: &Ctx, id: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None, "").await
call(ctx, reqwest::Method::DELETE, &format!("/v1/blocked/{}", seg(id)), None, None).await
}
pub async fn instances(ctx: &Ctx) -> Result<Vec<ipx_directory::Instance>, DirError> {
call(ctx, reqwest::Method::GET, "/v1/instances", None, "directory.Instances").await
call(
ctx,
reqwest::Method::GET,
"/v1/instances",
None,
Some(|b| Ok(pb::Instances::decode(b).map_err(|e| e.to_string())?.items.into_iter().map(Into::into).collect())),
)
.await
}
/// Drops one server's snapshot, and its counts with it. It comes back with that server's next
/// one: to keep a server out, revoke its token.
pub async fn drop_instance(ctx: &Ctx, name: &str) -> Result<(), DirError> {
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None, "").await
call(ctx, reqwest::Method::DELETE, &format!("/v1/instances/{}", seg(name)), None, None).await
}
/// Has the snapshot sent again now, changed or not.
@@ -248,8 +279,14 @@ async fn snapshot(ctx: &Ctx) -> Result<Vec<SnapshotEntry>, DirError> {
}
pub async fn share(ctx: &Ctx, entries: &[SnapshotEntry]) -> Result<SnapshotResult, DirError> {
let r: SnapshotResult =
call(ctx, reqwest::Method::POST, "/v1/snapshot", Some(entries), "directory.SnapshotResult").await?;
let r: SnapshotResult = call(
ctx,
reqwest::Method::POST,
"/v1/snapshot",
Some(entries),
Some(|b| pb::SnapshotResult::decode(b).map(Into::into).map_err(|e| e.to_string())),
)
.await?;
if r.refused_private > 0 {
// The directory caught what this side should have: worth knowing which check differs.
tracing::warn!(refused = r.refused_private, "the directory refused feeds as private that ipx sent");

View File

@@ -4,6 +4,7 @@
//! file address, which carries someone's access, never leaves this server.
use crate::ctx::Ctx;
use ipx_wire::Message as _;
use std::collections::HashMap;
use std::time::Duration;
@@ -79,7 +80,22 @@ pub async fn share(
// Protobuf both ways (#465).
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
.header(reqwest::header::ACCEPT, ipx_wire::PROTOBUF)
.body(ipx_wire::encode("play.Episode", &episode).map_err(NoLink::Failed)?);
.body(
ipx_wire::pb::play::Episode {
feed_url: episode.feed_url,
guid: episode.guid,
feed_title: episode.feed_title,
feed_image: episode.feed_image,
title: episode.title,
description: episode.description,
link: episode.link,
published: episode.published,
duration: episode.duration,
audio_url: episode.audio_url,
mime: episode.mime,
}
.encode_to_vec(),
);
// Its spans join this request's trace.
if let Some(tp) = ipx_directory::otel::traceparent() {
req = req.header("traceparent", tp);
@@ -91,7 +107,9 @@ pub async fn share(
return Err(NoLink::Failed(format!("ipx-play answered {status}: {}", msg.unwrap_or_default())));
}
let body = resp.bytes().await.map_err(|e| NoLink::Failed(format!("reading ipx-play's answer: {e:#}")))?;
ipx_wire::decode("play.Shared", &body).map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e}")))
let shared = ipx_wire::pb::play::Shared::decode(body)
.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e}")))?;
Ok(ipx_play::Shared { id: shared.id, url: shared.url })
}
#[cfg(test)]

View File

@@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `POST /v1/shares` takes and answers protobuf (`application/x-protobuf`) as well as JSON, chosen by `Content-Type` and `Accept`. The messages are in `crates/wire/proto/play.proto` (#465).
- `POST /v1/shares` takes and answers protobuf (`application/x-protobuf`) as well as JSON, chosen by `Content-Type` and `Accept`. The messages are in `crates/wire/proto/play.proto`, and answers go through structs generated from them (#465, #470).
- A page for each shared episode, at `/e/<id>`: its show, title, date, length and notes, a player that plays the publisher's own file from the time it was shared at (`?t=754` or `?t=12:34`), buttons to subscribe in Apple Podcasts, Overcast, Pocket Casts or Castro, the feed's address, and a preview where the link is pasted (#447).
- `POST /v1/shares`, for an ipx server with a token from `ipx-play token <name>`: an episode in, its short link out, the same link however often and from whichever server it is shared. An address that looks like a private or paid feed's is refused (#447).
- Metrics for Prometheus on a port of its own, `metrics_bind`: requests by route and status and their time, episodes shared, memory (#458).

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