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:
@@ -12,6 +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).
|
||||
- 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).
|
||||
|
||||
@@ -18,6 +18,7 @@ axum.workspace = true
|
||||
clap.workspace = true
|
||||
futures-util.workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
opentelemetry-otlp.workspace = true
|
||||
opentelemetry_sdk.workspace = true
|
||||
|
||||
@@ -17,6 +17,18 @@ use tower_http::compression::CompressionLayer;
|
||||
use tower_http::decompression::RequestDecompressionLayer;
|
||||
use tracing::Instrument;
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON.
|
||||
const WIRE: ipx_wire::Routes = &[
|
||||
("GET", "/v1/me", "", "directory.Me"),
|
||||
("GET", "/v1/feeds", "", "directory.Listings"),
|
||||
("GET", "/v1/popular", "", "directory.Listings"),
|
||||
("GET", "/v1/feeds/{id}", "", "directory.FeedPage"),
|
||||
("POST", "/v1/feeds/{id}/refresh", "", "directory.FeedPage"),
|
||||
("POST", "/v1/snapshot", "directory.Snapshot", "directory.SnapshotResult"),
|
||||
("GET", "/v1/blocked", "", "directory.BlockedList"),
|
||||
("GET", "/v1/instances", "", "directory.Instances"),
|
||||
];
|
||||
|
||||
/// Every route: the API under `/v1`, behind a token, and the public pages.
|
||||
pub fn router(dir: Shared) -> Router {
|
||||
let v1 = Router::new()
|
||||
@@ -30,6 +42,7 @@ pub fn router(dir: Shared) -> Router {
|
||||
.route("/v1/blocked/{id}", delete(unblock))
|
||||
.route("/v1/instances", get(instances))
|
||||
.route("/v1/instances/{name}", delete(drop_instance))
|
||||
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.layer(axum::middleware::from_fn_with_state(dir.clone(), authenticate));
|
||||
Router::new()
|
||||
.route("/healthz", get(healthz))
|
||||
|
||||
@@ -14,6 +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).
|
||||
- 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).
|
||||
|
||||
@@ -17,6 +17,7 @@ workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-directory.workspace = true
|
||||
ipx-play.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
ammonia.workspace = true
|
||||
anyhow.workspace = true
|
||||
argon2.workspace = true
|
||||
|
||||
@@ -73,6 +73,7 @@ async fn call<T: DeserializeOwned>(
|
||||
method: reqwest::Method,
|
||||
path: &str,
|
||||
body: Option<&[SnapshotEntry]>,
|
||||
answer: &str,
|
||||
) -> Result<T, DirError> {
|
||||
let (base, token) = target(&ctx.cfg()).ok_or(DirError::NotConfigured)?;
|
||||
let mut req =
|
||||
@@ -81,15 +82,19 @@ async fn call<T: DeserializeOwned>(
|
||||
if let Some(tp) = ipx_directory::otel::traceparent() {
|
||||
req = req.header("traceparent", tp);
|
||||
}
|
||||
// A snapshot is about 100 KB of JSON, sent gzipped; the directory unpacks it (#253).
|
||||
// Protobuf both ways (#465), where the answer has a message: a smaller body to read.
|
||||
if !answer.is_empty() {
|
||||
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 json = serde_json::to_vec(b).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
let pb = ipx_wire::encode("directory.Snapshot", &b).map_err(DirError::Unreachable)?;
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
gz.write_all(&json).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
gz.write_all(&pb).map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
let packed = gz.finish().map_err(|e| DirError::Unreachable(format!("{e:#}")))?;
|
||||
req = req
|
||||
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||||
.header(reqwest::header::CONTENT_TYPE, ipx_wire::PROTOBUF)
|
||||
.header(reqwest::header::CONTENT_ENCODING, "gzip")
|
||||
.body(packed);
|
||||
}
|
||||
@@ -104,9 +109,17 @@ async fn call<T: DeserializeOwned>(
|
||||
.unwrap_or_default();
|
||||
return Err(DirError::Refused(status.as_u16(), msg));
|
||||
}
|
||||
let protobuf = resp
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.is_some_and(|v| v.as_bytes().starts_with(ipx_wire::PROTOBUF.as_bytes()));
|
||||
// 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}")));
|
||||
}
|
||||
serde_json::from_slice(if body.is_empty() { b"null" } else { &body })
|
||||
.map_err(|e| DirError::Unreachable(format!("its answer did not read: {e:#}")))
|
||||
}
|
||||
@@ -116,23 +129,24 @@ fn seg(s: &str) -> percent_encoding::PercentEncode<'_> {
|
||||
}
|
||||
|
||||
pub async fn me(ctx: &Ctx) -> Result<Me, DirError> {
|
||||
call(ctx, reqwest::Method::GET, "/v1/me", None).await
|
||||
call(ctx, reqwest::Method::GET, "/v1/me", None, "directory.Me").await
|
||||
}
|
||||
|
||||
pub async fn feeds(ctx: &Ctx) -> Result<Vec<Listing>, DirError> {
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None).await?;
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/feeds", None, "directory.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).await?;
|
||||
let got: Vec<Listing> = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None, "directory.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).await?;
|
||||
let got: FeedPage =
|
||||
call(ctx, reqwest::Method::GET, &format!("/v1/feeds/{}", seg(id)), None, "directory.FeedPage").await?;
|
||||
note_art(std::iter::once(&got.listing));
|
||||
Ok(got)
|
||||
}
|
||||
@@ -157,29 +171,29 @@ 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, "").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, "").await
|
||||
}
|
||||
|
||||
pub async fn blocked(ctx: &Ctx) -> Result<Vec<ipx_directory::Blocked>, DirError> {
|
||||
call(ctx, reqwest::Method::GET, "/v1/blocked", None).await
|
||||
call(ctx, reqwest::Method::GET, "/v1/blocked", None, "directory.BlockedList").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, "").await
|
||||
}
|
||||
|
||||
pub async fn instances(ctx: &Ctx) -> Result<Vec<ipx_directory::Instance>, DirError> {
|
||||
call(ctx, reqwest::Method::GET, "/v1/instances", None).await
|
||||
call(ctx, reqwest::Method::GET, "/v1/instances", None, "directory.Instances").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, "").await
|
||||
}
|
||||
|
||||
/// Has the snapshot sent again now, changed or not.
|
||||
@@ -234,7 +248,8 @@ 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)).await?;
|
||||
let r: SnapshotResult =
|
||||
call(ctx, reqwest::Method::POST, "/v1/snapshot", Some(entries), "directory.SnapshotResult").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");
|
||||
|
||||
@@ -76,7 +76,10 @@ pub async fn share(
|
||||
.post(format!("{base}/v1/shares"))
|
||||
.bearer_auth(token)
|
||||
.timeout(Duration::from_secs(15))
|
||||
.json(&episode);
|
||||
// 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)?);
|
||||
// Its spans join this request's trace.
|
||||
if let Some(tp) = ipx_directory::otel::traceparent() {
|
||||
req = req.header("traceparent", tp);
|
||||
@@ -87,7 +90,8 @@ pub async fn share(
|
||||
let msg = resp.json::<serde_json::Value>().await.ok().and_then(|v| v["error"].as_str().map(str::to_owned));
|
||||
return Err(NoLink::Failed(format!("ipx-play answered {status}: {}", msg.unwrap_or_default())));
|
||||
}
|
||||
resp.json().await.map_err(|e| NoLink::Failed(format!("ipx-play's answer did not read: {e:#}")))
|
||||
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}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -48,6 +48,49 @@ pub struct WebState {
|
||||
pub wrong: Wrong,
|
||||
}
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON: what its body is and what it answers.
|
||||
const WIRE: ipx_wire::Routes = &[
|
||||
("POST", "/api/login", "ipx.Credentials", "ipx.SignedIn"),
|
||||
("GET", "/api/me", "", "ipx.Me"),
|
||||
("PATCH", "/api/me", "ipx.MePatch", ""),
|
||||
("GET", "/api/tokens", "", "ipx.ApiTokens"),
|
||||
("POST", "/api/tokens", "ipx.NewToken", "ipx.MadeToken"),
|
||||
("POST", "/api/push/devices", "ipx.PushDevice", ""),
|
||||
("GET", "/api/feeds", "", "ipx.FeedRows"),
|
||||
("POST", "/api/feeds", "ipx.NewFeed", "ipx.AddedFeed"),
|
||||
("PATCH", "/api/feeds/{id}", "ipx.FeedPatch", ""),
|
||||
("GET", "/api/feeds/{id}/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/signals", "", "ipx.SignalRows"),
|
||||
("POST", "/api/signals", "ipx.SignalBody", "ipx.SignalId"),
|
||||
("POST", "/api/signals/icon", "ipx.IconAsk", "ipx.Icon"),
|
||||
("PATCH", "/api/signals/{id}", "ipx.SignalBody", ""),
|
||||
("GET", "/api/signals/{id}/entries", "", "ipx.EntryPage"),
|
||||
("GET", "/api/entries/{feed_id}/{guid}", "", "ipx.EntryRow"),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/flags", "ipx.Flags", "ipx.FeedRow"),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/position", "ipx.Position", ""),
|
||||
("POST", "/api/entries/{feed_id}/{guid}/share", "ipx.ShareBody", "ipx.ShareLink"),
|
||||
("POST", "/api/feeds/{id}/read-all", "", "ipx.Marked"),
|
||||
("POST", "/api/read-all", "", "ipx.Marked"),
|
||||
("POST", "/api/feeds/{id}/download-latest", "ipx.HowMany", "ipx.Queued"),
|
||||
("POST", "/api/fetch", "ipx.FetchBody", ""),
|
||||
("POST", "/api/opml", "ipx.OpmlBody", "ipx.OpmlImported"),
|
||||
("GET", "/api/settings", "", "ipx.Settings"),
|
||||
("PATCH", "/api/settings", "ipx.SettingsPatch", ""),
|
||||
("GET", "/api/directory-status", "", "ipx.DirStatus"),
|
||||
("GET", "/api/status", "", "ipx.Status"),
|
||||
("GET", "/api/popular", "", "ipx.PopularRows"),
|
||||
("GET", "/api/directory", "", "ipx.PopularRows"),
|
||||
("GET", "/api/directory/{id}", "", "ipx.Listed"),
|
||||
("GET", "/api/directory-admin", "", "ipx.DirAdmin"),
|
||||
("POST", "/api/popular/{id}", "", "ipx.FeedId"),
|
||||
("GET", "/api/users", "", "ipx.Accounts"),
|
||||
("POST", "/api/users", "ipx.NewUser", ""),
|
||||
("PATCH", "/api/users/{id}", "ipx.UserPatch", ""),
|
||||
("GET", "/api/logs", "", "ipx.LogPage"),
|
||||
("POST", "/api/client", "ipx.ClientEvent", ""),
|
||||
];
|
||||
|
||||
pub fn router(state: WebState) -> Router {
|
||||
Router::new()
|
||||
.route("/api/me", get(me).patch(patch_me))
|
||||
@@ -102,6 +145,7 @@ pub fn router(state: WebState) -> Router {
|
||||
// Signing in cannot require being signed in, so these sit outside the auth layer.
|
||||
.route("/api/login", post(login))
|
||||
.route("/api/login-check", get(login_check))
|
||||
.route_layer(middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.route_layer(middleware::from_fn(name_span))
|
||||
.layer(middleware::from_fn(cross_site_refused))
|
||||
.layer(middleware::from_fn(access_log))
|
||||
|
||||
@@ -12,6 +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).
|
||||
- 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).
|
||||
|
||||
@@ -21,6 +21,7 @@ clap.workspace = true
|
||||
# log lines as ipx and the directory.
|
||||
ipx-directory.workspace = true
|
||||
ipx-feed.workspace = true
|
||||
ipx-wire.workspace = true
|
||||
opentelemetry.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
reqwest.workspace = true
|
||||
|
||||
@@ -108,10 +108,14 @@ pub struct Play {
|
||||
|
||||
type St = Arc<Play>;
|
||||
|
||||
/// Each route's protobuf messages (#465), beside its JSON.
|
||||
const WIRE: ipx_wire::Routes = &[("POST", "/v1/shares", "play.Episode", "play.Shared")];
|
||||
|
||||
pub fn router(play: Play) -> Router {
|
||||
let st = Arc::new(play);
|
||||
let api = Router::new()
|
||||
.route("/v1/shares", post(share))
|
||||
.route_layer(axum::middleware::from_fn_with_state(WIRE, ipx_wire::negotiate))
|
||||
.layer(axum::middleware::from_fn_with_state(st.clone(), authenticate));
|
||||
Router::new()
|
||||
.route("/healthz", get(healthz))
|
||||
|
||||
24
crates/wire/Cargo.toml
Normal file
24
crates/wire/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "ipx-wire"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
prost.workspace = true
|
||||
prost-reflect.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
prost.workspace = true
|
||||
protox.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
tower.workspace = true
|
||||
14
crates/wire/build.rs
Normal file
14
crates/wire/build.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
//! Compiles the `.proto` files into one descriptor set the crate reads at run time. protox is a
|
||||
//! compiler in Rust, so building needs no `protoc` on the host or in the image.
|
||||
|
||||
use prost::Message as _;
|
||||
|
||||
fn main() {
|
||||
let files = ["proto/ipx.proto", "proto/directory.proto", "proto/play.proto"];
|
||||
for f in files {
|
||||
println!("cargo:rerun-if-changed={f}");
|
||||
}
|
||||
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");
|
||||
}
|
||||
94
crates/wire/proto/directory.proto
Normal file
94
crates/wire/proto/directory.proto
Normal file
@@ -0,0 +1,94 @@
|
||||
// ipx-directory's API under /v1 (crates/directory/src/wire.rs), each message named after the Rust
|
||||
// struct it mirrors. A field added there goes here too; debug builds refuse an answer with a field
|
||||
// missing here. A message whose only field is `repeated items` is a JSON array.
|
||||
syntax = "proto3";
|
||||
package directory;
|
||||
|
||||
// GET /v1/me.
|
||||
message Me {
|
||||
string name = 1;
|
||||
// "ro", "rw" or "rwa".
|
||||
string access = 2;
|
||||
}
|
||||
|
||||
message Listing {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string category = 5;
|
||||
optional string subcategory = 6;
|
||||
bool podcast = 7;
|
||||
int64 subscribers = 8;
|
||||
}
|
||||
|
||||
// GET /v1/feeds, GET /v1/popular.
|
||||
message Listings {
|
||||
repeated Listing items = 1;
|
||||
}
|
||||
|
||||
message Item {
|
||||
string guid = 1;
|
||||
optional string title = 2;
|
||||
optional string link = 3;
|
||||
optional int64 published = 4;
|
||||
optional int64 duration = 5;
|
||||
optional string description = 6;
|
||||
}
|
||||
|
||||
// GET /v1/feeds/{id}, POST /v1/feeds/{id}/refresh: a Listing's fields and these.
|
||||
message FeedPage {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string category = 5;
|
||||
optional string subcategory = 6;
|
||||
bool podcast = 7;
|
||||
int64 subscribers = 8;
|
||||
optional string description = 9;
|
||||
optional string failing = 10;
|
||||
repeated Item items = 11;
|
||||
}
|
||||
|
||||
message SnapshotEntry {
|
||||
string url = 1;
|
||||
int64 subscribers = 2;
|
||||
optional string category = 3;
|
||||
}
|
||||
|
||||
// POST /v1/snapshot, the body.
|
||||
message Snapshot {
|
||||
repeated SnapshotEntry items = 1;
|
||||
}
|
||||
|
||||
// POST /v1/snapshot, the answer.
|
||||
message SnapshotResult {
|
||||
uint64 accepted = 1;
|
||||
uint64 refused_private = 2;
|
||||
uint64 refused_blocked = 3;
|
||||
uint64 refused_invalid = 4;
|
||||
}
|
||||
|
||||
message Instance {
|
||||
string name = 1;
|
||||
int64 feeds = 2;
|
||||
int64 subscribers = 3;
|
||||
}
|
||||
|
||||
// GET /v1/instances.
|
||||
message Instances {
|
||||
repeated Instance items = 1;
|
||||
}
|
||||
|
||||
message Blocked {
|
||||
string id = 1;
|
||||
optional string url = 2;
|
||||
optional string title = 3;
|
||||
int64 at = 4;
|
||||
}
|
||||
|
||||
// GET /v1/blocked.
|
||||
message BlockedList {
|
||||
repeated Blocked items = 1;
|
||||
}
|
||||
494
crates/wire/proto/ipx.proto
Normal file
494
crates/wire/proto/ipx.proto
Normal file
@@ -0,0 +1,494 @@
|
||||
// ipx's API under /api (crates/ipx/src/web.rs), the same answers its JSON gives, each message named
|
||||
// after the Rust struct it mirrors where there is one (web/src/types.ts mirrors the same). A field
|
||||
// added in Rust goes here too: debug builds refuse an answer with a field missing here.
|
||||
//
|
||||
// How the JSON maps (crates/wire/src/lib.rs):
|
||||
// * A field name is the JSON key.
|
||||
// * A Rust Option is `optional`, or a message; so is a field with a serde default, which an absent
|
||||
// field must leave to Rust.
|
||||
// * A message whose only field is `repeated ... items` is a JSON array, top-level or as a field.
|
||||
// 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.
|
||||
syntax = "proto3";
|
||||
package ipx;
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
import "directory.proto";
|
||||
|
||||
// A list of words, as an Option<Vec<String>> in a body: absent, or this.
|
||||
message Words {
|
||||
repeated string items = 1;
|
||||
}
|
||||
|
||||
// ---- signing in, and you ----
|
||||
|
||||
// POST /api/login, the body.
|
||||
message Credentials {
|
||||
string name = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// POST /api/login, the answer.
|
||||
message SignedIn {
|
||||
string name = 1;
|
||||
bool admin = 2;
|
||||
}
|
||||
|
||||
message Theme {
|
||||
string name = 1;
|
||||
string mode = 2;
|
||||
}
|
||||
|
||||
// GET /api/me.
|
||||
message Me {
|
||||
string name = 1;
|
||||
bool admin = 2;
|
||||
optional string sign_out = 3;
|
||||
repeated string blocked = 4;
|
||||
int64 deadair_saved = 5;
|
||||
optional Theme theme = 6;
|
||||
string version = 7;
|
||||
bool typesafe_key_set = 8;
|
||||
// "server" or "own".
|
||||
string signals = 9;
|
||||
uint64 signal_days = 10;
|
||||
}
|
||||
|
||||
// PATCH /api/me, the body.
|
||||
message MePatch {
|
||||
Words blocked = 1;
|
||||
google.protobuf.Value typesafe_key = 2;
|
||||
}
|
||||
|
||||
message ApiToken {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
int64 created = 3;
|
||||
optional int64 last_used = 4;
|
||||
}
|
||||
|
||||
// GET /api/tokens.
|
||||
message ApiTokens {
|
||||
repeated ApiToken items = 1;
|
||||
}
|
||||
|
||||
// POST /api/tokens, the body.
|
||||
message NewToken {
|
||||
string name = 1;
|
||||
}
|
||||
|
||||
// POST /api/tokens, the answer: the only time the token is shown.
|
||||
message MadeToken {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
string token = 3;
|
||||
}
|
||||
|
||||
// POST /api/push/devices, the body.
|
||||
message PushDevice {
|
||||
string token = 1;
|
||||
optional bool sandbox = 2;
|
||||
}
|
||||
|
||||
// ---- feeds ----
|
||||
|
||||
message FailingRow {
|
||||
string reason = 1;
|
||||
optional string new_url = 2;
|
||||
}
|
||||
|
||||
message FeedRow {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
optional string title = 3;
|
||||
optional string image = 4;
|
||||
optional string folder = 5;
|
||||
optional string category = 6;
|
||||
optional string feed_category = 7;
|
||||
repeated string keywords = 8;
|
||||
repeated string blocked = 9;
|
||||
bool deadair = 10;
|
||||
int64 deadair_pause = 11;
|
||||
bool allow_explicit = 12;
|
||||
bool auto_download = 13;
|
||||
optional uint64 max_new_per_check = 14;
|
||||
optional string group = 15;
|
||||
bool orphaned = 16;
|
||||
bool managed = 17;
|
||||
optional string schedule = 18;
|
||||
optional uint64 schedule_mins = 19;
|
||||
uint64 every_mins = 20;
|
||||
optional int64 last_checked = 21;
|
||||
optional int64 next_check = 22;
|
||||
optional string last_error = 23;
|
||||
optional FailingRow failing = 24;
|
||||
int64 entries = 25;
|
||||
int64 downloaded = 26;
|
||||
int64 unread = 27;
|
||||
int64 subscribers = 28;
|
||||
bool pinned = 29;
|
||||
bool kept = 30;
|
||||
bool hide_from_all = 31;
|
||||
bool hide_from_signals = 32;
|
||||
bool private = 33;
|
||||
bool private_by_address = 34;
|
||||
}
|
||||
|
||||
// GET /api/feeds.
|
||||
message FeedRows {
|
||||
repeated FeedRow items = 1;
|
||||
}
|
||||
|
||||
// POST /api/feeds, the body.
|
||||
message NewFeed {
|
||||
string url = 1;
|
||||
optional string folder = 2;
|
||||
repeated string keywords = 3;
|
||||
optional bool allow_explicit = 4;
|
||||
}
|
||||
|
||||
// POST /api/feeds, the answer.
|
||||
message AddedFeed {
|
||||
string id = 1;
|
||||
bool existing = 2;
|
||||
}
|
||||
|
||||
// PATCH /api/feeds/{id}, the body: what is there changes, what is not is left.
|
||||
message FeedPatch {
|
||||
optional string url = 1;
|
||||
google.protobuf.Value schedule = 2;
|
||||
google.protobuf.Value folder = 3;
|
||||
google.protobuf.Value category = 4;
|
||||
Words keywords = 5;
|
||||
Words blocked = 6;
|
||||
optional bool allow_explicit = 7;
|
||||
optional bool auto_download = 8;
|
||||
google.protobuf.Value max_new_per_check = 9;
|
||||
optional bool pinned = 10;
|
||||
optional bool kept = 11;
|
||||
optional bool hide_from_all = 12;
|
||||
optional bool hide_from_signals = 13;
|
||||
google.protobuf.Value deadair = 14;
|
||||
optional int64 deadair_pause = 15;
|
||||
optional bool private = 16;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/download-latest, the body.
|
||||
message HowMany {
|
||||
optional int64 count = 1;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/download-latest, the answer.
|
||||
message Queued {
|
||||
uint64 queued = 1;
|
||||
}
|
||||
|
||||
// POST /api/feeds/{id}/read-all, POST /api/read-all.
|
||||
message Marked {
|
||||
uint64 marked = 1;
|
||||
}
|
||||
|
||||
// POST /api/fetch, the body.
|
||||
message FetchBody {
|
||||
optional string feed = 1;
|
||||
optional bool force = 2;
|
||||
}
|
||||
|
||||
// POST /api/opml, the body.
|
||||
message OpmlBody {
|
||||
string xml = 1;
|
||||
}
|
||||
|
||||
// POST /api/opml, the answer.
|
||||
message OpmlImported {
|
||||
uint64 added = 1;
|
||||
uint64 already = 2;
|
||||
}
|
||||
|
||||
// ---- items ----
|
||||
|
||||
message EncRow {
|
||||
int64 id = 1;
|
||||
optional int64 deadair = 2;
|
||||
optional bool deadair_pending = 3;
|
||||
string feed_id = 4;
|
||||
string guid = 5;
|
||||
string url = 6;
|
||||
optional string mime = 7;
|
||||
optional int64 length = 8;
|
||||
optional string path = 9;
|
||||
string state = 10;
|
||||
optional string last_error = 11;
|
||||
}
|
||||
|
||||
// GET /api/entries/{feed_id}/{guid}.
|
||||
message EntryRow {
|
||||
string guid = 1;
|
||||
string feed_id = 2;
|
||||
optional string title = 3;
|
||||
optional string link = 4;
|
||||
optional int64 published = 5;
|
||||
optional string description = 6;
|
||||
optional string markdown = 7;
|
||||
optional string markdown_html = 8;
|
||||
bool read = 9;
|
||||
bool flagged = 10;
|
||||
optional string image = 11;
|
||||
optional int64 duration = 12;
|
||||
optional int64 episode = 13;
|
||||
optional int64 season = 14;
|
||||
int64 position = 15;
|
||||
repeated EncRow enclosures = 16;
|
||||
}
|
||||
|
||||
// GET /api/entries, /api/feeds/{id}/entries, /api/signals/{id}/entries.
|
||||
message EntryPage {
|
||||
int64 total = 1;
|
||||
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.
|
||||
message Flags {
|
||||
optional bool read = 1;
|
||||
optional bool flagged = 2;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/position, the body.
|
||||
message Position {
|
||||
int64 secs = 1;
|
||||
optional int64 duration = 2;
|
||||
optional int64 deadair = 3;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/share, the body.
|
||||
message ShareBody {
|
||||
optional int64 enc = 1;
|
||||
}
|
||||
|
||||
// POST /api/entries/{feed_id}/{guid}/share, the answer.
|
||||
message ShareLink {
|
||||
optional string url = 1;
|
||||
optional string why = 2;
|
||||
}
|
||||
|
||||
// ---- Signals ----
|
||||
|
||||
message SignalRow {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
repeated string keywords = 3;
|
||||
optional string description = 4;
|
||||
optional string icon = 5;
|
||||
int64 items = 6;
|
||||
int64 unread = 7;
|
||||
}
|
||||
|
||||
// GET /api/signals.
|
||||
message SignalRows {
|
||||
repeated SignalRow items = 1;
|
||||
}
|
||||
|
||||
// POST /api/signals and PATCH /api/signals/{id}, the body.
|
||||
message SignalBody {
|
||||
optional string name = 1;
|
||||
Words keywords = 2;
|
||||
google.protobuf.Value description = 3;
|
||||
google.protobuf.Value icon = 4;
|
||||
}
|
||||
|
||||
// POST /api/signals, the answer.
|
||||
message SignalId {
|
||||
int64 id = 1;
|
||||
}
|
||||
|
||||
// POST /api/signals/icon, the body. Each candidate is [icon, label].
|
||||
message IconAsk {
|
||||
string name = 1;
|
||||
repeated string keywords = 2;
|
||||
optional string description = 3;
|
||||
repeated google.protobuf.ListValue candidates = 4;
|
||||
}
|
||||
|
||||
// POST /api/signals/icon, the answer.
|
||||
message Icon {
|
||||
string icon = 1;
|
||||
}
|
||||
|
||||
// ---- the directory ----
|
||||
|
||||
message PopularRow {
|
||||
string id = 1;
|
||||
optional string title = 2;
|
||||
optional string image = 3;
|
||||
int64 subscribers = 4;
|
||||
bool subscribed = 5;
|
||||
optional string feed = 6;
|
||||
optional string category = 7;
|
||||
optional string subcategory = 8;
|
||||
bool podcast = 9;
|
||||
}
|
||||
|
||||
// GET /api/popular, GET /api/directory.
|
||||
message PopularRows {
|
||||
repeated PopularRow items = 1;
|
||||
}
|
||||
|
||||
message ListedItem {
|
||||
string guid = 1;
|
||||
optional string title = 2;
|
||||
optional string link = 3;
|
||||
optional int64 published = 4;
|
||||
optional int64 duration = 5;
|
||||
optional string description = 6;
|
||||
}
|
||||
|
||||
// GET /api/directory/{id}.
|
||||
message Listed {
|
||||
optional string description = 1;
|
||||
optional string failing = 2;
|
||||
repeated ListedItem items = 3;
|
||||
bool can_admin = 4;
|
||||
}
|
||||
|
||||
// POST /api/popular/{id}, the answer.
|
||||
message FeedId {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message BlockedRow {
|
||||
string id = 1;
|
||||
optional string title = 2;
|
||||
int64 at = 3;
|
||||
}
|
||||
|
||||
// GET /api/directory-admin.
|
||||
message DirAdmin {
|
||||
repeated directory.Instance instances = 1;
|
||||
repeated BlockedRow blocked = 2;
|
||||
}
|
||||
|
||||
// When the snapshot last went: a SnapshotResult's fields when it was taken, the error when not.
|
||||
message Shared {
|
||||
int64 at = 1;
|
||||
optional uint64 accepted = 2;
|
||||
optional uint64 refused_private = 3;
|
||||
optional uint64 refused_blocked = 4;
|
||||
optional uint64 refused_invalid = 5;
|
||||
optional string error = 6;
|
||||
}
|
||||
|
||||
// GET /api/directory-status.
|
||||
message DirStatus {
|
||||
bool configured = 1;
|
||||
optional string name = 2;
|
||||
optional string access = 3;
|
||||
optional string error = 4;
|
||||
optional Shared shared = 5;
|
||||
}
|
||||
|
||||
// ---- the server ----
|
||||
|
||||
// GET /api/status.
|
||||
message Status {
|
||||
uint64 feeds = 1;
|
||||
int64 pending = 2;
|
||||
int64 downloaded = 3;
|
||||
string version = 4;
|
||||
}
|
||||
|
||||
// GET /api/settings.
|
||||
message Settings {
|
||||
string schedule = 1;
|
||||
uint64 every_mins = 2;
|
||||
uint64 max_new_per_check = 3;
|
||||
repeated string media_types = 4;
|
||||
string download_dir = 5;
|
||||
double max_total_gb = 6;
|
||||
uint64 max_age_days = 7;
|
||||
uint64 art_cache_mb = 8;
|
||||
string directory_url = 9;
|
||||
bool directory_token_set = 10;
|
||||
bool directory_share = 11;
|
||||
string play_url = 12;
|
||||
bool play_token_set = 13;
|
||||
bool signals_on_server = 14;
|
||||
uint64 signal_days = 15;
|
||||
bool typesafe_server_key = 16;
|
||||
}
|
||||
|
||||
// PATCH /api/settings, the body.
|
||||
message SettingsPatch {
|
||||
optional string schedule = 1;
|
||||
optional uint64 max_new_per_check = 2;
|
||||
Words media_types = 3;
|
||||
optional double max_total_gb = 4;
|
||||
optional uint64 max_age_days = 5;
|
||||
optional uint64 art_cache_mb = 6;
|
||||
optional string directory_url = 7;
|
||||
optional string directory_token = 8;
|
||||
optional bool directory_share = 9;
|
||||
optional string play_url = 10;
|
||||
optional string play_token = 11;
|
||||
optional bool signals_on_server = 12;
|
||||
optional uint64 signal_days = 13;
|
||||
}
|
||||
|
||||
message Account {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
bool admin = 3;
|
||||
bool password = 4;
|
||||
optional int64 created = 5;
|
||||
optional int64 last_login = 6;
|
||||
}
|
||||
|
||||
// GET /api/users.
|
||||
message Accounts {
|
||||
repeated Account items = 1;
|
||||
}
|
||||
|
||||
// POST /api/users, the body.
|
||||
message NewUser {
|
||||
string name = 1;
|
||||
optional string password = 2;
|
||||
optional bool admin = 3;
|
||||
}
|
||||
|
||||
// PATCH /api/users/{id}, the body.
|
||||
message UserPatch {
|
||||
bool admin = 1;
|
||||
}
|
||||
|
||||
message LogLine {
|
||||
uint64 seq = 1;
|
||||
int64 ts = 2;
|
||||
string level = 3;
|
||||
string target = 4;
|
||||
string msg = 5;
|
||||
}
|
||||
|
||||
// GET /api/logs.
|
||||
message LogPage {
|
||||
repeated LogLine lines = 1;
|
||||
uint64 latest = 2;
|
||||
}
|
||||
|
||||
// POST /api/client, the body.
|
||||
message ClientEvent {
|
||||
string ev = 1;
|
||||
optional string msg = 2;
|
||||
optional string src = 3;
|
||||
optional uint32 line = 4;
|
||||
optional string feed = 5;
|
||||
optional int64 enclosure = 6;
|
||||
optional bool deadair = 7;
|
||||
optional uint64 ms = 8;
|
||||
optional string filter = 9;
|
||||
optional string trace = 10;
|
||||
optional string span = 11;
|
||||
optional uint64 start = 12;
|
||||
optional string state = 13;
|
||||
}
|
||||
25
crates/wire/proto/play.proto
Normal file
25
crates/wire/proto/play.proto
Normal file
@@ -0,0 +1,25 @@
|
||||
// ipx-play's API (crates/play/src/lib.rs), each message named after the Rust struct it mirrors.
|
||||
// A field added there goes here too; debug builds refuse an answer with a field missing here.
|
||||
syntax = "proto3";
|
||||
package play;
|
||||
|
||||
// POST /v1/shares, the body.
|
||||
message Episode {
|
||||
string feed_url = 1;
|
||||
string guid = 2;
|
||||
optional string feed_title = 3;
|
||||
optional string feed_image = 4;
|
||||
optional string title = 5;
|
||||
optional string description = 6;
|
||||
optional string link = 7;
|
||||
optional int64 published = 8;
|
||||
optional int64 duration = 9;
|
||||
string audio_url = 10;
|
||||
optional string mime = 11;
|
||||
}
|
||||
|
||||
// POST /v1/shares, the answer.
|
||||
message Shared {
|
||||
string id = 1;
|
||||
string url = 2;
|
||||
}
|
||||
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