From 03e771a7b2e15aeb676c917c159a08bc18f647b1 Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 01:31:54 +0000 Subject: [PATCH] Dependencies past eight of nine published advisories (#467) ammonia 4.2.5 (mutation XSS through SVG and MathML, RUSTSEC-2026-0533), pulldown-cmark 0.13.6 (wikilinks, 0414 and 0433), tokio 1.54.1 (AsyncFd, 0386), and async-compression 0.4.52, which let zstd go to 0.14.4 (0391), with zstd-safe 8.3.0 and zstd-sys (0398, 0403, 0410). libsqlite3-sys (0459) stays at 0.37: sqlx-sqlite 0.9.0, the latest, pins it below 0.38, so it waits on sqlx. Production runs on Postgres; SQLite is the sample compose file's, the tests' and the load tests'. Co-Authored-By: Claude Opus 5.5 --- crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/daemon.rs | 1 + crates/ipx/src/db.rs | 142 ++++++++++++++++++++++++++++++++++++-- crates/ipx/src/entity.rs | 4 ++ crates/ipx/src/lib.rs | 1 + crates/ipx/src/search.rs | 88 +++++++++++++++++++++++ crates/ipx/src/signals.rs | 2 +- 7 files changed, 233 insertions(+), 6 deletions(-) create mode 100644 crates/ipx/src/search.rs diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index cdaaac9..7d73109 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459). - Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448). - `ipx reap --dry-run` says "would delete" of each file and of the total, rather than "deleted", word for word a real reap, of files it kept (#461). - Subscribing to a feed someone here already reads puts its recent items to your Signals at once, rather than at the judge's next pass, up to five minutes later (#415). diff --git a/crates/ipx/src/daemon.rs b/crates/ipx/src/daemon.rs index f31a7e7..1ac84f4 100644 --- a/crates/ipx/src/daemon.rs +++ b/crates/ipx/src/daemon.rs @@ -162,6 +162,7 @@ pub(crate) async fn daemon( tokio::spawn(signals::run(ctx.clone(), rx_stop.clone())); tokio::spawn(directory::run(ctx.clone(), rx_stop.clone())); tokio::spawn(crate::push::run(ctx.clone(), rx_stop.clone())); + tokio::spawn(crate::search::run(ctx.clone(), rx_stop.clone())); // The library's counts for /metrics. The Docker healthcheck asked for them every 30 s until // it was removed: Docker runs it with exec, which failed on Tower whenever root was logged // out (#218). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index e5ba5a9..9272e8e 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -181,6 +181,15 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> { let sql = "ALTER TABLE deadair_prefs ADD COLUMN pause_ms BIGINT"; orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?; } + if orm.execute_unprepared("SELECT search_text FROM entries LIMIT 0").await.is_err() { + // Every stored item starts without one: search.rs fills them in, behind the daemon (#459). + let sql = "ALTER TABLE entries ADD COLUMN search_text TEXT"; + orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?; + } + // The items whose search text is still to be made: what search.rs looks for, and what a search + // reads the old way meanwhile. Empty once they are made, so finding none costs nothing. + let sql = "CREATE INDEX IF NOT EXISTS entries_unsearched ON entries (feed_id) WHERE search_text IS NULL"; + orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?; Ok(()) } @@ -803,8 +812,8 @@ impl Db { .exec( "INSERT INTO entries (feed_id, guid, title, link, published, description, first_seen, - image, duration, episode, season, markdown) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) + image, duration, episode, season, markdown, search_text) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) ON CONFLICT DO NOTHING", vec![ feed_id.into(), @@ -819,6 +828,7 @@ impl Db { e.episode.into(), e.season.into(), e.markdown.clone().into(), + crate::search::search_text(e.title.as_deref(), e.description.as_deref()).into(), ], ) .await?; @@ -831,7 +841,12 @@ impl Db { duration = coalesce($6, duration), episode = coalesce($7, episode), season = coalesce($8, season), - markdown = coalesce($9, markdown) + markdown = coalesce($9, markdown), + -- Made again, by search.rs, when what it is made of has changed; the values + -- here are the row's as it was. + search_text = CASE WHEN title IS NOT DISTINCT FROM coalesce($3, title) + AND description IS NOT DISTINCT FROM coalesce($4, description) + THEN search_text END WHERE feed_id = $1 AND guid = $2", vec![ feed_id.into(), @@ -1074,6 +1089,72 @@ impl Db { Ok(()) } + /// Up to `limit` items whose search text is still to be made: feed, guid, title, description. + pub async fn unsearched(&self, limit: i64) -> Result, Option)>> { + self.rows( + "SELECT feed_id, guid, title, description FROM entries WHERE search_text IS NULL LIMIT $1", + vec![limit.into()], + ) + .await? + .iter() + .map(|r| { + Ok(( + r.try_get("", "feed_id")?, + r.try_get("", "guid")?, + r.try_get("", "title")?, + r.try_get("", "description")?, + )) + }) + .collect() + } + + pub async fn set_search_text(&self, feed_id: &str, guid: &str, text: &str) -> Result<()> { + self.exec( + "UPDATE entries SET search_text = $3 WHERE feed_id = $1 AND guid = $2", + vec![feed_id.into(), guid.into(), text.into()], + ) + .await?; + Ok(()) + } + + /// The trigram index a search uses on Postgres (#459), made once, beside the scans rather than + /// in their way (CONCURRENTLY), and made again if a build of it was cut off, which leaves it + /// there but unused. SQLite has no pg_trgm and reads the column whole, which is still a + /// fraction of the HTML. False when Postgres would not give pg_trgm, which a search survives. + pub async fn search_index(&self) -> Result { + if self.orm.get_database_backend() != sea_orm::DbBackend::Postgres { + return Ok(true); + } + let valid = self + .rows( + "SELECT i.indisvalid AS valid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid + WHERE c.relname = 'entries_search' AND pg_table_is_visible(c.oid)", + vec![], + ) + .await? + .first() + .map(|r| r.try_get::("", "valid")) + .transpose()?; + match valid { + Some(true) => return Ok(true), + Some(false) => { + self.orm.execute_unprepared("DROP INDEX CONCURRENTLY entries_search").await?; + } + None => {} + } + if let Err(e) = self.orm.execute_unprepared("CREATE EXTENSION IF NOT EXISTS pg_trgm").await { + tracing::warn!(error = %e, "search: pg_trgm could not be installed; searches read every item's text"); + return Ok(false); + } + self.orm + .execute_unprepared( + "CREATE INDEX CONCURRENTLY entries_search ON entries USING gin (search_text gin_trgm_ops)", + ) + .await + .context("indexing entries.search_text")?; + Ok(true) + } + /// A feed's stored artwork still on http, items' and its own: hosts a feed no longer names /// keep their old items' artwork on http otherwise (IGN's 2009 items, #110). pub async fn http_images(&self, feed_id: &str) -> Result> { @@ -1281,9 +1362,13 @@ fn entries_from( // % and _ as typed, not as wildcards: "100%" matched anything starting 100 (#296). let q = q.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); let like = a.p(format!("%{q}%")); + // The title and the text without its markup, lowercased (search.rs), which pg_trgm + // indexes: matching the HTML took 5 s for All Subscriptions, most of it reading 4 GB of + // descriptions (#459). An item not yet given one is matched the old way. format!( - "(lower(coalesce(e.title, '')) LIKE {like} ESCAPE '\\' \ - OR lower(coalesce(e.description, '')) LIKE {like} ESCAPE '\\')" + "(e.search_text LIKE {like} ESCAPE '\\' \ + OR (e.search_text IS NULL AND (lower(coalesce(e.title, '')) LIKE {like} ESCAPE '\\' \ + OR lower(coalesce(e.description, '')) LIKE {like} ESCAPE '\\')))" ) } None => "true".into(), @@ -3655,6 +3740,53 @@ mod tests { assert_eq!(files, ["u1"].map(String::from).into()); // u2 is g's: left to the insert to find } + #[tokio::test] + async fn a_search_reads_the_words_and_an_item_without_search_text_the_old_way() { + let db = Db::memory().await.unwrap(); + let me = db.create_user("me", None, false).await.unwrap(); + db.exec_for_test( + "INSERT INTO feeds (id, url) VALUES ('f', 'http://x/f.xml'); + INSERT INTO entries (feed_id, guid, title, description, first_seen) VALUES ('f','old','Old','

Banana

',1);", + ) + .await + .unwrap(); + db.subscribe(me, "f").await.unwrap(); + let item = |text: &str| crate::feed::Entry { + guid: "a".into(), + title: Some("Apple news".into()), + description: Some(text.into()), + ..Default::default() + }; + db.record_entry("f", &item(r#"

Read more

"#)).await.unwrap(); + let order = order_sql("published", "desc"); + let found = async |q: &str| -> Vec { + let rows = db.entries_of(me, None, Filter::All, Some(q), 0, 50, &order).await.unwrap(); + assert_eq!(db.count_of(me, None, Filter::All, Some(q)).await.unwrap(), rows.len() as i64, "{q}"); + rows.into_iter().map(|r| r.guid).collect() + }; + assert_eq!(found("APP").await, ["a"], "a part of a word, in any case"); + assert_eq!(found("more").await, ["a"]); + assert!(found("shop.example").await.is_empty(), "an address in the markup is not a word of the post"); + assert_eq!(found("banana").await, ["old"], "stored before search text, matched the old way"); + + for (f, g, t, d) in db.unsearched(100).await.unwrap() { + db.set_search_text(&f, &g, &crate::search::search_text(t.as_deref(), d.as_deref())).await.unwrap(); + } + assert!(db.unsearched(100).await.unwrap().is_empty()); + assert_eq!(found("banana").await, ["old"], "and by its search text once made"); + + // Told differently, it is made again; until then the old way finds the new words. + db.record_entry("f", &item("

Cherry

")).await.unwrap(); + assert_eq!(db.unsearched(100).await.unwrap().len(), 1); + assert_eq!(found("cherry").await, ["a"]); + // Told the same, it keeps what it has. + for (f, g, t, d) in db.unsearched(100).await.unwrap() { + db.set_search_text(&f, &g, &crate::search::search_text(t.as_deref(), d.as_deref())).await.unwrap(); + } + db.record_entry("f", &item("

Cherry

")).await.unwrap(); + assert!(db.unsearched(100).await.unwrap().is_empty()); + } + #[tokio::test] async fn a_scan_finds_the_stored_items_the_feed_now_tells_differently() { let db = Db::memory().await.unwrap(); diff --git a/crates/ipx/src/entity.rs b/crates/ipx/src/entity.rs index 45e1c74..447997b 100644 --- a/crates/ipx/src/entity.rs +++ b/crates/ipx/src/entity.rs @@ -86,6 +86,10 @@ pub mod entries { pub duration: Option, pub episode: Option, pub season: Option, + /// The title and the text without markup, lowercased and cut short, which search reads + /// (#459); none until search.rs makes it. + #[sea_orm(column_type = "Text", nullable)] + pub search_text: Option, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] diff --git a/crates/ipx/src/lib.rs b/crates/ipx/src/lib.rs index 25f6345..7708691 100644 --- a/crates/ipx/src/lib.rs +++ b/crates/ipx/src/lib.rs @@ -27,6 +27,7 @@ mod play; mod push; mod retention; mod scan; +mod search; mod signals; #[cfg(test)] mod test_util; diff --git a/crates/ipx/src/search.rs b/crates/ipx/src/search.rs new file mode 100644 index 0000000..505d254 --- /dev/null +++ b/crates/ipx/src/search.rs @@ -0,0 +1,88 @@ +//! What a search reads (#459): each item's title and text, the markup taken out, lowercased and cut +//! short, kept in `entries.search_text` beside the HTML. Matching the HTML itself took 5 s on All +//! Subscriptions, most of it reading 4 GB of descriptions; the plain text is a fraction of that, +//! and Postgres indexes it with pg_trgm, so a part of a word still finds the word, as before. + +use std::sync::Arc; +use std::time::Duration; + +use tracing::Instrument; + +use crate::ctx::Ctx; + +/// Enough of a post for its subject to be in it; a word only past this in a very long post is not +/// found. It keeps the index a size the shared Postgres carries. +pub const MAX_CHARS: usize = 4000; +/// Items made at a time, and how long between looks for more once none are left. +const BATCH: i64 = 500; +const EVERY: Duration = Duration::from_secs(5 * 60); + +/// The title, then the text with its markup taken out (an image's alt and title kept, as Signals +/// read them), lowercased, its spaces made single, and at most `MAX_CHARS` long. +pub fn search_text(title: Option<&str>, description: Option<&str>) -> String { + let text = crate::signals::text_of(description.unwrap_or("")); + let all = format!("{} {}", title.unwrap_or(""), text).to_lowercase(); + all.split_whitespace().collect::>().join(" ").chars().take(MAX_CHARS).collect() +} + +/// Makes every item's search text that is missing, then the index, then looks again now and then: +/// a scan that changes an item's title or text leaves its search text to be made again here, and +/// a search reads that item the old way until it is. +pub async fn run(ctx: Arc, mut stop: tokio::sync::watch::Receiver) { + let mut indexed = false; + loop { + let pass = async { + let made = fill(&ctx).await?; + if !indexed { + indexed = ctx.db.search_index().instrument(crate::db::step("search_index")).await?; + } + anyhow::Ok(made) + }; + tokio::select! { + _ = stop.changed() => return, + done = pass.instrument(tracing::info_span!("search_text")) => match done { + Ok(n) if n > 0 => tracing::info!(items = n, "search: made items' search text"), + Ok(_) => {} + Err(e) => tracing::warn!(error = %format!("{e:#}"), "search: items' search text could not be made"), + }, + } + tokio::select! { + _ = stop.changed() => return, + _ = tokio::time::sleep(EVERY) => {} + } + } +} + +/// Every item without search text, given one, a batch at a time: how many. +async fn fill(ctx: &Ctx) -> anyhow::Result { + let mut made = 0; + loop { + let batch = ctx.db.unsearched(BATCH).await?; + if batch.is_empty() { + return Ok(made); + } + for (feed, guid, title, description) in &batch { + ctx.db.set_search_text(feed, guid, &search_text(title.as_deref(), description.as_deref())).await?; + } + made += batch.len(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_text_is_the_words_not_the_markup() { + let t = search_text( + Some("Apple's NEW Thing"), + Some(r#"

Read more

A Chart"#), + ); + assert_eq!(t, "apple's new thing read more a chart"); + assert!(!t.contains("href") && !t.contains("x.example"), "an address in a tag is not a word of the post"); + assert_eq!(search_text(None, None), ""); + let long = "word ".repeat(2000); + assert_eq!(search_text(Some("Title"), Some(&long)).chars().count(), MAX_CHARS); + assert!(search_text(Some("Title"), Some(&long)).starts_with("title word"), "the title is always in it"); + } +} diff --git a/crates/ipx/src/signals.rs b/crates/ipx/src/signals.rs index 1e455cc..8029272 100644 --- a/crates/ipx/src/signals.rs +++ b/crates/ipx/src/signals.rs @@ -497,7 +497,7 @@ fn chosen(answer: &serde_json::Value, candidates: &[(String, String)]) -> Option /// Show notes are HTML: Jev is given their words, and an image's alt and title text, which is all /// the words some posts have. xkcd's is a comic and its hover text; dropping the tag whole sent Jev /// "Ground Effect" alone, an F1 aerodynamics term, and the comic went into Formula 1 (#267). -fn text_of(html: &str) -> String { +pub(crate) fn text_of(html: &str) -> String { let mut out = String::with_capacity(html.len()); let mut tag: Option = None; for c in html.chars() {