diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 654af1e..7001303 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -2,15 +2,15 @@ # Refuses a commit whose Rust is not as rustfmt writes it, or that clippy warns about. Clippy only # checks and never links, so it is light beside a test build (CLAUDE.md, Tests). It checks the # crates the commit touches and those built on them, not the workspace: ipx uses ipx-play and -# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed. A commit to the page alone runs nothing here. +# ipx-directory, ipx-play uses ipx-directory, and all use ipx-feed and ipx-wire. A commit to the page alone runs nothing here. staged=$(git diff --cached --name-only --diff-filter=ACMD) echo "$staged" | grep -q -e '\.rs$' -e 'Cargo\.toml$' -e '^Cargo\.lock$' || exit 0 if ! cargo fmt --all --check >/dev/null 2>&1; then echo "pre-commit: the Rust is not formatted; run cargo fmt --all" >&2 exit 1 fi -if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/'; then - pkgs="ipx-feed ipx-directory ipx-play ipx ipx-tui" +if echo "$staged" | grep -q -e '^Cargo\.toml$' -e '^Cargo\.lock$' -e '^crates/feed/' -e '^crates/wire/'; then + pkgs="ipx-feed ipx-wire ipx-directory ipx-play ipx ipx-tui" elif echo "$staged" | grep -q '^crates/tui/'; then pkgs="ipx-tui" elif echo "$staged" | grep -q '^crates/directory/'; then diff --git a/CLAUDE.md b/CLAUDE.md index b156c01..2cfba83 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -250,7 +250,7 @@ session was stopped. So: * Look at the load before and after each (`cat /proc/loadavg`). Above about 24, Tower's twelve threads twice over, wait for it to come down before starting another. * Test only what the change is in. ipx uses ipx-play and ipx-directory, ipx-play uses - ipx-directory, and all use ipx-feed, so: + ipx-directory, and all use ipx-feed and ipx-wire, so: | changed | run | |---|---| @@ -260,7 +260,8 @@ session was stopped. So: | `crates/play/` | `cargo test -p ipx-play`, then `-p ipx` | | `crates/feed/` | `cargo test -p ipx-feed`, then `-p ipx-directory`, `-p ipx-play`, then `-p ipx` | | `crates/tui/` | `cargo test -p ipx-tui`; it uses only the API, none of the other crates | - | `Cargo.toml`, `Cargo.lock` | all five, one at a time | + | `crates/wire/` | `cargo test -p ipx-wire`, then `-p ipx-play`, `-p ipx-directory`, then `-p ipx`; the browser suite, whose debug builds check every answer against the `.proto` | + | `Cargo.toml`, `Cargo.lock` | all six, one at a time | The pre-commit hook's clippy follows the same table. The whole browser suite once, at the end of a change to the page or the API; never `cargo test` for the workspace in one command. diff --git a/Cargo.lock b/Cargo.lock index c369726..cb65167 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -377,6 +377,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "beef" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -1984,6 +1990,7 @@ dependencies = [ "ipx-directory", "ipx-feed", "ipx-play", + "ipx-wire", "jsonwebtoken", "librqbit", "opentelemetry", @@ -2016,6 +2023,7 @@ dependencies = [ "flate2", "futures-util", "ipx-feed", + "ipx-wire", "mimalloc", "opentelemetry", "opentelemetry-otlp", @@ -2068,6 +2076,7 @@ dependencies = [ "clap", "ipx-directory", "ipx-feed", + "ipx-wire", "opentelemetry", "percent-encoding", "reqwest", @@ -2097,6 +2106,21 @@ dependencies = [ "serde_json", ] +[[package]] +name = "ipx-wire" +version = "0.0.0" +dependencies = [ + "axum", + "prost", + "prost-reflect", + "protox", + "serde", + "serde_json", + "tokio", + "tower", + "tracing", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -2688,6 +2712,72 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "logos" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154" +dependencies = [ + "logos-derive 0.15.1", +] + +[[package]] +name = "logos" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f" +dependencies = [ + "logos-derive 0.16.1", +] + +[[package]] +name = "logos-codegen" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c" +dependencies = [ + "beef", + "fnv", + "lazy_static", + "proc-macro2", + "quote", + "regex-syntax", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "logos-codegen" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970" +dependencies = [ + "fnv", + "proc-macro2", + "quote", + "regex-automata", + "regex-syntax", + "syn 2.0.119", +] + +[[package]] +name = "logos-derive" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470" +dependencies = [ + "logos-codegen 0.15.1", +] + +[[package]] +name = "logos-derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31" +dependencies = [ + "logos-codegen 0.16.1", +] + [[package]] name = "lru" version = "0.18.5" @@ -2790,6 +2880,28 @@ dependencies = [ "rapidhash", ] +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width 0.1.14", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "mimalloc" version = "0.1.52" @@ -3115,6 +3227,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + [[package]] name = "ordered-float" version = "4.6.0" @@ -3369,6 +3490,57 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prost-reflect" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1" +dependencies = [ + "base64 0.22.1", + "logos 0.16.1", + "miette", + "prost", + "prost-types", + "serde", + "serde-value", +] + +[[package]] +name = "prost-types" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +dependencies = [ + "prost", +] + +[[package]] +name = "protox" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1" +dependencies = [ + "bytes", + "miette", + "prost", + "prost-reflect", + "prost-types", + "protox-parse", + "thiserror 2.0.20", +] + +[[package]] +name = "protox-parse" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366" +dependencies = [ + "logos 0.15.1", + "miette", + "prost-types", + "thiserror 2.0.20", +] + [[package]] name = "pulldown-cmark" version = "0.13.4" @@ -3631,7 +3803,7 @@ dependencies = [ "thiserror 2.0.20", "unicode-segmentation", "unicode-truncate", - "unicode-width", + "unicode-width 0.2.3", ] [[package]] @@ -3663,7 +3835,7 @@ dependencies = [ "strum", "time", "unicode-segmentation", - "unicode-width", + "unicode-width 0.2.3", ] [[package]] @@ -4083,7 +4255,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "546040c653a705e60ec65ecd3191a809603734bebbc225775916dea9ae409b31" dependencies = [ - "ordered-float", + "ordered-float 4.6.0", "sea-query-derive", "serde_json", ] @@ -4176,6 +4348,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -5260,9 +5442,15 @@ checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" dependencies = [ "itertools 0.14.0", "unicode-segmentation", - "unicode-width", + "unicode-width 0.2.3", ] +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + [[package]] name = "unicode-width" version = "0.2.3" diff --git a/Cargo.toml b/Cargo.toml index ad96d24..100cd85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play"] +members = ["crates/ipx", "crates/feed", "crates/directory", "crates/tui", "crates/play", "crates/wire"] resolver = "3" # Each service has its own version, in its own Cargo.toml (ipx, ipx-directory) or package.json @@ -15,6 +15,7 @@ unsafe_code = "forbid" ipx-feed = { path = "crates/feed" } ipx-directory = { path = "crates/directory" } ipx-play = { path = "crates/play" } +ipx-wire = { path = "crates/wire" } ammonia = "4.1.4" anyhow = "1.0.104" argon2 = "0.6.0" @@ -30,6 +31,9 @@ opentelemetry = { version = "0.33", default-features = false, features = ["trace opentelemetry-otlp = { version = "0.33", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client", "gzip-http"] } opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] } opml = "1.1.6" +prost = "0.14.4" +prost-reflect = { version = "0.16", features = ["serde"] } +protox = "0.9" pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] } mimalloc = "0.1.52" http = "1.5.0" diff --git a/Dockerfile b/Dockerfile index 7c5d5dd..7310929 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,7 +20,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/ RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \ --mount=type=cache,id=ipx-target,target=/src/target,sharing=locked \ touch crates/ipx/src/main.rs crates/ipx/src/lib.rs crates/feed/src/lib.rs \ - crates/directory/src/lib.rs \ + crates/directory/src/lib.rs crates/play/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \ && cargo build --release --locked -p ipx \ && cp target/release/ipxd /usr/local/bin/ipxd diff --git a/Dockerfile.directory b/Dockerfile.directory index ee7adb1..ae60278 100644 --- a/Dockerfile.directory +++ b/Dockerfile.directory @@ -14,7 +14,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/ # of its own: built with ipx's, the two would rebuild shared crates for each other's features. RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \ --mount=type=cache,id=ipx-directory-target,target=/src/target,sharing=locked \ - touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \ + touch crates/directory/src/main.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \ && cargo build --release --locked -p ipx-directory \ && cp target/release/ipx-directory /usr/local/bin/ipx-directory diff --git a/Dockerfile.play b/Dockerfile.play index 30a8870..f97a810 100644 --- a/Dockerfile.play +++ b/Dockerfile.play @@ -13,7 +13,7 @@ COPY web/logo.svg web/logo-dark.svg web/favicon.png ./web/ # Compiled crates kept in the builder between builds (#438), in a target of its own. RUN --mount=type=cache,id=ipx-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \ --mount=type=cache,id=ipx-play-target,target=/src/target,sharing=locked \ - touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs \ + touch crates/play/src/main.rs crates/play/src/lib.rs crates/directory/src/lib.rs crates/feed/src/lib.rs crates/wire/src/lib.rs crates/wire/proto/*.proto \ && cargo build --release --locked -p ipx-play \ && cp target/release/ipx-play /usr/local/bin/ipx-play diff --git a/crates/directory/CHANGELOG.md b/crates/directory/CHANGELOG.md index 4265f15..78c88c0 100644 --- a/crates/directory/CHANGELOG.md +++ b/crates/directory/CHANGELOG.md @@ -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). diff --git a/crates/directory/Cargo.toml b/crates/directory/Cargo.toml index 31e0382..4a7926d 100644 --- a/crates/directory/Cargo.toml +++ b/crates/directory/Cargo.toml @@ -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 diff --git a/crates/directory/src/api.rs b/crates/directory/src/api.rs index c134c69..9e10b7c 100644 --- a/crates/directory/src/api.rs +++ b/crates/directory/src/api.rs @@ -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)) diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index eb86206..3b8015c 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -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). diff --git a/crates/ipx/Cargo.toml b/crates/ipx/Cargo.toml index d379196..a4e232f 100644 --- a/crates/ipx/Cargo.toml +++ b/crates/ipx/Cargo.toml @@ -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 diff --git a/crates/ipx/src/directory.rs b/crates/ipx/src/directory.rs index 691cb72..779ad1b 100644 --- a/crates/ipx/src/directory.rs +++ b/crates/ipx/src/directory.rs @@ -73,6 +73,7 @@ async fn call( method: reqwest::Method, path: &str, body: Option<&[SnapshotEntry]>, + answer: &str, ) -> Result { let (base, token) = target(&ctx.cfg()).ok_or(DirError::NotConfigured)?; let mut req = @@ -81,15 +82,19 @@ async fn call( 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( .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 { - 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, DirError> { - let got: Vec = call(ctx, reqwest::Method::GET, "/v1/feeds", None).await?; + let got: Vec = call(ctx, reqwest::Method::GET, "/v1/feeds", None, "directory.Listings").await?; note_art(got.iter()); Ok(got) } pub async fn popular(ctx: &Ctx) -> Result, DirError> { - let got: Vec = call(ctx, reqwest::Method::GET, "/v1/popular?limit=10", None).await?; + let got: Vec = 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 { - 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 { - 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, 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, 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, DirError> { } pub async fn share(ctx: &Ctx, entries: &[SnapshotEntry]) -> Result { - 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"); diff --git a/crates/ipx/src/play.rs b/crates/ipx/src/play.rs index b7f1279..db061a7 100644 --- a/crates/ipx/src/play.rs +++ b/crates/ipx/src/play.rs @@ -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::().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)] diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 29b2ff9..d50e4bb 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -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)) diff --git a/crates/play/CHANGELOG.md b/crates/play/CHANGELOG.md index b8764b9..28a1673 100644 --- a/crates/play/CHANGELOG.md +++ b/crates/play/CHANGELOG.md @@ -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/`: 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 `: 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). diff --git a/crates/play/Cargo.toml b/crates/play/Cargo.toml index 96afe83..1b71022 100644 --- a/crates/play/Cargo.toml +++ b/crates/play/Cargo.toml @@ -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 diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index 4b32dce..d7404be 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -108,10 +108,14 @@ pub struct Play { type St = Arc; +/// 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)) diff --git a/crates/wire/Cargo.toml b/crates/wire/Cargo.toml new file mode 100644 index 0000000..b94fd72 --- /dev/null +++ b/crates/wire/Cargo.toml @@ -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 diff --git a/crates/wire/build.rs b/crates/wire/build.rs new file mode 100644 index 0000000..bb3878b --- /dev/null +++ b/crates/wire/build.rs @@ -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"); +} diff --git a/crates/wire/proto/directory.proto b/crates/wire/proto/directory.proto new file mode 100644 index 0000000..f2605fd --- /dev/null +++ b/crates/wire/proto/directory.proto @@ -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; +} diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto new file mode 100644 index 0000000..32e3934 --- /dev/null +++ b/crates/wire/proto/ipx.proto @@ -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 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> 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; +} diff --git a/crates/wire/proto/play.proto b/crates/wire/proto/play.proto new file mode 100644 index 0000000..a2a6075 --- /dev/null +++ b/crates/wire/proto/play.proto @@ -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; +} diff --git a/crates/wire/src/lib.rs b/crates/wire/src/lib.rs new file mode 100644 index 0000000..60503cc --- /dev/null +++ b/crates/wire/src/lib.rs @@ -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 = 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 { + 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, 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 { + 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(name: &str, value: &T) -> Result, 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(name: &str, bytes: &[u8]) -> Result { + 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, 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::::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| 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); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 0010f08..77b5a14 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -208,6 +208,15 @@ else a `401`. A feed's items and files (its entries, `download-latest`, `/api/en | `GET /api/logs` | admin-only; the ring buffer, with a sequence cursor | | `GET /media/{id}` | the file, with Range support so seeking works | +Every route that takes or answers JSON also speaks protobuf (#465): `Content-Type: +application/x-protobuf` for a body, `Accept: application/x-protobuf` for an answer, JSON +otherwise. The messages are in `crates/wire/proto/` (ipx, directory and play), and the handlers do +not know: `ipx_wire::negotiate`, a layer on each service's routes, converts the JSON at the edge +by its table of each route's messages (`WIRE` in `web.rs`, `api.rs` and play's `lib.rs`). A route +added to a router goes in its table. Debug builds convert every JSON answer strictly, so the cargo +tests and the browser suite answer `500` for a field missing from the `.proto` or a route missing +from the table. Errors stay JSON. + Show notes are feed-supplied HTML from an untrusted source, sanitized with `ammonia` server-side before they reach the page. diff --git a/docs/directory.md b/docs/directory.md index ade62fd..96b95c5 100644 --- a/docs/directory.md +++ b/docs/directory.md @@ -162,6 +162,9 @@ blocks it, so no snapshot brings it back. | `DELETE /v1/instances/{name}` | rwa | drop one token's snapshot, its counts with it | | `POST /v1/feeds/{id}/refresh` | rwa | fetch the feed now, answering with its page | +Each also speaks protobuf, by `Accept` and `Content-Type: application/x-protobuf` (#465), in the +messages of `crates/wire/proto/directory.proto`; ipx asks for it. + A feed's `id` is the first 64 bits of the SHA-256 of its address, normalised (scheme and host in lower case, no default port or fragment), so every server arrives at the same id. `subscribers` is the sum over every token's latest snapshot. A feed is listed once the directory has read it as