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

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

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

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

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

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

View File

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