//! Counts of the records across the network that point at a record: its //! likes, reposts and replies, a gallery's favorites. A repository holds //! only its own records, so these come from a backlink index, which //! watches every repository and counts, for a target at-uri, the records //! of each collection whose field at a path names it. The index is behind //! an interface (`Index`) so another can replace it; the one there is is //! Constellation (`HUD_BACKLINKS=constellation:`, the default), and //! `none` turns counts off. A view never names the index: it names what to //! count, a collection and a path, so swapping the index changes no view. //! //! An index is someone else's server and may lag, fail or be down: its //! answers are kept a minute, its failures too, and a failure is no counts //! (`null`), never a tool's error. use crate::Hud; use crate::net::Net; use futures::future::BoxFuture; use serde_json::{Map, Value, json}; use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; use url::Url; /// The index used when `HUD_BACKLINKS` is not set. pub const DEFAULT: &str = "constellation:https://constellation.microcosm.blue"; /// How long an index has to answer. const WAIT: Duration = Duration::from_secs(5); /// The most of an answer read. const MAX: usize = 1024 * 1024; /// How long an answer, or a failure, is kept. pub const KEEP: Duration = Duration::from_secs(60); /// Which backlink index counts come from. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Backlinks { /// No index: counts are null. None, /// A Constellation server, at its base URL (no trailing `/`). Constellation(String), } impl Backlinks { /// `HUD_BACKLINKS`: `none`, or `constellation:`; anything /// else is refused. pub fn parse(s: &str) -> Result { let s = s.trim(); if s == "none" { return Ok(Backlinks::None); } let Some((scheme, rest)) = s.split_once(':') else { return Err(format!( "{s:?} is not an index: none, or constellation:" )); }; match scheme { "constellation" => { let bad = || format!("{rest:?} is not an http or https URL of a Constellation server"); let url = Url::parse(rest).map_err(|_| bad())?; let plain = matches!(url.scheme(), "http" | "https") && url.host().is_some() && url.username().is_empty() && url.password().is_none() && url.query().is_none() && url.fragment().is_none(); if !plain { return Err(bad()); } Ok(Backlinks::Constellation( url.as_str().trim_end_matches('/').to_string(), )) } other => Err(format!( "{other:?} is not an index HUD knows: none, or constellation:" )), } } } /// A count of records pointing at a target from one collection and path. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Count { pub records: u64, pub distinct_dids: u64, } /// A target's counts, by collection and path (as the index writes paths, /// starting with `.`, as `.subject.uri`). pub type Counts = BTreeMap<(String, String), Count>; /// A backlink index. pub trait Index: Send + Sync { /// Every count the index has of records pointing at `target`. fn counts<'a>(&'a self, net: &'a Net, target: &'a str) -> BoxFuture<'a, Result>; } /// Constellation (microcosm.blue): `GET /links/all?target=`. pub struct Constellation { base: String, } impl Index for Constellation { fn counts<'a>( &'a self, net: &'a Net, target: &'a str, ) -> BoxFuture<'a, Result> { Box::pin(async move { let mut url = Url::parse(&format!("{}/links/all", self.base)) .map_err(|_| "the index's URL is unusable".to_string())?; url.query_pairs_mut().append_pair("target", target); let got = net.fetch_json(&url, WAIT, MAX).await?; if got.status != 200 { return Err(format!("the index answered {}", got.status)); } let body: Value = serde_json::from_slice(&got.body) .map_err(|_| "the index answered no JSON".to_string())?; constellation_counts(&body).ok_or_else(|| "the index answered no links".to_string()) }) } } /// Constellation's `/links/all` answer, `{links: {: {: /// {records, distinct_dids}}}}`, as counts. fn constellation_counts(body: &Value) -> Option { let mut out = Counts::new(); for (collection, paths) in body.get("links")?.as_object()? { for (path, n) in paths.as_object().into_iter().flatten() { let records = n.get("records").and_then(Value::as_u64).unwrap_or(0); let distinct_dids = n.get("distinct_dids").and_then(Value::as_u64).unwrap_or(0); out.insert( (collection.clone(), path.clone()), Count { records, distinct_dids, }, ); } } Some(out) } /// The index `Backlinks` names, if any. pub fn index(b: &Backlinks) -> Option> { match b { Backlinks::None => None, Backlinks::Constellation(base) => Some(Box::new(Constellation { base: base.clone() })), } } /// A counts join's result: each name's count of records (0 where the index /// has none), or null with no counts (no index, or it failed). pub fn named(names: &[(String, String, String)], counts: Option<&Counts>) -> Value { let Some(counts) = counts else { return Value::Null; }; let out: Map = names .iter() .map(|(name, collection, path)| { let n = counts .get(&(collection.clone(), path.clone())) .map_or(0, |c| c.records); (name.clone(), json!(n)) }) .collect(); Value::Object(out) } /// Every count of a target, as `describe_collection` shows a sample's: /// `[{collection, path, records}]`, the most records first. pub fn listed(counts: &Counts) -> Value { let mut all: Vec<(&(String, String), &Count)> = counts.iter().collect(); all.sort_by(|a, b| b.1.records.cmp(&a.1.records).then_with(|| a.0.cmp(b.0))); Value::Array( all.into_iter() .map(|((collection, path), c)| { json!({ "collection": collection, "path": path, "records": c.records }) }) .collect(), ) } impl Hud { /// The counts of records pointing at `target`, kept a minute; none if /// there is no index, or it failed (kept a minute too). pub async fn backlink_counts(&self, target: &str) -> Option> { let index = self.backlinks.as_ref()?; if let Some(kept) = self.counts.get(&target.to_string()) { return kept; } let got = match index.counts(&self.net, target).await { Ok(c) => Some(Arc::new(c)), Err(why) => { tracing::warn!(target, why, "the backlink index failed"); None } }; self.counts.put(target.to_string(), got.clone(), KEEP); got } } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; /// A Constellation answering each target as it names it, counting /// what it is asked; and its URL. async fn constellation(asked: Arc) -> String { let links = move |axum::extract::Query(q): axum::extract::Query>| { asked.fetch_add(1, SeqCst); async move { use axum::response::IntoResponse; match q["target"].as_str() { "at://ok" => axum::Json(json!({ "links": { "app.bsky.feed.like": { ".subject.uri": { "records": 3, "distinct_dids": 2 } } } })) .into_response(), "at://busy" => axum::http::StatusCode::BAD_GATEWAY.into_response(), "at://text" => "nope".into_response(), _ => axum::Json(json!({ "error": "x" })).into_response(), } } }; let app = axum::Router::new().route("/links/all", axum::routing::get(links)); crate::tests::serve(app).await } #[tokio::test] async fn counts_from_constellation_kept_a_minute() { let asked = Arc::new(AtomicUsize::new(0)); let base = constellation(asked.clone()).await; let hud = crate::tests::hud_with("http://127.0.0.1:1", |c| { c.backlinks = Backlinks::Constellation(base.clone()); }); let like = ("app.bsky.feed.like".to_string(), ".subject.uri".to_string()); let counts = hud.backlink_counts("at://ok").await.unwrap(); assert_eq!( counts.get(&like), Some(&Count { records: 3, distinct_dids: 2 }) ); // A failure is no counts, kept as well. assert!(hud.backlink_counts("at://busy").await.is_none()); assert!(hud.backlink_counts("at://ok").await.is_some()); assert!(hud.backlink_counts("at://busy").await.is_none()); assert_eq!(asked.load(SeqCst), 2); // Why each failed. let why = |base: &str, target: &'static str| { let hud = hud.clone(); let index = Constellation { base: base.into() }; async move { index.counts(&hud.net, target).await.unwrap_err() } }; assert_eq!(why(&base, "at://busy").await, "the index answered 502"); assert_eq!(why(&base, "at://text").await, "the index answered no JSON"); assert_eq!(why(&base, "at://none").await, "the index answered no links"); assert_eq!( why("http://127.0.0.1:1", "at://ok").await, "could not connect" ); assert_eq!( why("no index", "at://ok").await, "the index's URL is unusable" ); // No index: no counts. let none = crate::tests::hud_with("http://127.0.0.1:1", |_| {}); assert!(none.backlink_counts("at://ok").await.is_none()); } #[test] fn listed_ties_by_name() { let n = |records| Count { records, distinct_dids: records, }; let counts = Counts::from([ (("b.c.d".into(), ".x".into()), n(1)), (("a.c.d".into(), ".y".into()), n(1)), (("a.c.d".into(), ".x".into()), n(2)), ]); let order: Vec = listed(&counts) .as_array() .unwrap() .iter() .map(|c| format!("{} {}", c["collection"], c["path"])) .collect(); assert_eq!( order, [r#""a.c.d" ".x""#, r#""a.c.d" ".y""#, r#""b.c.d" ".x""#] ); } #[test] fn parsing() { assert_eq!(Backlinks::parse("none"), Ok(Backlinks::None)); assert_eq!( Backlinks::parse(DEFAULT), Ok(Backlinks::Constellation( "https://constellation.microcosm.blue".into() )) ); assert_eq!( Backlinks::parse(" constellation:http://127.0.0.1:6789/ "), Ok(Backlinks::Constellation("http://127.0.0.1:6789".into())) ); for bad in [ "", "constellation", "constellation:", "constellation:ftp://x.example", "constellation:https://x.example/?q=1", "constellation:https://u@x.example", "atlas:https://x.example", "None", ] { assert!(Backlinks::parse(bad).is_err(), "{bad}"); } } #[test] fn mapping() { let body = json!({ "links": { "app.bsky.feed.like": { ".subject.uri": { "records": 39, "distinct_dids": 39 } }, "app.bsky.feed.repost": { ".subject.uri": { "records": 4, "distinct_dids": 4 } }, "app.bsky.feed.post": { ".reply.parent.uri": { "records": 7, "distinct_dids": 5 }, ".embed.record.uri": { "records": 2, "distinct_dids": 2 } }, } }); let counts = constellation_counts(&body).unwrap(); let names = |n: &[(&str, &str, &str)]| -> Vec<(String, String, String)> { n.iter() .map(|(a, b, c)| (a.to_string(), b.to_string(), c.to_string())) .collect() }; let wanted = names(&[ ("likes", "app.bsky.feed.like", ".subject.uri"), ("replies", "app.bsky.feed.post", ".reply.parent.uri"), ("quotes", "app.bsky.feed.post", ".embed.record.uri.missing"), ("favorites", "social.grain.favorite", ".subject"), ]); // Missing ones are 0. assert_eq!( named(&wanted, Some(&counts)), json!({ "likes": 39, "replies": 7, "quotes": 0, "favorites": 0 }) ); // No index, or it failed: null. assert_eq!(named(&wanted, None), Value::Null); assert_eq!( listed(&counts), json!([ { "collection": "app.bsky.feed.like", "path": ".subject.uri", "records": 39 }, { "collection": "app.bsky.feed.post", "path": ".reply.parent.uri", "records": 7 }, { "collection": "app.bsky.feed.repost", "path": ".subject.uri", "records": 4 }, { "collection": "app.bsky.feed.post", "path": ".embed.record.uri", "records": 2 }, ]) ); assert_eq!(constellation_counts(&json!({ "error": "x" })), None); assert_eq!( constellation_counts(&json!({ "links": {} })), Some(Counts::new()) ); } }