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

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

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

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

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

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

85
Cargo.lock generated
View File

@@ -1270,6 +1270,12 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
[[package]]
name = "fixedbitset"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -1298,6 +1304,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -1581,6 +1593,15 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -1589,7 +1610,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1600,7 +1621,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -2112,7 +2133,9 @@ version = "0.0.0"
dependencies = [
"axum",
"prost",
"prost-build",
"prost-reflect",
"prost-types",
"protox",
"serde",
"serde_json",
@@ -2949,6 +2972,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "multiversion"
version = "0.9.0"
@@ -3323,6 +3352,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap 2.14.2",
]
[[package]]
name = "pgvector"
version = "0.4.2"
@@ -3449,6 +3489,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -3477,6 +3527,25 @@ dependencies = [
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
dependencies = [
"heck 0.5.0",
"itertools 0.14.0",
"log",
"multimap",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn 2.0.119",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
@@ -4970,6 +5039,18 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "tendril"
version = "0.5.1"

View File

@@ -32,8 +32,10 @@ opentelemetry-otlp = { version = "0.33", default-features = false, features = ["
opentelemetry_sdk = { version = "0.33", default-features = false, features = ["trace"] }
opml = "1.1.6"
prost = "0.14.4"
prost-build = "0.14"
prost-reflect = { version = "0.16", features = ["serde"] }
protox = "0.9"
prost-types = "0.14"
pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] }
mimalloc = "0.1.52"
http = "1.5.0"

View File

@@ -5,6 +5,8 @@ WORKDIR /src
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY web ./web
# The protobuf messages the page reads its answers in (#470).
COPY crates/wire/proto ./crates/wire/proto
RUN node web/build.mts /dist
FROM caddy:2

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -215,7 +215,11 @@ not know: `ipx_wire::negotiate`, a layer on each service's routes, converts the
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. The iOS app's own calls go in protobuf (#469), from Swift
from the table. Errors stay JSON, and so does an answer of null. An answer goes into a struct
generated from its message (prost, in `crates/wire/build.rs`) and out as protobuf, named in its
`Content-Type` (`application/x-protobuf; messageType=ipx.FeedRows`); the page reads it with
`web/src/wire.ts`, a decoder of its own driven by the same `.proto` files, which `web/build.mts`
reads into the page and the offline worker (#470). The iOS app's own calls go in protobuf (#469), from Swift
generated off the same files: a change to them is `sh ios/scripts/proto.sh` too.
Show notes are feed-supplied HTML from an untrusted source, sanitized with `ammonia` server-side

View File

@@ -66,7 +66,7 @@ function makeContext(html: string, script: string, { media = false } = {}) {
localStorage: { getItem: () => null, setItem(){}, removeItem(){} },
navigator: { clipboard: undefined, sendBeacon(){}, mediaSession: undefined },
fetch: (url: unknown) => Promise.resolve({
ok: true, status: 200, text: () => Promise.resolve(''),
ok: true, status: 200, headers: new Headers({ 'Content-Type': 'application/json' }), text: () => Promise.resolve(''),
json: () => Promise.resolve(
String(url).includes('/api/settings')
? { schedule: 'every 60m', every_mins: 60, download_dir: '/tmp', max_total_gb: 0, max_age_days: 0 }

View File

@@ -239,7 +239,7 @@ test('Signals are everyone\'s on the server\'s key, and yours on your own once a
});
test('a tap is its trace\'s root span, reported with its ids once it has an answer (#376)', () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); traceAt = Date.now()`);
const [, trace, parent] = run('traceparent()').split('-');
assert.equal(parent, run('rootId'), 'requests hang from the tap');
@@ -253,7 +253,7 @@ test('a tap is its trace\'s root span, reported with its ids once it has an answ
});
test('a request begun long after a tap\'s last answer does not stretch the tap (#379)', async () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); traceAt = Date.now()`);
await run(`api('/api/a')`);
const answered = run('answeredAt');
@@ -266,7 +266,7 @@ test('a request begun long after a tap\'s last answer does not stretch the tap (
});
test('a tap ended over a minute after its last request reports once, without recursing (#378)', () => {
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204 }); }`);
run(`globalThis.sent = []; fetch = (url, o) => { sent.push([url, o]); return Promise.resolve({ ok: true, status: 204, headers: { get: () => null } }); }`);
run(`newTrace('pointerdown'); answeredAt = rootAt + 100; traceAt = Date.now() - 120_000`);
run('endTap()');
assert.equal(run(`sent.filter(([u, o]) => JSON.parse(o.body).ev === 'tap').length`), 1);
@@ -368,3 +368,24 @@ test('a file\'s box says where it is: the publisher, on its way, iPX, this devic
assert.equal(where({ state: 'reaped' }), 'On this device');
run('kept.clear()');
});
test('wireDecode reads protobuf into what the JSON would have been (#470)', () => {
// A browser has TextDecoder; the stub's sandbox does not, and the page makes one only to decode.
ctx.TextDecoder = TextDecoder;
const dec = (type: string, bytes: number[]) => run(`wireDecode(${JSON.stringify(type)}, new Uint8Array(${JSON.stringify(bytes)}))`);
assert.deepEqual({ ...dec('ipx.Marked', [0x08, 0xac, 0x02]) }, { marked: 300 }, 'a varint over a byte');
assert.equal(dec('ipx.SignalId', [0x08, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]).id, -1, 'a negative int64');
assert.equal(dec('ipx.Marked', []).marked, 0, 'a field at its default is not sent');
// A field this page does not know, as from a newer server, is passed over.
assert.equal(dec('ipx.Marked', [0x4a, 0x01, 0x78, 0x08, 0x05]).marked, 5);
const rows = dec('ipx.FeedRows', [0x0a, 0x03, 0x0a, 0x01, 0x61]);
assert.ok(Array.isArray(rows) && rows.length === 1, 'a list message is its array');
assert.equal(rows[0].id, 'a');
assert.equal(rows[0].title, null, 'an optional not sent is null, as JSON had it');
assert.equal(rows[0].failing, null, 'so is a message');
assert.deepEqual([...rows[0].keywords], []);
assert.equal(rows[0].pinned, false);
assert.equal(dec('ipx.Settings', [0x31, 0, 0, 0, 0, 0, 0, 0xf8, 0x3f]).max_total_gb, 1.5, 'a double');
assert.equal(run(`wireType('application/x-protobuf; messageType=ipx.FeedRows')`), 'ipx.FeedRows');
assert.equal(run(`wireType('application/json')`), undefined);
});

View File

@@ -10,5 +10,5 @@
"noUncheckedIndexedAccess": true,
"skipLibCheck": true
},
"include": ["web/sw/*.ts"]
"include": ["web/sw/*.ts", "web/src/wire.ts"]
}

View File

@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470).
- On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456).
- Share on an episode offers Share link, Share from where you are, and Copy link, with a link to the episode's page on ipx-play that anyone can play; an episode of a private feed offers its own page in the same menu, never its file, which a paid feed signs for you, and says why there is no page anyone can play. An admin sets ipx-play up in Admin, Directory (#447, #452, #454, #455).
- In the iOS app, Settings has a This device section for the app's server and player token, with a button that makes a token and hands it to the app (#445).

View File

@@ -29,13 +29,34 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js
// The files are one script, concatenated in this order, not modules: they share one top-level
// scope, as the single inline script did, and code that runs at load needs what came before it.
const PAGES: Record<string, { script: string, src: string[] }> = {
'index.html': { script: 'app.js', src: ['util', 'theme', 'feeds', 'feedpage', 'items', 'player', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'admin.html': { script: 'admin.js', src: ['util', 'theme', 'admin'] },
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'admin.html': { script: 'admin.js', src: ['util', 'wire', 'theme', 'admin'] },
'login.html': { script: 'login.js', src: ['login'] },
};
// The stylesheet the app and admin pages share, served and named by hash as the scripts are.
const STYLE = 'app.css';
/// The protobuf messages ipx answers in (#470), for web/src/wire.ts: { 'pkg.Name': [[number, name,
/// type, repeated, optional]] }, read from crates/wire/proto. Only what those files use: proto3,
/// one level of messages, scalar types and messages as field types.
export function wireMessages() {
const dir = path.join(here, '..', 'crates', 'wire', 'proto');
const short: Record<string, string> = { string: 's', bool: 'b', int64: 'i', int32: 'i', uint64: 'u', uint32: 'u', double: 'd' };
const out: Record<string, [number, string, string, 0 | 1, 0 | 1][]> = {};
for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.proto')).sort()) {
const text = fs.readFileSync(path.join(dir, file), 'utf8').replace(/\/\/.*$/gm, '');
const pkg = /^\s*package\s+([\w.]+)\s*;/m.exec(text)?.[1];
if (!pkg) throw new Error(`${file}: no package`);
for (const [, name, body] of text.matchAll(/message\s+(\w+)\s*\{([^}]*)\}/g)) {
out[`${pkg}.${name}`] = [...body!.matchAll(/^\s*(optional\s+|repeated\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)\s*;/gm)].map(
([, label, type, field, num]) => [Number(num), field!, short[type!] ?? (type!.includes('.') ? type! : `${pkg}.${type}`),
label?.trim() === 'repeated' ? 1 : 0, label?.trim() === 'optional' ? 1 : 0]);
}
}
return out;
}
const WIRE = JSON.stringify(wireMessages());
const hash = (s: string | Buffer) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 12);
// hls.js, for browsers that cannot play DeadAir's playlists themselves (#181). Served as it comes,
@@ -78,9 +99,11 @@ export function buildStyle({ minify = !coverageMap } = {}) {
return out;
}
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript.
function compile(file: string, { minify = true } = {}): string {
const src = fs.readFileSync(path.resolve(here, file), 'utf8');
/// A script served on its own, not one of the pages' (#392): TypeScript made JavaScript. `before`
/// are files put ahead of it, sharing its scope as the pages' files do.
function compile(file: string, { minify = true } = {}, before: string[] = []): string {
const src = [...before, file].map(f => fs.readFileSync(path.resolve(here, f), 'utf8')).join('\n')
.replaceAll('/*__WIRE__*/{}', WIRE);
return swc.transformSync(src, {
filename: path.basename(file),
jsc: { parser: { syntax: 'typescript' }, target: 'es2022', minify: minify ? { compress: true, mangle: true } : undefined },
@@ -90,7 +113,7 @@ function compile(file: string, { minify = true } = {}): string {
}
/// The offline service worker (#389), at the top of the site.
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o);
export const buildWorker = (o?: { minify?: boolean }) => compile('sw/sw.ts', o, ['src/wire.ts']);
/// The directory's one script (#392), as crates/directory/src/site.js holds it: readable, since it
/// is committed, and saying where it comes from.
export const buildDirectoryScript = () =>
@@ -108,7 +131,8 @@ export function buildPage(name: string, { minify = !coverageMap } = {}) {
const src = parts.map(p => p.text).join('\n')
.replaceAll('__HLS_JS__', HLS_URL)
.replaceAll('__ICONS__', ICONS_URL)
.replaceAll('__WEB_VERSION__', WEB_VERSION);
.replaceAll('__WEB_VERSION__', WEB_VERSION)
.replaceAll('/*__WIRE__*/{}', WIRE);
const js = swc.transformSync(src, {
filename: name + '.ts',
jsc: {

View File

@@ -179,7 +179,8 @@ async function api(url: string, opts?: RequestInit): Promise<any>{
const tp=traceparent(), mine=traceId;
const taps=!!rootKind&&(tapBusy>0||Date.now()-Math.max(rootAt,answeredAt)<2000);
if(taps) tapBusy++;
const r = await fetch(url,{headers:{'Content-Type':'application/json',traceparent:tp},...opts})
// Answers in protobuf where ipx has them (#470), JSON where not; wire.ts reads either the same.
const r = await fetch(url,{headers:{'Content-Type':'application/json',Accept:'application/x-protobuf, application/json',traceparent:tp},...opts})
.catch(()=>{ throw new Error('Unable to reach iPX. Check your connection and try again.'); })
.finally(()=>{ if(taps&&mine===traceId) tapBusy--; });
// The tap lasts until the last answer to what it set off.
@@ -193,6 +194,8 @@ async function api(url: string, opts?: RequestInit): Promise<any>{
throw new Error(r.status===500 ? 'iPX could not do that just now. Try again in a minute.'
: said || 'Unable to reach iPX just now. Try again in a minute.');
}
const pb=wireType(r.headers.get('Content-Type'));
if(pb) return wireDecode(pb,new Uint8Array(await r.arrayBuffer()));
return r.status===204?null:r.json().catch((): null=>null);
}
// navigator.clipboard only exists in a secure context. Served over plain HTTP on a LAN

67
web/src/wire.ts Normal file
View File

@@ -0,0 +1,67 @@
// ipx's answers in protobuf (#470): the page asks for them, and this reads one into the same object
// its JSON would have been, so nothing past api() knows the difference. The messages come from
// crates/wire/proto, which web/build.mts reads into WIRE when it builds the page and the offline
// worker, both of which take this file. No library: the encoding is a few rules, and a decoder
// library was larger than everything protobuf saves the page.
/// A field: its number, its name, its type (s string, b bool, i signed, u unsigned, d double, or a
/// message's full name), whether repeated, whether optional.
type WireField = readonly [number, string, string, 0 | 1, 0 | 1];
const WIRE = /*__WIRE__*/{} as Record<string, readonly WireField[]>;
/// Message `type` from `buf`, as its JSON would have read: an absent optional or message is null, a
/// list message (only `repeated items`) is its array, 64-bit numbers are numbers.
function wireDecode(type: string, buf: Uint8Array): any {
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
let pos = 0;
const text = new TextDecoder();
// Low and high 32 bits, as protobufjs reads them: a JS number's bit operations stop at 32.
// Each length is read before `pos` is used: `pos += varint()[0]` adds to the old `pos`.
const varint = (): [number, number] => {
let lo = 0, hi = 0, b = 0;
for (let i = 0; i < 4; i++) { b = buf[pos++]!; lo |= (b & 127) << (i * 7); if (b < 128) return [lo >>> 0, 0]; }
b = buf[pos++]!; lo |= (b & 127) << 28; hi |= (b & 127) >> 4; if (b < 128) return [lo >>> 0, hi >>> 0];
for (let i = 0; i < 5; i++) { b = buf[pos++]!; hi |= (b & 127) << (i * 7 + 3); if (b < 128) return [lo >>> 0, hi >>> 0]; }
throw new Error('a varint longer than ten bytes');
};
const num = ([lo, hi]: [number, number], signed: boolean) =>
signed && hi >= 0x80000000 ? -((~hi >>> 0) * 4294967296 + (~lo >>> 0) + 1) : hi * 4294967296 + lo;
const skip = (wt: number) => {
if (wt === 0) varint(); else if (wt === 1) pos += 8; else if (wt === 2) { const len = varint()[0]; pos += len; } else if (wt === 5) pos += 4;
else throw new Error(`wire type ${wt}`);
};
const scalar = (t: string): unknown => {
if (t === 'd') { const v = view.getFloat64(pos, true); pos += 8; return v; }
const v = varint();
return t === 'b' ? (v[0] | v[1]) !== 0 : num(v, t === 'i');
};
const message = (type: string, end: number): any => {
const fields = WIRE[type];
if (!fields) throw new Error(`no message ${type} in the page`);
const o: Record<string, unknown> = {};
for (const [, name, t, rep, opt] of fields) {
o[name] = rep ? [] : opt || t.length > 1 ? null : t === 's' ? '' : t === 'b' ? false : 0;
}
while (pos < end) {
const [tag] = varint();
const f = fields.find(x => x[0] === tag >>> 3), wt = tag & 7;
if (!f) { skip(wt); continue; }
const [, name, t, rep] = f;
let v: unknown;
if (t.length > 1) { const len = varint()[0]; v = WIRE[t] ? message(t, pos + len) : (pos += len, null); }
else if (t === 's') { const len = varint()[0]; v = text.decode(buf.subarray(pos, pos + len)); pos += len; }
// Packed: proto3 sends a repeated number as one run of them.
else if (rep && wt === 2) { const len = varint()[0], e = pos + len; while (pos < e) (o[name] as unknown[]).push(scalar(t)); continue; }
else v = scalar(t);
if (rep) (o[name] as unknown[]).push(v); else o[name] = v;
}
const only = fields.length === 1 ? fields[0] : undefined;
return only && only[1] === 'items' && only[3] ? o.items : o;
};
return message(type, buf.length);
}
/// The message an answer is in, from its Content-Type, or undefined for one that is not protobuf.
const wireType = (contentType: string | null) =>
/^application\/x-protobuf;\s*messageType=([\w.]+)/.exec(contentType || '')?.[1];

View File

@@ -133,10 +133,13 @@ async function withQueuedReads(kept: Response): Promise<Response> {
const read: unknown = (JSON.parse(w.body || '{}') as {read?: unknown}).read;
if (typeof read === 'boolean') reads.set(decodeURIComponent(m[1]!) + '\n' + decodeURIComponent(m[2]!), read);
}
if (!reads.size || !(kept.headers.get('Content-Type') || '').includes('json')) return kept;
// Only the fields read here: a page of items, or one item, as the API sends them.
const type = kept.headers.get('Content-Type') || '', pb = wireType(type);
if (!reads.size || !(type.includes('json') || pb)) return kept;
// Only the fields read here: a page of items, or one item, as the API sends them. One kept in
// protobuf (#470) goes back as JSON, which the page reads as well.
type Item = {feed_id: string, guid: string, read: boolean};
const body = await kept.clone().json().catch((): null => null) as {entries?: Item[]} & Partial<Item> | null;
const body = await (pb ? kept.clone().arrayBuffer().then(b => wireDecode(pb, new Uint8Array(b)))
: kept.clone().json()).catch((): null => null) as {entries?: Item[]} & Partial<Item> | null;
const mark = (e: Partial<Item>) => { const r = reads.get(e.feed_id + '\n' + e.guid); if (r !== undefined) e.read = r; };
if (Array.isArray(body?.entries)) body.entries.forEach(mark);
else if (body?.guid) mark(body);