chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
0
0
The index keeps what's asked and answers without waiting on its writes
.changeset/index-keeps-what-is-asked.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# The index keeps what is asked for, and answers within 2 s | ||
| ||
`hud index` is a cache now in name and deed. A collection, a field or an author nobody asks for in `HUD_INDEX_KEEP_DAYS` (14) days is dropped, a little at a time behind the writes, unless `HUD_INDEX_KEEP` names it, and a later spec takes it in again. A collection held by more than `HUD_INDEX_MAX_REPOS` (20,000) repositories, such as `app.bsky.feed.post`, is taken in per author: only the authors a spec names (`by`) are read and kept current, and a spec naming none answers from those with `partial: true` and the new `partialReason: perAuthor` (unless `HUD_INDEX_LARGE` takes it in whole). A collection past `HUD_INDEX_SLOW_RECORDS` (250,000) records goes slow, behind every other backfill, and still completes; every backfill pauses while the disk has less than `HUD_INDEX_MIN_FREE` (2 GB) free. Answers never wait on the writer: fields' tables are made in the background, reads go through at most `HUD_INDEX_READERS` (6) connections, and an answer past 2 s answers `partialReason: deadline`. `partialReason` says `filling` while a field is being indexed. getStatus says of each collection whether it is taken in `whole` or `perAuthor`, whether it is `slow`, its `records` and `lastAsked`, and whether backfills are `paused`. HUD asks a partial answer again soon, and keeps one taken in per author live as a complete one. | ||
crates/hud/src/main.rs+61−6
| @@ -218,6 +218,22 @@ HUD_ALLOW_PRIVATE, RUST_LOG, HUD_SLOW_MS, HUD_LOGS and HUD_LOGS_KEEP above: | ||
PDS hosts whose repositories are never read, by commas | ||
or spaces, and the hosts under them; empty skips none | ||
(atproto.brid.gy) | ||
HUD_INDEX_READERS the most connections reading the index at once (6) | ||
HUD_INDEX_KEEP_DAYS | ||
days a collection, a field or an author is kept with | ||
nobody asking for it (14) | ||
HUD_INDEX_KEEP collections kept however long nobody asks, by commas | ||
or spaces (none) | ||
HUD_INDEX_MAX_REPOS | ||
past this many repositories holding a collection, it is | ||
taken in per author, as specs name them (20000) | ||
HUD_INDEX_LARGE collections taken in whole however many hold them, by | ||
commas or spaces (none) | ||
HUD_INDEX_SLOW_RECORDS | ||
past this many records held of a collection, its | ||
backfill goes behind every other's (250000) | ||
HUD_INDEX_MIN_FREE bytes free on the index's disk below which backfills | ||
pause (2000000000) | ||
"; | ||
| ||
/// An environment variable, if set to something. | ||
| @@ -829,20 +845,59 @@ fn index_settings(config: &Config) -> Result<(SocketAddr, hud_index::Settings), | ||
return Err("HUD_INDEX_SKIP_HOSTS is not valid text".into()); | ||
} | ||
}; | ||
let backfill = hud_index::backfill::Settings { | ||
relay, | ||
hubble, | ||
skip_hosts, | ||
max_repos: number("HUD_INDEX_MAX_REPOS", "repositories", defaults.max_repos)?, | ||
large: nsids("HUD_INDEX_LARGE")?, | ||
slow_records: number("HUD_INDEX_SLOW_RECORDS", "records", defaults.slow_records)?, | ||
..defaults | ||
}; | ||
let kept = hud_index::sweep::Settings::default(); | ||
let days = number("HUD_INDEX_KEEP_DAYS", "days", kept.keep.as_secs() / 86_400)?; | ||
let sweep = hud_index::sweep::Settings { | ||
keep: std::time::Duration::from_secs(days.saturating_mul(86_400)), | ||
kept: nsids("HUD_INDEX_KEEP")?, | ||
min_free: number("HUD_INDEX_MIN_FREE", "bytes", kept.min_free)?, | ||
..kept | ||
}; | ||
let settings = hud_index::Settings { | ||
origin, | ||
db, | ||
backfill: hud_index::backfill::Settings { | ||
relay, | ||
hubble, | ||
skip_hosts, | ||
..defaults | ||
}, | ||
readers: number( | ||
"HUD_INDEX_READERS", | ||
"connections", | ||
hud_index::store::READERS, | ||
)?, | ||
backfill, | ||
live: hud_index::live::Settings { jetstreams }, | ||
sweep, | ||
}; | ||
Ok((SocketAddr::new(config.bind, port), settings)) | ||
} | ||
| ||
/// `name` as a number of `what`, or `default` where it is unset. | ||
fn number<T: std::str::FromStr>(name: &str, what: &str, default: T) -> Result<T, String> { | ||
match var(name)? { | ||
Some(n) => n | ||
.parse() | ||
.map_err(|_| format!("{name}: {n:?} is not a number of {what}")), | ||
None => Ok(default), | ||
} | ||
} | ||
| ||
/// `name` as a list of NSIDs, by commas or spaces; none where it is unset. | ||
fn nsids(name: &str) -> Result<Vec<String>, String> { | ||
let listed = var(name)?.unwrap_or_default(); | ||
items(&listed) | ||
.map(|n| match atproto::syntax::is_nsid(n) { | ||
true => Ok(n.to_string()), | ||
false => Err(format!("{name}: {n:?} is not an NSID")), | ||
}) | ||
.collect() | ||
} | ||
| ||
/// `hud index`: the index (`hud_index`) on a port of its own, with | ||
/// `hud serve`'s identity and outbound client, its lines kept with | ||
/// `HUD_LOGS` and summarized each minute as `hud serve`'s are, and its | ||
crates/hud/tests/cli.rs+19−1
| @@ -1200,6 +1200,16 @@ fn serves_the_index_and_stops_on_sigterm() { | ||
"ws://127.0.0.1:9, wss://jetstream.example/", | ||
), | ||
("HUD_INDEX_SKIP_HOSTS", "a.example b.example"), | ||
("HUD_INDEX_READERS", "4"), | ||
("HUD_INDEX_KEEP_DAYS", "7"), | ||
( | ||
"HUD_INDEX_KEEP", | ||
"social.grain.gallery, fm.teal.alpha.feed.play", | ||
), | ||
("HUD_INDEX_MAX_REPOS", "100"), | ||
("HUD_INDEX_LARGE", "app.bsky.feed.post"), | ||
("HUD_INDEX_SLOW_RECORDS", "1000"), | ||
("HUD_INDEX_MIN_FREE", "0"), | ||
("HUD_INDEX_METRICS", &at), | ||
("HUD_DATA_DIR", dir.to_str().unwrap()), | ||
("HUD_RELAY", "http://127.0.0.1:9"), | ||
| @@ -1221,7 +1231,7 @@ fn serves_the_index_and_stops_on_sigterm() { | ||
); | ||
assert_eq!( | ||
get(port, "/xrpc/place.hud.index.getStatus"), | ||
(200, r#"{"collections":[]}"#.into()) | ||
(200, r#"{"collections":[],"paused":false}"#.into()) | ||
); | ||
let (status, _, text) = ask(metrics, "GET", "/metrics", "", ""); | ||
assert_eq!(status, 200); | ||
| @@ -1285,6 +1295,14 @@ fn refuses_index_configuration_it_cannot_use() { | ||
&[("HUD_INDEX_JETSTREAMS", "https://jetstream.example")], | ||
r#"HUD_INDEX_JETSTREAMS: "https://jetstream.example" is not a ws or wss URL"#, | ||
), | ||
( | ||
&[("HUD_INDEX_READERS", "many")], | ||
r#"HUD_INDEX_READERS: "many" is not a number of connections"#, | ||
), | ||
( | ||
&[("HUD_INDEX_LARGE", "app.bsky.feed.post bad!")], | ||
r#"HUD_INDEX_LARGE: "bad!" is not an NSID"#, | ||
), | ||
( | ||
&[("HUD_INDEX_DB", under_a_file.to_str().unwrap())], | ||
&format!("the index at {}", under_a_file.display()), | ||
crates/hud-core/src/ui/refresh.rs+34−3
| @@ -23,14 +23,22 @@ const LIVE_MS: u64 = 20_000; | ||
| ||
/// `_meta.ui.refresh` of a query's answer (its `structuredContent`): | ||
/// `{ afterMs, note? }` while it fills, `{ afterMs, live: true, version? }` | ||
/// once complete, or None for another method's. | ||
/// once complete, or None for another method's. A complete answer still | ||
/// partial (a field being indexed, or out of time) is asked again soon; | ||
/// one of a collection taken in per author, which never completes, as a | ||
/// complete one is. | ||
pub fn refresh(structured: &Value) -> Option<Value> { | ||
let response = &structured["response"]; | ||
if structured["method"] != INDEX { | ||
return None; | ||
} | ||
if response["complete"].as_bool()? { | ||
let mut hint = json!({ "afterMs": LIVE_MS, "live": true }); | ||
let reason = response["partialReason"].as_str(); | ||
if response["complete"].as_bool()? || reason == Some("perAuthor") { | ||
let after = match reason { | ||
Some("filling" | "deadline") => READING_MS.0, | ||
_ => LIVE_MS, | ||
}; | ||
let mut hint = json!({ "afterMs": after, "live": true }); | ||
if let Some(version) = response["version"].as_str() { | ||
hint["version"] = version.into(); | ||
} | ||
| @@ -170,4 +178,27 @@ mod tests { | ||
other["response"]["complete"] = Value::Null; | ||
assert_eq!(refresh(&other), None); | ||
} | ||
| ||
/// A complete answer still partial, a field being indexed or out of | ||
/// time, is asked again soon; one of a collection taken in per author, | ||
/// never complete, is kept live as a complete one is. | ||
#[test] | ||
fn a_partial_answer_says_when_to_ask_again_by_its_reason() { | ||
let mut whole = filling(543, 543, false, json!([])); | ||
whole["response"]["complete"] = true.into(); | ||
for reason in ["filling", "deadline"] { | ||
whole["response"]["partialReason"] = reason.into(); | ||
assert_eq!( | ||
refresh(&whole), | ||
Some(json!({ "afterMs": 2000, "live": true })) | ||
); | ||
} | ||
let mut wide = filling(20_001, 7, false, json!([])); | ||
wide["response"]["partialReason"] = "perAuthor".into(); | ||
wide["response"]["version"] = "19a.0.7.0.0".into(); | ||
assert_eq!( | ||
refresh(&wide), | ||
Some(json!({ "afterMs": 20000, "live": true, "version": "19a.0.7.0.0" })) | ||
); | ||
} | ||
} | ||
crates/hud-index/examples/backfill_load.rsnew+229−0
| @@ -0,0 +1,229 @@ | ||
//! How long answers take while two collections are backfilled at once, as | ||
//! production's were: two writer threads put synthetic records through the | ||
//! backfill's lanes, `PLAYS` plays (as `fm.teal.alpha.feed.play`'s, a | ||
//! track and a release each, a collection big enough to go slow) and | ||
//! `FAVORITES` favorites (as `social.grain.favorite`'s, of a gallery | ||
//! each), a tenth of each held before; meanwhile reader threads ask what | ||
//! tiles ask (the newest plays, a track by name, the top releases, a page | ||
//! by fifty authors, a gallery's favorites, and a field never asked | ||
//! before, whose table is made meanwhile), each answer timed. Prints each | ||
//! collection's backfill rate, and each kind of answer's p50, p99 and | ||
//! slowest, and how many answered late or partial. | ||
//! | ||
//! cargo run --release -p hud-index --example backfill_load [plays] [favorites] | ||
//! | ||
//! Production's index has one CPU: give it one as production's container | ||
//! does, `docker run --cpus=1 --memory=1g` around a Linux build of it. | ||
| ||
use hud_index::sink::{Record, Sink, Write}; | ||
use hud_index::spec::parse; | ||
use hud_index::store::{DEADLINE, Store}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
use std::sync::atomic::{AtomicUsize, Ordering}; | ||
use std::time::{Duration, Instant}; | ||
| ||
const PLAY: &str = "fm.teal.alpha.feed.play"; | ||
const FAVORITE: &str = "social.grain.favorite"; | ||
const PLAYS: usize = 300_000; | ||
const FAVORITES: usize = 100_000; | ||
/// Records a call to the sink, as the backfill gives them. | ||
const BATCH: usize = 1000; | ||
const AUTHORS: usize = 543; | ||
const GALLERIES: usize = 2_000; | ||
const MINUTE: i64 = 60_000_000; | ||
| ||
/// A record of `collection` by author `j`, its record key the TID of `t`. | ||
fn record(j: usize, collection: &str, t: i64, value: Value) -> Write { | ||
let value = atproto::drisl::Value::from_json(&value).unwrap(); | ||
Write::Put(Record { | ||
did: format!("did:plc:author{:05}", j % AUTHORS), | ||
collection: collection.into(), | ||
rkey: atproto::tid::tid_from(t as u64, 0), | ||
cid: atproto::drisl::cid(&value).to_string(), | ||
record: atproto::drisl::encode(&value), | ||
}) | ||
} | ||
| ||
/// The `j`th play, a minute after the one before, the first at `t0`. | ||
fn play(j: usize, t0: i64) -> Write { | ||
let t = t0 + j as i64 * MINUTE; | ||
let created = atproto::time::iso(t / 1000); | ||
let value = json!({ | ||
"$type": PLAY, | ||
"trackName": format!("track {}", j % 5_000), | ||
"releaseName": format!("release {}", j % 700), | ||
"artists": [{"artistName": format!("artist {}", j % 300)}], | ||
"duration": 180 + j % 120, | ||
"playedTime": created, | ||
"createdAt": created, | ||
}); | ||
record(j, PLAY, t, value) | ||
} | ||
| ||
/// The `j`th favorite, three minutes after the one before. | ||
fn favorite(j: usize, t0: i64) -> Write { | ||
let t = t0 + j as i64 * 3 * MINUTE; | ||
let value = json!({ | ||
"$type": FAVORITE, | ||
"subject": gallery(j % GALLERIES), | ||
"createdAt": atproto::time::iso(t / 1000), | ||
}); | ||
record(j, FAVORITE, t, value) | ||
} | ||
| ||
fn gallery(g: usize) -> String { | ||
format!( | ||
"at://did:plc:author{:05}/social.grain.gallery/{g}", | ||
g % AUTHORS | ||
) | ||
} | ||
| ||
/// One of the collections backfilled: its NSID, how many records, the | ||
/// `j`th of them from the time of the first, and whether it goes slow. | ||
#[derive(Clone, Copy)] | ||
struct Backfilled { | ||
nsid: &'static str, | ||
records: usize, | ||
make: fn(usize, i64) -> Write, | ||
t0: i64, | ||
slow: bool, | ||
} | ||
| ||
impl Backfilled { | ||
/// Writes records `from..to`, made as they go, `BATCH` a call. | ||
fn put(&self, store: &Store, from: usize, to: usize) { | ||
let all: Vec<usize> = (from..to).collect(); | ||
for batch in all.chunks(BATCH) { | ||
let writes: Vec<Write> = batch.iter().map(|&j| (self.make)(j, self.t0)).collect(); | ||
store.backfill(&writes, self.slow).unwrap(); | ||
} | ||
} | ||
} | ||
| ||
fn main() { | ||
let mut args = std::env::args().skip(1).map(|n| n.parse().unwrap()); | ||
let (plays, favorites) = ( | ||
args.next().unwrap_or(PLAYS), | ||
args.next().unwrap_or(FAVORITES), | ||
); | ||
let dir = std::env::temp_dir().join(format!("hud-index-load-{}", std::process::id())); | ||
let store = Arc::new(Store::open(&dir.join("index.db")).unwrap()); | ||
store.spawn_builder(); | ||
// A play a minute and a favorite every three, the last of each now: | ||
// the top releases count a month's. | ||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH); | ||
let now = now.unwrap().as_micros() as i64; | ||
let backfilled = [ | ||
Backfilled { | ||
nsid: PLAY, | ||
records: plays, | ||
make: play, | ||
t0: now - plays as i64 * MINUTE, | ||
slow: true, | ||
}, | ||
Backfilled { | ||
nsid: FAVORITE, | ||
records: favorites, | ||
make: favorite, | ||
t0: now - favorites as i64 * 3 * MINUTE, | ||
slow: false, | ||
}, | ||
]; | ||
// What production held before: a first part in, its tables made. | ||
for b in &backfilled { | ||
b.put(&store, 0, b.records / 10); | ||
} | ||
let authors: Vec<String> = (0..50).map(|i| format!("did:plc:author{i:05}")).collect(); | ||
let specs = [ | ||
("newest", json!({"collection": PLAY}), false), | ||
( | ||
"track", | ||
json!({"collection": PLAY, "where": [{"path": "trackName", "eq": "track 7"}]}), | ||
false, | ||
), | ||
( | ||
"top releases", | ||
json!({"collection": PLAY, "since": "30d", "group": {"by": "releaseName", "top": 10}}), | ||
false, | ||
), | ||
( | ||
"by 50 authors", | ||
json!({"collection": PLAY, "limit": 30}), | ||
true, | ||
), | ||
( | ||
"favorites of", | ||
json!({"collection": FAVORITE, "where": [{"path": "subject", "eq": gallery(7)}]}), | ||
false, | ||
), | ||
( | ||
"new field", | ||
json!({"collection": PLAY, "where": [{"path": "duration", "gt": 290}]}), | ||
false, | ||
), | ||
]; | ||
for (name, spec, _) in &specs[..5] { | ||
let answered = store.answer(&parse(&spec.to_string()).unwrap(), None, None); | ||
assert!(answered.is_ok(), "{name}"); | ||
} | ||
while store.build().unwrap() {} | ||
let writing = Arc::new(AtomicUsize::new(backfilled.len())); | ||
let writers: Vec<_> = backfilled | ||
.iter() | ||
.map(|&b| { | ||
let (store, writing) = (store.clone(), writing.clone()); | ||
std::thread::spawn(move || { | ||
let at = Instant::now(); | ||
b.put(&store, b.records / 10, b.records); | ||
writing.fetch_sub(1, Ordering::SeqCst); | ||
(b.nsid, b.records - b.records / 10, at.elapsed()) | ||
}) | ||
}) | ||
.collect(); | ||
let readers: Vec<_> = specs | ||
.iter() | ||
.cloned() | ||
.map(|(name, spec, by)| { | ||
let (store, writing, authors) = (store.clone(), writing.clone(), authors.clone()); | ||
std::thread::spawn(move || { | ||
let spec = parse(&spec.to_string()).unwrap(); | ||
let (mut took, mut late, mut partial) = (Vec::new(), 0, 0); | ||
while writing.load(Ordering::SeqCst) > 0 { | ||
let at = Instant::now(); | ||
let answer = store | ||
.answer(&spec, by.then_some(&authors[..]), None) | ||
.unwrap(); | ||
took.push(at.elapsed()); | ||
late += usize::from(answer.late); | ||
partial += usize::from(answer.partial); | ||
std::thread::sleep(Duration::from_millis(20)); | ||
} | ||
(name, took, late, partial) | ||
}) | ||
}) | ||
.collect(); | ||
let (mut all, mut longest) = (0, Duration::ZERO); | ||
for writer in writers { | ||
let (nsid, written, took) = writer.join().unwrap(); | ||
let rate = written as f64 / took.as_secs_f64(); | ||
println!("backfilled {written} {nsid} in {took:.1?} ({rate:.0}/s)"); | ||
(all, longest) = (all + written, longest.max(took)); | ||
} | ||
let rate = all as f64 / longest.as_secs_f64(); | ||
println!("backfilled {all} records in {longest:.1?} ({rate:.0}/s), deadline {DEADLINE:?}"); | ||
for reader in readers { | ||
let (name, mut took, late, partial) = reader.join().unwrap(); | ||
took.sort(); | ||
let at = |q: f64| took[((took.len() - 1) as f64 * q) as usize]; | ||
println!( | ||
"{name:>14}: {:>4} answers, p50 {:>9.1?}, p99 {:>9.1?}, slowest {:>9.1?}, {late} late, {partial} partial", | ||
took.len(), | ||
at(0.5), | ||
at(0.99), | ||
took[took.len() - 1] | ||
); | ||
} | ||
drop(store); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
crates/hud-index/src/backfill/tests.rs+256−7
| @@ -491,6 +491,11 @@ struct Mem { | ||
collections: Mutex<Vec<String>>, | ||
/// DIDs in the order their revisions were set. | ||
order: Mutex<Vec<String>>, | ||
/// Collections taken in per author, with how many repositories hold | ||
/// them. | ||
wide: Mutex<HashMap<String, u64>>, | ||
/// How many writes went behind the rest, slow. | ||
slow: Mutex<usize>, | ||
broken: bool, | ||
} | ||
| ||
| @@ -549,6 +554,11 @@ impl Sink for Mem { | ||
Ok(()) | ||
} | ||
| ||
fn backfill(&self, writes: &[Write], slow: bool) -> Result<(), String> { | ||
*self.slow.lock().unwrap() += usize::from(slow) * writes.len(); | ||
self.apply(writes) | ||
} | ||
| ||
fn drop_repo(&self, did: &str, collection: Option<&str>) -> Result<(), String> { | ||
self.check()?; | ||
let collection = collection.unwrap(); | ||
| @@ -612,6 +622,25 @@ impl Sink for Mem { | ||
self.collections.lock().unwrap().clone() | ||
} | ||
| ||
fn records(&self, collection: &str) -> u64 { | ||
let records = self.records.lock().unwrap(); | ||
records.keys().filter(|(_, c, _)| c == collection).count() as u64 | ||
} | ||
| ||
fn wide(&self, collection: &str) -> Option<u64> { | ||
self.wide.lock().unwrap().get(collection).copied() | ||
} | ||
| ||
fn set_wide(&self, collection: &str, repos: Option<u64>) -> Result<(), String> { | ||
self.check()?; | ||
let mut wide = self.wide.lock().unwrap(); | ||
match repos { | ||
Some(n) => wide.insert(collection.into(), n), | ||
None => wide.remove(collection), | ||
}; | ||
Ok(()) | ||
} | ||
| ||
fn cursor(&self) -> Option<i64> { | ||
None | ||
} | ||
| @@ -640,7 +669,12 @@ fn the_default_settings_are_the_networks_own() { | ||
assert_eq!(s.relay, "https://relay1.us-east.bsky.network"); | ||
assert_eq!(s.hubble.as_deref(), Some("https://hubble.microcosm.blue")); | ||
assert_eq!(s.skip_hosts, ["atproto.brid.gy"]); | ||
assert_eq!((s.per_host, s.at_once, s.heavy), (8, 64, 2_000)); | ||
assert_eq!((s.per_host, s.at_once, s.heavy), (8, 16, 2_000)); | ||
assert_eq!( | ||
(s.max_repos, s.slow_records, s.slow_at_once), | ||
(20_000, 250_000, 4) | ||
); | ||
assert!(s.large.is_empty()); | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
| @@ -674,7 +708,8 @@ async fn a_collection_backfills_every_listed_repo_and_is_marked_complete() { | ||
repos: 6, | ||
done: 6, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
assert_eq!(sink.collections(), [GALLERY]); | ||
| @@ -843,7 +878,8 @@ async fn priority_repos_land_first_and_repos_answers_by_its_deadline() { | ||
repos: 10, | ||
done: 10, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
for d in listed.iter().chain([&did(8)]) { | ||
| @@ -941,7 +977,8 @@ async fn a_failing_pds_is_retried_then_left_without_a_rev_while_the_rest_complet | ||
repos: 8, | ||
done: 8, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
assert_eq!(sink.rev_of(&did(0)), Some(rev(1))); | ||
| @@ -1015,7 +1052,8 @@ async fn resuming_reads_only_repos_without_a_rev() { | ||
repos: 4, | ||
done: 4, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
assert_eq!( | ||
| @@ -1024,7 +1062,8 @@ async fn resuming_reads_only_repos_without_a_rev() { | ||
repos: 2, | ||
done: 2, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
let comment = bf.progress("social.grain.comment"); | ||
| @@ -1034,7 +1073,8 @@ async fn resuming_reads_only_repos_without_a_rev() { | ||
repos: 2, | ||
done: 2, | ||
complete: true, | ||
finding: false | ||
finding: false, | ||
..Progress::default() | ||
} | ||
); | ||
for d in &listed[..2] { | ||
| @@ -1266,3 +1306,212 @@ async fn repos_waits_no_more_on_a_repo_whose_read_ended_unread_even_after_a_rest | ||
until(|| sink.unread(&did(0), GALLERY).is_none()).await; | ||
assert_eq!(sink.rev_of(&did(0)), Some(rev(1))); | ||
} | ||
| ||
/// What a backfill told of how it takes each collection in. | ||
fn tells(bf: &Arc<Backfill>) -> Arc<Mutex<Vec<(String, bool)>>> { | ||
let told = Arc::new(Mutex::new(Vec::new())); | ||
let tell = told.clone(); | ||
bf.scoped(Arc::new(move |c: &str, whole: bool| { | ||
tell.lock().unwrap().push((c.to_string(), whole)) | ||
})); | ||
told | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
async fn a_collection_held_too_widely_is_taken_in_per_author() { | ||
let f = fakes().await; | ||
let listed: Vec<String> = (0..52).map(did).collect(); | ||
for d in &listed { | ||
f.world.add(d, repo(&f.a, 2)); | ||
} | ||
f.world.list(GALLERY, &listed); | ||
let sink = Arc::new(Mem::default()); | ||
let settings = Settings { | ||
max_repos: 3, | ||
per_host: 64, | ||
..f.settings() | ||
}; | ||
let bf = f.backfill(&sink, settings.clone()); | ||
let told = tells(&bf); | ||
| ||
bf.collection(GALLERY); | ||
until(|| bf.progress(GALLERY).wide).await; | ||
| ||
// Counted past three, two pages in: none read, the rest unlisted. | ||
let wide = Progress { | ||
repos: 4, | ||
wide: true, | ||
..Progress::default() | ||
}; | ||
assert_eq!(bf.progress(GALLERY), wide); | ||
assert_eq!(sink.wide(GALLERY), Some(4)); | ||
assert_eq!(*told.lock().unwrap(), [(GALLERY.to_string(), false)]); | ||
assert_eq!(f.world.asked("listReposByCollection", ""), 2); | ||
assert!( | ||
listed | ||
.iter() | ||
.all(|d| f.world.asked("getLatestCommit", d) == 0) | ||
); | ||
// The authors a spec names are read, fifty at most at once. | ||
assert_eq!(bf.repos(&listed, GALLERY, soon()).await, AUTHORS); | ||
let read = listed | ||
.iter() | ||
.filter(|d| f.world.asked("getLatestCommit", d) == 1); | ||
assert_eq!(read.count(), AUTHORS); | ||
assert_eq!(bf.repos(&listed, GALLERY, soon()).await, 52); | ||
| ||
// Started again, it is not listed again. | ||
let bf = f.backfill(&sink, settings.clone()); | ||
let told = tells(&bf); | ||
bf.collection(GALLERY); | ||
assert_eq!(bf.progress(GALLERY), wide); | ||
assert_eq!(*told.lock().unwrap(), [(GALLERY.to_string(), false)]); | ||
assert_eq!(f.world.asked("listReposByCollection", ""), 2); | ||
| ||
// Unless the operator takes it in whole: then it is listed and read | ||
// whole, its pages as they come. | ||
let large = Settings { | ||
large: vec![GALLERY.into()], | ||
..settings | ||
}; | ||
let bf = f.backfill(&sink, large); | ||
let told = tells(&bf); | ||
bf.collection(GALLERY); | ||
until(|| bf.progress(GALLERY).complete).await; | ||
assert_eq!(sink.wide(GALLERY), None); | ||
assert_eq!(bf.progress(GALLERY).repos, 52); | ||
assert_eq!(*told.lock().unwrap(), [(GALLERY.to_string(), true)]); | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
async fn a_collection_listed_whole_is_told_so() { | ||
let f = fakes().await; | ||
f.world.add(&did(0), repo(&f.a, 2)); | ||
f.world.list(GALLERY, &[did(0)]); | ||
let sink = Arc::new(Mem::default()); | ||
let bf = f.backfill(&sink, f.settings()); | ||
let told = tells(&bf); | ||
bf.collection(GALLERY); | ||
until(|| bf.progress(GALLERY).complete).await; | ||
assert_eq!(*told.lock().unwrap(), [(GALLERY.to_string(), true)]); | ||
// Told once. | ||
bf.scoped(Arc::new(|_: &str, _: bool| unreachable!())); | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
async fn a_big_collection_goes_slow_behind_the_rest_and_still_completes() { | ||
let f = fakes().await; | ||
let listed: Vec<String> = (0..6).map(did).collect(); | ||
for d in &listed { | ||
let mut r = repo(&f.a, 3); | ||
r.delay = Duration::from_millis(20); | ||
f.world.add(d, r); | ||
} | ||
f.world.list(GALLERY, &listed); | ||
let sink = Arc::new(Mem::default()); | ||
let settings = Settings { | ||
at_once: 1, | ||
slow_at_once: 1, | ||
slow_records: 3, | ||
..f.settings() | ||
}; | ||
let bf = f.backfill(&sink, settings.clone()); | ||
| ||
bf.collection(GALLERY); | ||
until(|| bf.progress(GALLERY).complete).await; | ||
| ||
// The first in, it went slow: the rest were written behind every other | ||
// collection's, one at a time. | ||
let progress = bf.progress(GALLERY); | ||
assert!(progress.slow && progress.done == 6, "{progress:?}"); | ||
assert_eq!(*sink.slow.lock().unwrap(), 5 * 3); | ||
assert_eq!(f.world.flying.lock().unwrap().most_all, 1); | ||
for d in &listed { | ||
assert_eq!(sink.held(d), f.galleries(d), "{d}"); | ||
} | ||
// Held past its limit already, it is slow from the start; a read a | ||
// tile waits on is not. | ||
let mut more = listed.clone(); | ||
more.push(did(11)); | ||
f.world.add(&did(11), repo(&f.a, 3)); | ||
f.world.list(GALLERY, &more); | ||
sink.complete.lock().unwrap().clear(); | ||
let bf = f.backfill(&sink, settings); | ||
bf.collection(GALLERY); | ||
assert!(bf.progress(GALLERY).slow); | ||
bf.resync(&did(0)); | ||
until(|| bf.progress(GALLERY).complete && *sink.slow.lock().unwrap() == 7 * 3).await; | ||
assert_eq!(sink.held(&did(11)), f.galleries(&did(11))); | ||
f.world.add(&did(9), repo(&f.a, 3)); | ||
assert_eq!(bf.repos(&[did(9)], GALLERY, soon()).await, 1); | ||
assert_eq!(*sink.slow.lock().unwrap(), 7 * 3); | ||
// One never taken in never goes slow. | ||
let follows = "app.bsky.graph.follow"; | ||
let mut r = repo(&f.a, 0); | ||
for i in 0..3 { | ||
r.records | ||
.push((follows.into(), rkey(i), json!({"subject": did(i)}))); | ||
} | ||
f.world.add(&did(10), r); | ||
assert_eq!(bf.repos(&[did(10)], follows, soon()).await, 1); | ||
assert_eq!(sink.records(follows), 3); | ||
assert!(!bf.progress(follows).slow); | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
async fn paused_reads_wait_until_let_go_on() { | ||
let f = fakes().await; | ||
f.world.add(&did(0), repo(&f.a, 2)); | ||
let sink = Arc::new(Mem::default()); | ||
let bf = f.backfill(&sink, f.settings()); | ||
assert!(!bf.paused()); | ||
assert!(bf.pause(true)); | ||
assert!(!bf.pause(true)); | ||
assert!(bf.paused()); | ||
let reading = { | ||
let bf = bf.clone(); | ||
tokio::spawn(async move { bf.repos(&[did(0)], GALLERY, soon()).await }) | ||
}; | ||
tokio::time::sleep(Duration::from_millis(200)).await; | ||
assert_eq!(f.world.asked("getLatestCommit", &did(0)), 0); | ||
assert!(!bf.idle()); | ||
assert!(bf.pause(false)); | ||
assert_eq!(reading.await.unwrap(), 1); | ||
until(|| bf.idle()).await; | ||
} | ||
| ||
#[tokio::test(flavor = "multi_thread")] | ||
async fn an_expired_collection_is_forgotten_and_taken_in_anew() { | ||
let f = fakes().await; | ||
let listed: Vec<String> = (0..3).map(did).collect(); | ||
for d in &listed { | ||
let mut r = repo(&f.a, 2); | ||
r.delay = Duration::from_millis(200); | ||
f.world.add(d, r); | ||
} | ||
f.world.list(GALLERY, &listed); | ||
*f.world.relay_delay.lock().unwrap() = Duration::from_millis(100); | ||
let sink = Arc::new(Mem::default()); | ||
let settings = Settings { | ||
at_once: 1, | ||
..f.settings() | ||
}; | ||
let bf = f.backfill(&sink, settings); | ||
assert!(!bf.busy(GALLERY)); | ||
| ||
bf.collection(GALLERY); | ||
// Listed, then read one at a time: busy while either goes on. | ||
assert!(bf.busy(GALLERY)); | ||
until(|| f.world.asked("getLatestCommit", &did(0)) == 1).await; | ||
assert!(bf.busy(GALLERY)); | ||
// Expired, the reads not started are forgotten; the one running ends. | ||
bf.expired(GALLERY); | ||
assert_eq!(bf.progress(GALLERY), Progress::default()); | ||
until(|| bf.idle()).await; | ||
assert!(!bf.busy(GALLERY)); | ||
assert_eq!(f.world.asked("getLatestCommit", &did(2)), 0); | ||
// Asked for again, it is listed again. | ||
bf.collection(GALLERY); | ||
until(|| bf.progress(GALLERY).complete).await; | ||
assert_eq!(f.world.asked("listReposByCollection", ""), 4); | ||
} | ||
crates/hud-index/src/live/tests.rs+69−0
| @@ -25,6 +25,8 @@ struct State { | ||
cursor: Option<i64>, | ||
cursors_saved: usize, | ||
dropped: Vec<String>, | ||
/// Collections taken in per author. | ||
wide: Vec<String>, | ||
fail: bool, | ||
} | ||
| ||
| @@ -74,6 +76,9 @@ impl Sink for Memory { | ||
} | ||
Ok(()) | ||
} | ||
fn backfill(&self, _: &[Write], _: bool) -> Result<(), String> { | ||
unreachable!("the live stream never backfills") | ||
} | ||
fn drop_repo(&self, did: &str, collection: Option<&str>) -> Result<(), String> { | ||
assert_eq!(collection, None); | ||
let mut state = self.changed()?; | ||
| @@ -109,6 +114,19 @@ impl Sink for Memory { | ||
fn collections(&self) -> Vec<String> { | ||
self.state().collections.clone() | ||
} | ||
fn records(&self, _: &str) -> u64 { | ||
unreachable!("the live stream never counts") | ||
} | ||
fn wide(&self, collection: &str) -> Option<u64> { | ||
self.state() | ||
.wide | ||
.iter() | ||
.any(|c| c == collection) | ||
.then_some(20_001) | ||
} | ||
fn set_wide(&self, _: &str, _: Option<u64>) -> Result<(), String> { | ||
unreachable!("the live stream never counts") | ||
} | ||
fn cursor(&self) -> Option<i64> { | ||
self.state().cursor | ||
} | ||
| @@ -722,3 +740,54 @@ async fn writes_that_cannot_be_kept_are_skipped_and_failures_logged() { | ||
assert!(sink.state().dropped.is_empty()); | ||
assert_eq!(sink.cursor(), Some(2)); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_collection_taken_in_per_author_keeps_its_authors_writes_alone() { | ||
let mut fake = Fake::start().await; | ||
let sink = Memory::holding(&["a.b.c", "p.q.r"]); | ||
sink.state().wide.push("p.q.r".into()); | ||
sink.set_rev(A, "p.q.r", "3m1").unwrap(); | ||
let (live, _) = live(&sink, &Arc::new(Handoff::new()), vec![fake.url.clone()]); | ||
let conn = fake.next().await; | ||
assert_eq!(conn.asked("collections"), ["a.b.c", "p.q.r"]); | ||
let gallery = |n: &str| Some(gallery(n)); | ||
conn.send(commit_to(1, B, "create", "p.q.r", "1", "3m2", gallery("b"))); | ||
conn.send(commit_to(2, A, "create", "p.q.r", "1", "3m2", gallery("a"))); | ||
until("the author's write", || { | ||
sink.record(A, "p.q.r", "1").is_some() | ||
}) | ||
.await; | ||
assert_eq!(sink.record(B, "p.q.r", "1"), None); | ||
| ||
// Found too widely held, a collection followed whole is narrowed. | ||
let scoped = live.scoped(); | ||
scoped("a.b.c", false); | ||
let conn = fake.next().await; | ||
assert_eq!(conn.asked("collections"), ["a.b.c", "p.q.r"]); | ||
conn.send(commit(3, B, "create", "1", "3m3", gallery("unheld"))); | ||
conn.send(commit_to(4, A, "create", "p.q.r", "2", "3m3", gallery("a"))); | ||
until("the next write", || sink.record(A, "p.q.r", "2").is_some()).await; | ||
assert_eq!(sink.record(B, "a.b.c", "1"), None); | ||
scoped("a.b.c", false); | ||
assert!( | ||
fake.quiet().await, | ||
"a narrowed collection was narrowed again" | ||
); | ||
// Found few enough to take in whole, followed whole. | ||
scoped("x.y.z", true); | ||
let conn = fake.next().await; | ||
assert_eq!(conn.asked("collections"), ["a.b.c", "p.q.r", "x.y.z"]); | ||
| ||
// Expired, no longer followed. | ||
live.unfollow(&["x.y.z".into(), "p.q.r".into()]); | ||
let conn = fake.next().await; | ||
assert_eq!(conn.asked("collections"), ["a.b.c"]); | ||
live.unfollow(&["x.y.z".into()]); | ||
assert!( | ||
fake.quiet().await, | ||
"a collection not followed was unfollowed" | ||
); | ||
// Once the stream is gone, nothing is told. | ||
drop(live); | ||
scoped("m.n.o", true); | ||
} | ||
crates/hud-index/src/server/tests.rs+183−9
| @@ -12,19 +12,23 @@ use tower::ServiceExt; | ||
| ||
const GALLERY: &str = "social.grain.gallery"; | ||
const FOLLOW: &str = "app.bsky.graph.follow"; | ||
const POST: &str = "app.bsky.feed.post"; | ||
const A: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"; | ||
const B: &str = "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb"; | ||
const C: &str = "did:plc:cccccccccccccccccccccccc"; | ||
const VIEWER: &str = "did:plc:vvvvvvvvvvvvvvvvvvvvvvvv"; | ||
| ||
/// A relay listing A, B and C as holding galleries, and no repository | ||
/// holding anything else: its URL. | ||
/// A relay listing A, B and C as holding galleries, five accounts as | ||
/// holding posts, past the four `index` takes a collection in whole from, | ||
/// and no repository holding anything else: its URL. | ||
async fn relay() -> String { | ||
let listing = |Query(q): Query<HashMap<String, String>>| async move { | ||
let repos: Vec<Value> = match q.get("collection").map(String::as_str) { | ||
Some(GALLERY) => [A, B, C].iter().map(|d| json!({ "did": d })).collect(), | ||
let dids: Vec<String> = match q.get("collection").map(String::as_str) { | ||
Some(GALLERY) => [A, B, C].map(String::from).to_vec(), | ||
Some(POST) => (0..5).map(|i| format!("did:plc:poster{i}")).collect(), | ||
_ => Vec::new(), | ||
}; | ||
let repos: Vec<Value> = dids.iter().map(|d| json!({ "did": d })).collect(); | ||
axum::Json(json!({ "repos": repos })) | ||
}; | ||
let app = Router::new().route("/xrpc/com.atproto.sync.listReposByCollection", get(listing)); | ||
| @@ -84,11 +88,15 @@ fn put(did: &str, collection: &str, rkey: &str, value: Value) -> Write { | ||
/// collection complete, and the viewer's follows of A and B: its | ||
/// directory and the index, started as `hud index` starts it. | ||
async fn index() -> (PathBuf, Arc<Index>) { | ||
index_at(None).await | ||
index_with(None, |_| {}).await | ||
} | ||
| ||
/// [`index`], its live stream resuming from `cursor` where given. | ||
async fn index_at(cursor: Option<i64>) -> (PathBuf, Arc<Index>) { | ||
/// `index`, A's post held too, its live stream resuming from `cursor` | ||
/// where given and its settings as `set` leaves them. | ||
async fn index_with( | ||
cursor: Option<i64>, | ||
set: impl FnOnce(&mut crate::Settings), | ||
) -> (PathBuf, Arc<Index>) { | ||
let dir = std::env::temp_dir().join(format!("hud-index-server-{}", atproto::jose::random(6))); | ||
std::fs::create_dir_all(&dir).unwrap(); | ||
let db = dir.join("index.db"); | ||
| @@ -104,27 +112,36 @@ async fn index_at(cursor: Option<i64>) -> (PathBuf, Arc<Index>) { | ||
put(B, GALLERY, "3kccccccccc22", json!({"title": "More film", "camera": "Leica", "photos": 12, "createdAt": "2026-03-01T00:00:00Z"})), | ||
put(VIEWER, FOLLOW, "3kddddddddd22", json!({"subject": A, "createdAt": "2026-01-01T00:00:00Z"})), | ||
put(VIEWER, FOLLOW, "3keeeeeeeee22", json!({"subject": B, "createdAt": "2026-01-01T00:00:00Z"})), | ||
put(A, POST, "3kfffffffff22", json!({"text": "hello", "createdAt": "2026-01-01T00:00:00Z"})), | ||
]) | ||
.unwrap(); | ||
for did in [A, B, C] { | ||
store.set_rev(did, GALLERY, "3kzzzzzzzzz22").unwrap(); | ||
} | ||
store.set_rev(VIEWER, FOLLOW, "3kzzzzzzzzz22").unwrap(); | ||
store.set_rev(A, POST, "3kzzzzzzzzz22").unwrap(); | ||
store.add_collection(GALLERY).unwrap(); | ||
store.set_complete(GALLERY).unwrap(); | ||
} | ||
let settings = crate::Settings { | ||
let mut settings = crate::Settings { | ||
origin: "http://localhost:8790".into(), | ||
db, | ||
readers: crate::store::READERS, | ||
backfill: crate::backfill::Settings { | ||
relay: relay().await, | ||
hubble: None, | ||
max_repos: 4, | ||
..Default::default() | ||
}, | ||
live: crate::live::Settings { | ||
jetstreams: Vec::new(), | ||
}, | ||
sweep: crate::sweep::Settings { | ||
min_free: 0, | ||
..Default::default() | ||
}, | ||
}; | ||
set(&mut settings); | ||
let index = crate::start(hud(&dir), settings).unwrap(); | ||
(dir, index) | ||
} | ||
| @@ -315,7 +332,7 @@ async fn counts_each_collection_and_the_live_streams_lag() { | ||
let (_dir, index) = index().await; | ||
assert!(!index.metrics().contains("hud_index_live_lag_seconds")); | ||
let ago = 5_000_000; | ||
let (_dir, index) = index_at(Some(crate::store::now_micros() - ago)).await; | ||
let (_dir, index) = index_with(Some(crate::store::now_micros() - ago), |_| {}).await; | ||
// Read between two statuses that agree, as the backfill moves on. | ||
let (status, text) = loop { | ||
let (_, before) = get_json(&index, "/xrpc/place.hud.index.getStatus").await; | ||
| @@ -452,10 +469,167 @@ async fn refuses_to_start_on_a_store_it_cannot_open() { | ||
let settings = crate::Settings { | ||
origin: "http://localhost:8790".into(), | ||
db: dir.join("file").join("index.db"), | ||
readers: crate::store::READERS, | ||
backfill: Default::default(), | ||
live: crate::live::Settings { | ||
jetstreams: Vec::new(), | ||
}, | ||
sweep: Default::default(), | ||
}; | ||
assert!(crate::start(hud(&dir), settings).is_err()); | ||
} | ||
| ||
/// getStatus, once `done` holds of it. | ||
async fn status_until(index: &Arc<Index>, done: impl Fn(&Value) -> bool) -> Value { | ||
let deadline = Instant::now() + Duration::from_secs(10); | ||
loop { | ||
let (_, status) = get_json(index, "/xrpc/place.hud.index.getStatus").await; | ||
if done(&status) { | ||
return status; | ||
} | ||
assert!(Instant::now() < deadline, "never came: {status}"); | ||
tokio::time::sleep(Duration::from_millis(20)).await; | ||
} | ||
} | ||
| ||
/// What getStatus says of `collection`. | ||
fn held<'a>(status: &'a Value, collection: &str) -> Option<&'a Value> { | ||
let held = status["collections"].as_array().unwrap(); | ||
held.iter().find(|c| c["collection"] == collection) | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_collection_held_too_widely_answers_by_author() { | ||
let (_dir, index) = index().await; | ||
let spec = format!(r#"{{"collection":"{POST}"}}"#); | ||
ask(&index, &[("spec", &spec), ("wait", "0")]).await; | ||
let wide = |s: &Value| held(s, POST).is_some_and(|c| c["indexed"] == "perAuthor"); | ||
let status = status_until(&index, wide).await; | ||
let post = held(&status, POST).unwrap(); | ||
assert_eq!( | ||
(&post["repos"], &post["reposIn"], &post["complete"]), | ||
(&json!(5), &json!(1), &json!(false)) | ||
); | ||
// Naming nobody, it answers from the authors read in, partial, saying | ||
// why. | ||
let (_, answer) = ask(&index, &[("spec", &spec), ("wait", "0")]).await; | ||
assert_eq!(answer["records"][0]["value"]["text"], "hello"); | ||
let said = |a: &Value| { | ||
let keys = ["partial", "partialReason", "complete", "repos", "reposIn"]; | ||
keys.map(|k| a[k].clone()) | ||
}; | ||
let per_author = [ | ||
json!(true), | ||
json!("perAuthor"), | ||
json!(false), | ||
json!(5), | ||
json!(1), | ||
]; | ||
assert_eq!(said(&answer), per_author); | ||
// Naming its authors, those are read, and it is complete once they are. | ||
let by = format!(r#"{{"collection":"{POST}","by":["{A}"]}}"#); | ||
let (_, answer) = ask(&index, &[("spec", &by), ("wait", "0")]).await; | ||
let whole = [json!(false), Value::Null, json!(true), json!(1), json!(1)]; | ||
assert_eq!(said(&answer), whole); | ||
let by = format!(r#"{{"collection":"{POST}","by":["{A}","{B}"]}}"#); | ||
let (_, answer) = ask(&index, &[("spec", &by), ("wait", "0")]).await; | ||
let half = [json!(false), Value::Null, json!(false), json!(2), json!(1)]; | ||
assert_eq!(said(&answer), half); | ||
} | ||
| ||
#[tokio::test] | ||
async fn the_status_says_how_each_collection_is_taken_in_and_when_it_was_asked_for() { | ||
let (_dir, index) = index().await; | ||
let status = status_until(&index, |s| held(s, GALLERY).is_some()).await; | ||
let gallery = held(&status, GALLERY).unwrap(); | ||
assert_eq!(gallery["indexed"], "whole"); | ||
assert_eq!( | ||
(&gallery["slow"], &gallery["records"]), | ||
(&json!(false), &json!(3)) | ||
); | ||
assert!(gallery["lastAsked"].as_str().unwrap().starts_with("20")); | ||
assert_eq!(status["paused"], false); | ||
} | ||
| ||
#[tokio::test] | ||
async fn an_answer_out_of_time_or_filling_says_so() { | ||
let (_dir, index) = index().await; | ||
let spec = spec::parse(r#"{"collection":"social.grain.gallery"}"#).unwrap(); | ||
let version = index.store.version(&spec); | ||
let late = Answer { | ||
partial: true, | ||
late: true, | ||
..Answer::default() | ||
}; | ||
let out = answer_json(&index, &spec, late, &version, None); | ||
OUTPUTS | ||
.validate("place.hud.index.query#output", &out) | ||
.unwrap(); | ||
assert_eq!(out["partialReason"], "deadline"); | ||
// Told apart from the answer that next reads the same. | ||
assert!(out["version"].as_str().unwrap().ends_with(".late")); | ||
let filling = Answer { | ||
partial: true, | ||
..Answer::default() | ||
}; | ||
let out = answer_json(&index, &spec, filling, &version, None); | ||
OUTPUTS | ||
.validate("place.hud.index.query#output", &out) | ||
.unwrap(); | ||
assert_eq!(out["partialReason"], "filling"); | ||
assert_eq!(out["version"], version.mark(true)); | ||
} | ||
| ||
#[tokio::test] | ||
async fn the_sweep_pauses_backfills_on_a_short_disk_and_drops_what_nobody_asks_for() { | ||
// Short of disk, every backfill pauses from the first sweep. | ||
let (_short, short) = index_with(None, |s| s.sweep.min_free = u64::MAX).await; | ||
status_until(&short, |s| s["paused"] == true).await; | ||
let (dir, index) = index().await; | ||
status_until(&index, |s| { | ||
held(s, GALLERY).is_some_and(|c| c["complete"] == true) | ||
}) | ||
.await; | ||
// With room, a pause is let go. | ||
index.backfill.pause(true); | ||
let now = crate::store::now_micros(); | ||
index.sweep(now).await; | ||
assert!(!index.backfill.paused()); | ||
// While a read is under way, the WAL is left. | ||
let by = format!(r#"{{"collection":"{GALLERY}","by":["did:plc:unknownunknownunknownu"]}}"#); | ||
ask(&index, &[("spec", &by), ("wait", "0")]).await; | ||
index.sweep(now).await; | ||
// A month on, nothing asked for since, all of it goes. | ||
let month = 30 * 24 * 60 * 60 * 1_000_000; | ||
status_until(&index, |_| index.backfill.idle()).await; | ||
index.sweep(now + month).await; | ||
let status = status_until(&index, |s| s["collections"] == json!([])).await; | ||
assert_eq!(status["paused"], false); | ||
assert!(index.store.partial_collections().is_empty()); | ||
// Asked for again, a collection is taken in anew. | ||
let spec = r#"{"collection":"social.grain.gallery"}"#; | ||
let (_, answer) = ask(&index, &[("spec", spec), ("wait", "0")]).await; | ||
assert_eq!(answer["records"], json!([])); | ||
status_until(&index, |s| held(s, GALLERY).is_some()).await; | ||
// A sweep that fails is said, and the next tries again. | ||
let db = rusqlite::Connection::open(dir.join("index.db")).unwrap(); | ||
db.execute_batch("ALTER TABLE fields RENAME TO lost") | ||
.unwrap(); | ||
index.sweep(now).await; | ||
db.execute_batch("ALTER TABLE lost RENAME TO fields") | ||
.unwrap(); | ||
index.sweep(now).await; | ||
} | ||
| ||
#[tokio::test] | ||
async fn the_sweep_ends_with_its_index() { | ||
let (dir, index) = index_with(None, |s| s.sweep.every = Duration::from_millis(10)).await; | ||
tokio::time::sleep(Duration::from_millis(50)).await; | ||
drop(index); | ||
tokio::time::sleep(Duration::from_millis(50)).await; | ||
let free = crate::sweep::free_bytes(&dir.join("index.db")); | ||
assert!(free.is_some_and(|n| n > 0)); | ||
let nowhere = std::path::Path::new("/nowhere/at/all/index.db"); | ||
assert_eq!(crate::sweep::free_bytes(nowhere), None); | ||
assert_eq!(crate::sweep::free_bytes(std::path::Path::new("/")), None); | ||
} | ||
crates/hud-index/src/backfill.rs+302−66
| @@ -15,6 +15,13 @@ | ||
//! at every limit. A read whose servers cannot answer is tried again after | ||
//! a wait (as long as a rate limit asks, up to `LIMITED_MOST`), a few | ||
//! times, then left without a revision. | ||
//! | ||
//! A collection is counted before it is read: past `Settings::max_repos` | ||
//! repositories holding it, the relay's listing stops and it is taken in | ||
//! per author, only the repositories a spec names (`repos`) read and kept | ||
//! current. One held past `Settings::slow_records` records goes slow: its | ||
//! reads few at once and its writes behind every other's. While the disk | ||
//! runs short (`pause`), no read starts. | ||
| ||
use crate::handoff::{Handoff, Held}; | ||
use crate::sink::{Record, Sink, Write}; | ||
| @@ -29,13 +36,15 @@ use hud_core::telemetry::spawn; | ||
use std::borrow::Cow; | ||
use std::collections::{HashMap, HashSet, VecDeque}; | ||
use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; | ||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; | ||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; | ||
use std::time::{Duration, SystemTime, UNIX_EPOCH}; | ||
use tokio::sync::Notify; | ||
use tokio::sync::{Notify, watch}; | ||
use tokio::time::Instant; | ||
use url::Url; | ||
| ||
/// Writes given the sink in one transaction. | ||
/// Writes given the sink in one call: one transaction, but committed | ||
/// after the part being written where a write ahead of the backfill's (an | ||
/// answer's tables, the live stream's) comes to wait (`store::PART`). | ||
const BATCH: usize = 1000; | ||
/// How many times a read is tried while its servers cannot answer. | ||
const TRIES: u32 = 3; | ||
| @@ -44,8 +53,8 @@ const BACKOFF: Duration = Duration::from_millis(250); | ||
/// The longest a read waits before trying again where its server asked to | ||
/// be left longer (a rate limit's `Retry-After`). | ||
const LIMITED_MOST: Duration = Duration::from_secs(60); | ||
/// How long a request has to answer whole. | ||
const WAIT: Duration = Duration::from_secs(30); | ||
/// How long a request has to answer whole, before it is tried again. | ||
const WAIT: Duration = Duration::from_secs(10); | ||
/// How long an archive has to arrive whole. | ||
const ARCHIVE_WAIT: Duration = Duration::from_secs(600); | ||
/// The most bytes of an answer read: a page of records, or of the relay's | ||
| @@ -57,6 +66,9 @@ const LISTING_WAIT: Duration = Duration::from_millis(300); | ||
/// How long a repository whose read ended unread goes before `repos` reads | ||
/// it again, in the background. | ||
const UNREAD_AGAIN: Duration = Duration::from_secs(300); | ||
/// The most repositories of a collection taken in per author one `repos` | ||
/// starts reading. | ||
pub const AUTHORS: usize = 50; | ||
| ||
/// Where the backfill reads from, and how hard. | ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
| @@ -77,19 +89,34 @@ pub struct Settings { | ||
/// Past this many records of a collection, a repository is read from | ||
/// Hubble. | ||
pub heavy: usize, | ||
/// Past this many repositories the relay lists with a collection, it | ||
/// is taken in per author. | ||
pub max_repos: usize, | ||
/// Collections taken in whole however many repositories hold them. | ||
pub large: Vec<String>, | ||
/// Past this many records held of a collection, its backfill goes | ||
/// slow. | ||
pub slow_records: u64, | ||
/// The most repositories of slow collections read at once. | ||
pub slow_at_once: usize, | ||
} | ||
| ||
impl Default for Settings { | ||
/// Bluesky's relay, microcosm's Hubble, Bridgy Fed skipped, 8 requests | ||
/// a host, 64 at once, Hubble past 2,000 records. | ||
/// a host, 16 at once, Hubble past 2,000 records, per author past | ||
/// 20,000 repositories, slow past 250,000 records, 4 at once. | ||
fn default() -> Settings { | ||
Settings { | ||
relay: "https://relay1.us-east.bsky.network".into(), | ||
hubble: Some("https://hubble.microcosm.blue".into()), | ||
skip_hosts: vec!["atproto.brid.gy".into()], | ||
per_host: 8, | ||
at_once: 64, | ||
at_once: 16, | ||
heavy: 2_000, | ||
max_repos: 20_000, | ||
large: Vec::new(), | ||
slow_records: 250_000, | ||
slow_at_once: 4, | ||
} | ||
} | ||
} | ||
| @@ -98,15 +125,24 @@ impl Default for Settings { | ||
/// listed so far, how many of them were read or found read already (or | ||
/// tried and left), whether all were, so the sink holds it complete, and | ||
/// whether the relay is listing them still (`finding`: `repos` is then how | ||
/// many it listed so far, not their total). | ||
/// many it listed so far, not their total); whether it is taken in per | ||
/// author (`wide`: `repos` is then how many the relay had listed when it | ||
/// stopped), and whether it goes slow. | ||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | ||
pub struct Progress { | ||
pub repos: usize, | ||
pub done: usize, | ||
pub complete: bool, | ||
pub finding: bool, | ||
pub wide: bool, | ||
pub slow: bool, | ||
} | ||
| ||
/// What the backfill tells of a collection once its listing finds it held | ||
/// by few enough repositories to take in whole (`true`), or too many | ||
/// (`false`): the live stream follows it so. | ||
pub type Scoped = Arc<dyn Fn(&str, bool) + Send + Sync>; | ||
| ||
/// The backfill of the collections tiles ask for. | ||
pub struct Backfill { | ||
hud: Arc<Hud>, | ||
| @@ -120,6 +156,10 @@ pub struct Backfill { | ||
state: Mutex<State>, | ||
/// Woken as each read ends, for `repos`. | ||
ended: Notify, | ||
/// Told how each collection is taken in (`scoped`). | ||
scoped: OnceLock<Scoped>, | ||
/// Whether reads wait to start (`pause`). | ||
paused: watch::Sender<bool>, | ||
} | ||
| ||
#[derive(Default)] | ||
| @@ -130,28 +170,48 @@ struct State { | ||
queue: VecDeque<Arc<Job>>, | ||
/// Reads taken from the queue and running. | ||
running: usize, | ||
/// Reads of slow collections, waiting for one of `slow_at_once` slots, | ||
/// and those running. | ||
slow: VecDeque<Arc<Job>>, | ||
slow_running: usize, | ||
/// The collections whose backfill started, and how far each came. | ||
collections: HashMap<String, Listing>, | ||
} | ||
| ||
impl State { | ||
/// Queues a read of `did`'s `collection`, ahead of the rest if `first`. | ||
fn queue(&mut self, did: &str, collection: &str, first: bool) { | ||
/// Queues a read of `did`'s `collection`, ahead of the rest if `first`, | ||
/// with the slow collections' if `slow`. | ||
fn queue(&mut self, did: &str, collection: &str, first: bool, slow: bool) { | ||
let job = Arc::new(Job::new(did, collection)); | ||
let key = (did.to_string(), collection.to_string()); | ||
self.pending.insert(key, job.clone()); | ||
let queue = if slow { | ||
&mut self.slow | ||
} else { | ||
&mut self.queue | ||
}; | ||
match first { | ||
true => self.queue.push_front(job), | ||
false => self.queue.push_back(job), | ||
true => queue.push_front(job), | ||
false => queue.push_back(job), | ||
} | ||
} | ||
} | ||
| ||
/// Which slot a read took: none (a tile waits on it), one of `at_once`, or | ||
/// one of `slow_at_once`. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
enum Slot { | ||
Urgent, | ||
Queued, | ||
Slow, | ||
} | ||
| ||
/// A collection's backfill: the repositories listed, those done, the | ||
/// listed ones still being read, every one the relay listed, whether the | ||
/// relay's listing is running and whether it ended whole, and whether the | ||
/// relay's listing is running and whether it ended whole, whether the | ||
/// sink held the collection complete already, so the listing only learns | ||
/// which repositories hold it. | ||
/// which repositories hold it, whether it is taken in per author | ||
/// (`wide`), and whether it goes slow. | ||
#[derive(Default)] | ||
struct Listing { | ||
repos: usize, | ||
| @@ -161,6 +221,8 @@ struct Listing { | ||
running: bool, | ||
listed: bool, | ||
learning: bool, | ||
wide: bool, | ||
slow: bool, | ||
} | ||
| ||
impl Listing { | ||
| @@ -259,6 +321,7 @@ impl Backfill { | ||
) -> Arc<Backfill> { | ||
settings.per_host = settings.per_host.max(1); | ||
settings.at_once = settings.at_once.max(1); | ||
settings.slow_at_once = settings.slow_at_once.max(1); | ||
Arc::new(Backfill { | ||
hud, | ||
sink, | ||
| @@ -268,23 +331,45 @@ impl Backfill { | ||
hosts: Mutex::default(), | ||
state: Mutex::default(), | ||
ended: Notify::new(), | ||
scoped: OnceLock::new(), | ||
paused: watch::channel(false).0, | ||
}) | ||
} | ||
| ||
/// Starts, once, backfilling every repository the relay lists with | ||
/// `collection`, in the background (resuming one the sink holds | ||
/// incomplete: only repositories with no revision are read). Marks it | ||
/// complete once every repository listed was read or tried. One the | ||
/// sink holds complete is listed too, reading none, so `repos` knows | ||
/// which repositories hold it. | ||
/// Tells `scoped` how each collection is taken in from now on (once: | ||
/// the first told is told). | ||
pub fn scoped(&self, scoped: Scoped) { | ||
let _ = self.scoped.set(scoped); | ||
} | ||
| ||
fn scope(&self, collection: &str, whole: bool) { | ||
if let Some(scoped) = self.scoped.get() { | ||
scoped(collection, whole); | ||
} | ||
} | ||
| ||
/// Starts, once, taking in `collection`: in the background, the relay | ||
/// lists the repositories holding it, and past `max_repos` of them | ||
/// (unless the operator takes it in whole, `large`) it is taken in per | ||
/// author; else every one is read (resuming one the sink holds | ||
/// incomplete: only repositories with no revision are read), and it is | ||
/// marked complete once every repository listed was read or tried. One | ||
/// the sink holds complete is listed too, reading none, so `repos` | ||
/// knows which repositories hold it. One the sink holds per author is | ||
/// not listed again. | ||
pub fn collection(self: &Arc<Self>, collection: &str) { | ||
let mut state = self.lock(); | ||
if state.collections.contains_key(collection) { | ||
return; | ||
} | ||
let large = self.settings.large.iter().any(|c| c == collection); | ||
let wide = self.sink.wide(collection).filter(|_| !large); | ||
let listing = Listing { | ||
running: true, | ||
running: wide.is_none(), | ||
wide: wide.is_some(), | ||
repos: wide.unwrap_or(0) as usize, | ||
learning: self.sink.complete(collection), | ||
slow: self.sink.records(collection) >= self.settings.slow_records, | ||
..Listing::default() | ||
}; | ||
state.collections.insert(collection.to_string(), listing); | ||
| @@ -293,7 +378,16 @@ impl Backfill { | ||
self.sink.add_collection(collection), | ||
"taking in a collection", | ||
); | ||
spawn(self.clone().list(collection.to_string())); | ||
if large { | ||
logged( | ||
self.sink.set_wide(collection, None), | ||
"taking in a collection whole", | ||
); | ||
} | ||
match wide { | ||
Some(_) => self.scope(collection, false), | ||
None => drop(spawn(self.clone().list(collection.to_string()))), | ||
} | ||
} | ||
| ||
/// Brings these repositories' `collection` in ahead of the rest, | ||
| @@ -303,6 +397,7 @@ impl Backfill { | ||
/// by `collection`) ended, only those it listed are read, the rest | ||
/// counted in at once, as they hold none; one still running is waited | ||
/// on for `LISTING_WAIT` at most. The collection is not taken in whole. | ||
/// Of one taken in per author, at most `AUTHORS` start being read. | ||
pub async fn repos( | ||
self: &Arc<Self>, | ||
dids: &[String], | ||
| @@ -313,7 +408,13 @@ impl Backfill { | ||
self.listing(collection, until.min(Instant::now() + LISTING_WAIT)) | ||
.await; | ||
let (dids, absent) = self.wanted(&dids, collection); | ||
let waited = self.urge(&dids, collection); | ||
let wide = self | ||
.lock() | ||
.collections | ||
.get(collection) | ||
.is_some_and(|l| l.wide); | ||
let room = if wide { AUTHORS } else { usize::MAX }; | ||
let waited = self.urge(&dids, collection, room); | ||
loop { | ||
let ended = self.ended.notified(); | ||
let mut ended = std::pin::pin!(ended); | ||
| @@ -359,11 +460,16 @@ impl Backfill { | ||
} | ||
| ||
/// Starts reading `dids`' `collection` now, ahead of the rest, but | ||
/// those held already; those queued or running go ahead from now. One | ||
/// whose last read ended unread is not waited on: it is read again in | ||
/// the background once `UNREAD_AGAIN` has passed. Answers those to wait | ||
/// on. | ||
fn urge<'a>(self: &Arc<Self>, dids: &HashSet<&'a str>, collection: &str) -> Vec<&'a str> { | ||
/// those held already, `room` of them at most; those queued or running | ||
/// go ahead from now. One whose last read ended unread is not waited | ||
/// on: it is read again in the background once `UNREAD_AGAIN` has | ||
/// passed. Answers those to wait on. | ||
fn urge<'a>( | ||
self: &Arc<Self>, | ||
dids: &HashSet<&'a str>, | ||
collection: &str, | ||
mut room: usize, | ||
) -> Vec<&'a str> { | ||
let mut state = self.lock(); | ||
let mut waited = Vec::new(); | ||
let now = now_micros(); | ||
| @@ -372,14 +478,16 @@ impl Backfill { | ||
if let Some(at) = self.sink.unread(did, collection) { | ||
let due = now - at >= UNREAD_AGAIN.as_micros() as i64; | ||
if due && !state.pending.contains_key(&key) { | ||
state.queue(did, collection, true); | ||
state.queue(did, collection, true, false); | ||
} | ||
continue; | ||
} | ||
let job = match state.pending.get(&key) { | ||
Some(job) => job.clone(), | ||
None if self.sink.rev(did, collection).is_some() => continue, | ||
None if room == 0 => continue, | ||
None => { | ||
room -= 1; | ||
let job = Arc::new(Job::new(did, collection)); | ||
state.pending.insert(key, job.clone()); | ||
job | ||
| @@ -388,7 +496,7 @@ impl Backfill { | ||
waited.push(*did); | ||
job.urgent.store(true, SeqCst); | ||
if !job.started.swap(true, SeqCst) { | ||
spawn(self.clone().run(job, false)); | ||
spawn(self.clone().run(job, Slot::Urgent)); | ||
} | ||
} | ||
drop(state); | ||
| @@ -409,7 +517,7 @@ impl Backfill { | ||
continue; | ||
} | ||
if self.sink.rev(did, &key.1).is_some() { | ||
state.queue(did, &key.1, true); | ||
state.queue(did, &key.1, true, false); | ||
} | ||
} | ||
drop(state); | ||
| @@ -419,16 +527,53 @@ impl Backfill { | ||
pub fn progress(&self, collection: &str) -> Progress { | ||
let state = self.lock(); | ||
let listing = state.collections.get(collection); | ||
let (repos, done, finding) = | ||
listing.map_or((0, 0, false), |l| (l.repos, l.done, l.running)); | ||
let (repos, done, finding, wide, slow) = listing.map_or((0, 0, false, false, false), |l| { | ||
(l.repos, l.done, l.running, l.wide, l.slow) | ||
}); | ||
Progress { | ||
repos, | ||
done, | ||
complete: self.sink.complete(collection), | ||
complete: !wide && self.sink.complete(collection), | ||
finding, | ||
wide, | ||
slow, | ||
} | ||
} | ||
| ||
/// Forgets `collection`, expired: how far it came, and its reads not | ||
/// yet started. It is taken in again when next asked for. | ||
pub fn expired(&self, collection: &str) { | ||
let mut state = self.lock(); | ||
state.collections.remove(collection); | ||
let started = |job: &Arc<Job>| job.collection != collection || job.started.load(SeqCst); | ||
state.queue.retain(started); | ||
state.slow.retain(started); | ||
state.pending.retain(|_, job| started(job)); | ||
} | ||
| ||
/// Whether `collection`'s backfill is under way: the relay listing it, | ||
/// or a read of it queued or running. | ||
pub fn busy(&self, collection: &str) -> bool { | ||
let state = self.lock(); | ||
let listing = state.collections.get(collection); | ||
listing.is_some_and(|l| l.running) || state.pending.keys().any(|(_, c)| c == collection) | ||
} | ||
| ||
/// Whether no read is queued or running. | ||
pub fn idle(&self) -> bool { | ||
self.lock().pending.is_empty() | ||
} | ||
| ||
/// Holds every read back from starting while `paused` (a read under | ||
/// way ends first), or lets them start again: whether that changed. | ||
pub fn pause(&self, paused: bool) -> bool { | ||
self.paused.send_replace(paused) != paused | ||
} | ||
| ||
pub fn paused(&self) -> bool { | ||
*self.paused.borrow() | ||
} | ||
| ||
fn lock(&self) -> MutexGuard<'_, State> { | ||
self.state.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| @@ -446,32 +591,73 @@ impl Backfill { | ||
(count, reading) | ||
} | ||
| ||
/// The relay's listing of `collection`, page by page, each page's | ||
/// repositories queued as it comes. | ||
/// The relay's listing of `collection`, page by page, counted as it | ||
/// comes: past `max_repos`, it stops and the collection is taken in per | ||
/// author; else once it ends, each repository is queued, and the | ||
/// collection is taken in whole. One the operator takes in whole | ||
/// (`large`) is not counted, each page's repositories queued as it | ||
/// comes. A listing that fails queues what it found. | ||
async fn list(self: Arc<Self>, collection: String) { | ||
let large = self.settings.large.contains(&collection); | ||
if large { | ||
self.scope(&collection, true); | ||
} | ||
let mut cursor: Option<String> = None; | ||
loop { | ||
let mut found = Vec::new(); | ||
let whole = loop { | ||
let page = again(|| self.relay_page(&collection, cursor.as_deref())).await; | ||
let (dids, next) = match page { | ||
Ok(page) => page, | ||
Err(why) => { | ||
tracing::warn!(collection, %why, "the relay's listing failed; the collection stays incomplete"); | ||
self.listing_ended(&collection, false); | ||
return; | ||
break false; | ||
} | ||
}; | ||
let more = next.is_some() && !dids.is_empty(); | ||
self.listed(&collection, dids); | ||
self.lock() | ||
.collections | ||
.entry(collection.clone()) | ||
.or_default() | ||
.repos += dids.len(); | ||
found.extend(dids); | ||
if large { | ||
self.listed(&collection, std::mem::take(&mut found)); | ||
} else if found.len() > self.settings.max_repos { | ||
return self.widened(&collection, found.len()).await; | ||
} | ||
if !more { | ||
break; | ||
break true; | ||
} | ||
cursor = next; | ||
}; | ||
self.listed(&collection, found); | ||
if whole && !large { | ||
self.scope(&collection, true); | ||
} | ||
if self.listing_ended(&collection, true) { | ||
if self.listing_ended(&collection, whole) { | ||
self.completed(&collection).await; | ||
} | ||
} | ||
| ||
/// `collection` found held by `repos` repositories, too many to take | ||
/// in whole: taken in per author from now on, the live stream keeping | ||
/// those read alone. | ||
async fn widened(&self, collection: &str, repos: usize) { | ||
let said = "too widely held to take in whole: taken in per author"; | ||
tracing::info!(collection, repos, "{said}"); | ||
let (sink, nsid) = (self.sink.clone(), collection.to_string()); | ||
let set = blocking(move || sink.set_wide(&nsid, Some(repos as u64))).await; | ||
logged(set, "taking a collection in per author"); | ||
let mut state = self.lock(); | ||
let listing = state.collections.entry(collection.to_string()).or_default(); | ||
listing.running = false; | ||
listing.wide = true; | ||
listing.repos = repos; | ||
drop(state); | ||
self.ended.notify_waiters(); | ||
self.scope(collection, false); | ||
} | ||
| ||
/// The relay's listing of `collection` ended, `whole` or not, waking | ||
/// `repos` waiting on it: whether it listed every repository whole and | ||
/// each is done. | ||
| @@ -501,9 +687,9 @@ impl Backfill { | ||
Ok((dids, pages.cursor().map(str::to_string))) | ||
} | ||
| ||
/// Takes a page of the relay's listing of `collection`: each repository | ||
/// counted, done if the sink holds a revision of it or the collection | ||
/// complete, else queued unless it is being read already. | ||
/// Takes repositories the relay listed with `collection`: each done if | ||
/// the sink holds a revision of it or the collection complete, else | ||
/// queued unless it is being read already. | ||
fn listed(self: &Arc<Self>, collection: &str, dids: Vec<String>) { | ||
let mut state = self.lock(); | ||
for did in dids { | ||
| @@ -512,15 +698,15 @@ impl Backfill { | ||
let held = !reading && self.sink.rev(&key.0, collection).is_some(); | ||
let listing = state.collections.entry(key.1.clone()).or_default(); | ||
let held = held || listing.learning; | ||
let slow = listing.slow; | ||
listing.members.insert(key.0.clone()); | ||
listing.repos += 1; | ||
listing.done += usize::from(held); | ||
if held { | ||
continue; | ||
} | ||
listing.waiting.insert(key.0.clone()); | ||
if !reading { | ||
state.queue(&key.0, collection, false); | ||
state.queue(&key.0, collection, false, slow); | ||
} | ||
} | ||
drop(state); | ||
| @@ -533,26 +719,39 @@ impl Backfill { | ||
logged(set, "marking a collection complete"); | ||
} | ||
| ||
/// Starts queued reads while `at_once` of them are not running, passing | ||
/// by those started already. | ||
/// Starts queued reads while `at_once` of them are not running, and | ||
/// slow collections' while `slow_at_once` of theirs are not, passing by | ||
/// those started already. | ||
fn pump(self: &Arc<Self>) { | ||
let mut state = self.lock(); | ||
while state.running < self.settings.at_once { | ||
let Some(job) = state.queue.pop_front() else { | ||
return; | ||
let state = &mut *state; | ||
for slot in [Slot::Queued, Slot::Slow] { | ||
let (running, max, queue) = match slot { | ||
Slot::Slow => ( | ||
&mut state.slow_running, | ||
self.settings.slow_at_once, | ||
&mut state.slow, | ||
), | ||
_ => (&mut state.running, self.settings.at_once, &mut state.queue), | ||
}; | ||
if !job.started.swap(true, SeqCst) { | ||
state.running += 1; | ||
spawn(self.clone().run(job, true)); | ||
while *running < max { | ||
let Some(job) = queue.pop_front() else { | ||
break; | ||
}; | ||
if !job.started.swap(true, SeqCst) { | ||
*running += 1; | ||
spawn(self.clone().run(job, slot)); | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// Reads `job`, again if asked to while it was read, then lets the | ||
/// next queued read start; `queued` if it took one of the queue's | ||
/// slots. | ||
async fn run(self: Arc<Self>, job: Arc<Job>, queued: bool) { | ||
/// Reads `job` once reads are not paused, again if asked to while it | ||
/// was read, then lets the next queued read start in the `slot` it | ||
/// took. | ||
async fn run(self: Arc<Self>, job: Arc<Job>, slot: Slot) { | ||
let completed = loop { | ||
let _ = self.paused.subscribe().wait_for(|paused| !paused).await; | ||
self.read_repo(&job).await; | ||
if self.sink.rev(&job.did, &job.collection).is_none() { | ||
let (sink, did, collection) = | ||
| @@ -566,7 +765,8 @@ impl Backfill { | ||
} | ||
let key = (job.did.clone(), job.collection.clone()); | ||
state.pending.remove(&key); | ||
state.running -= usize::from(queued); | ||
state.running -= usize::from(slot == Slot::Queued); | ||
state.slow_running -= usize::from(slot == Slot::Slow); | ||
let listing = state.collections.get_mut(&job.collection); | ||
break listing.is_some_and(|l| l.ended(&job.did)); | ||
}; | ||
| @@ -667,7 +867,7 @@ impl Backfill { | ||
self.forget(job).await?; | ||
dropped = true; | ||
} | ||
self.put(std::mem::take(&mut writes)).await?; | ||
self.put(job, std::mem::take(&mut writes)).await?; | ||
} | ||
if next.is_none() { | ||
break; | ||
| @@ -677,7 +877,7 @@ impl Backfill { | ||
if !dropped { | ||
self.forget(job).await?; | ||
} | ||
self.put(writes).await?; | ||
self.put(job, writes).await?; | ||
self.set_rev(job, &rev).await?; | ||
Ok(rev) | ||
} | ||
| @@ -713,7 +913,7 @@ impl Backfill { | ||
} | ||
}; | ||
self.forget(job).await?; | ||
self.put(writes).await?; | ||
self.put(job, writes).await?; | ||
self.set_rev(job, &rev).await?; | ||
Ok(Some(rev)) | ||
} | ||
| @@ -795,15 +995,51 @@ impl Backfill { | ||
dropped.map_err(Fail::Never) | ||
} | ||
| ||
async fn put(&self, writes: Vec<Write>) -> Result<(), Fail> { | ||
/// Writes `job`'s records, behind every other backfill's where its | ||
/// collection goes slow and no tile waits on it; then weighs the | ||
/// collection (`weigh`). | ||
async fn put(&self, job: &Job, writes: Vec<Write>) -> Result<(), Fail> { | ||
let collection = &job.collection; | ||
let slow = !job.urgent.load(SeqCst) && self.weighed(collection); | ||
let sink = self.sink.clone(); | ||
let put = blocking(move || { | ||
for batch in writes.chunks(BATCH) { | ||
sink.apply(batch)?; | ||
sink.backfill(batch, slow)?; | ||
} | ||
Ok(()) | ||
}); | ||
put.await.map_err(Fail::Never) | ||
put.await.map_err(Fail::Never)?; | ||
self.weigh(collection); | ||
Ok(()) | ||
} | ||
| ||
/// Whether `collection` goes slow. | ||
fn weighed(&self, collection: &str) -> bool { | ||
let state = self.lock(); | ||
state.collections.get(collection).is_some_and(|l| l.slow) | ||
} | ||
| ||
/// Takes `collection` slow once it holds `slow_records` records, if it | ||
/// is taken in: its reads still queued wait for a slow slot from then | ||
/// on, behind every other collection's. | ||
fn weigh(&self, collection: &str) { | ||
if self.weighed(collection) || self.sink.records(collection) < self.settings.slow_records { | ||
return; | ||
} | ||
let mut state = self.lock(); | ||
let Some(listing) = state.collections.get_mut(collection) else { | ||
return; | ||
}; | ||
listing.slow = true; | ||
let (slow, rest) = state | ||
.queue | ||
.drain(..) | ||
.partition(|j| j.collection == collection); | ||
state.queue = rest; | ||
state.slow.extend::<VecDeque<_>>(slow); | ||
drop(state); | ||
let said = "held past its records' limit: its backfill goes slow"; | ||
tracing::info!(collection, "{said}"); | ||
} | ||
| ||
async fn set_rev(&self, job: &Job, rev: &str) -> Result<(), Fail> { | ||
crates/hud-index/src/lib.rs+18−9
| @@ -9,8 +9,9 @@ | ||
//! - `backfill`: a collection's repositories read in, from their PDSes or | ||
//! Hubble's archives. | ||
//! - `live`: Jetstream, keeping what is held current. | ||
//! - `handoff`: a repository's live writes held while it is read. | ||
//! - `server`: the XRPC methods. | ||
//! - `sweep`: the upkeep: what nobody asks for expired, the backfill | ||
//! paused while the disk runs short. | ||
| ||
pub mod backfill; | ||
pub mod handoff; | ||
| @@ -19,6 +20,7 @@ pub mod server; | ||
pub mod sink; | ||
pub mod spec; | ||
pub mod store; | ||
pub mod sweep; | ||
| ||
use crate::backfill::Backfill; | ||
use crate::handoff::Handoff; | ||
| @@ -35,33 +37,40 @@ pub struct Settings { | ||
pub origin: String, | ||
/// Its SQLite file. | ||
pub db: PathBuf, | ||
/// The most connections reading it at once. | ||
pub readers: usize, | ||
pub backfill: backfill::Settings, | ||
pub live: live::Settings, | ||
pub sweep: sweep::Settings, | ||
} | ||
| ||
/// The index, its store opened, its backfill and live stream started, and | ||
/// what it held before resumed: every collection's backfill picks up where | ||
/// it stopped and the live stream from its cursor. | ||
/// it stopped and the live stream from its cursor, following each | ||
/// collection as the backfill takes it in (`Backfill::scoped`). Its sweep | ||
/// runs from now (`sweep`). | ||
pub fn start(hud: Arc<Hud>, settings: Settings) -> Result<Arc<server::Index>, String> { | ||
let did = server::did_web(&settings.origin)?; | ||
let store = Arc::new(Store::open(&settings.db)?); | ||
let store = Arc::new(Store::open(&settings.db)?.readers(settings.readers)); | ||
store.spawn_builder(); | ||
let handoff = Arc::new(Handoff::new()); | ||
let backfill = Backfill::new(hud, store.clone(), handoff.clone(), settings.backfill); | ||
let live = Live::start(store.clone(), handoff, settings.live, resyncing(&backfill)); | ||
let held = store.collections(); | ||
for collection in &held { | ||
for collection in &store.collections() { | ||
backfill.collection(collection); | ||
} | ||
live.follow(&held); | ||
let live = Live::start(store.clone(), handoff, settings.live, resyncing(&backfill)); | ||
backfill.scoped(live.scoped()); | ||
live.follow_repos(&store.partial_collections()); | ||
Ok(Arc::new(server::Index { | ||
let index = Arc::new(server::Index { | ||
store, | ||
backfill, | ||
live, | ||
did, | ||
origin: settings.origin, | ||
})) | ||
sweep: settings.sweep, | ||
}); | ||
sweep::spawn(&index); | ||
Ok(index) | ||
} | ||
| ||
/// What the live stream calls on a `sync` event: `backfill` reads that | ||
crates/hud-index/src/live.rs+58−6
crates/hud-index/src/server.rs+83−24
crates/hud-index/src/sink.rs+13−0
crates/hud-index/src/store.rs+1363−278
A large diff, not shown.