Something went wrong. Try again.
contributor fork of @ptr.pet hydrant forked from ptr.pet/hydrant
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263#![allow(unused_imports)]
#[cfg(feature = "indexer")]pub(crate) mod crawler;pub(crate) mod filter;pub(crate) mod firehose;pub(crate) mod pds;pub(crate) mod repos;mod seed;pub(crate) mod stream;
#[cfg(feature = "indexer")]mod indexer;#[cfg(feature = "indexer")]pub use indexer::*;
#[cfg(feature = "relay")]mod relay;#[cfg(feature = "relay")]pub use relay::*;#[cfg(feature = "jetstream")]mod jetstream;#[cfg(feature = "jetstream")]pub use jetstream::*;
pub use filter::{FilterControl, FilterPatch, FilterSnapshot};#[cfg(feature = "firehose-diagnostics")]pub use firehose::FirehoseDiagnosticsInfo;pub use firehose::{FirehoseHandle, FirehoseSourceInfo};pub use pds::{PdsControl, PdsTierAssignment, PdsTierDefinition};pub use repos::{ListedRecord, Record, RecordList, RepoHandle, RepoInfo, ReposControl};use smol_str::{SmolStr, ToSmolStr};
use std::collections::BTreeMap;use std::collections::BTreeSet;use std::future::Future;use std::pin::Pin;use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};use std::task::{Context, Poll};
use futures::{FutureExt, Stream};use miette::{IntoDiagnostic, Result, WrapErr};use tokio::sync::{mpsc, watch};use tracing::{debug, error, info, warn};
#[cfg(feature = "indexer")]use crate::backfill::BackfillWorker;use crate::config::{Config, SignatureVerification};#[cfg(feature = "indexer")]use crate::db::load_persisted_crawler_sources;use crate::db::{self, filter as db_filter, keys, load_persisted_firehose_sources};use crate::filter::FilterMode;#[cfg(feature = "indexer")]use crate::ingest::indexer::FirehoseWorker;use crate::pds_meta::{PdsMeta, PdsMetaHandle};use crate::state::AppState;#[cfg(feature = "indexer_stream")]use crate::types::MarshallableEvt;use firehose::FirehoseShared;#[cfg(feature = "indexer_stream")]use stream::event_stream_thread;#[cfg(feature = "relay")]use stream::relay_stream_thread;use url::Url;
#[derive(Debug, Clone)]pub struct ApiBinds { head: std::net::SocketAddr, tail: Vec<std::net::SocketAddr>,}
impl ApiBinds { pub fn new(addr: std::net::SocketAddr) -> Self { Self { head: addr, tail: Vec::new(), } }
pub fn try_from_iter<I: IntoIterator<Item = std::net::SocketAddr>>(iter: I) -> Option<Self> { let mut iter = iter.into_iter(); let head = iter.next()?; Some(Self { head, tail: iter.collect(), }) }
pub fn iter(&self) -> impl Iterator<Item = std::net::SocketAddr> + '_ { std::iter::once(self.head).chain(self.tail.iter().copied()) }}
#[derive(Debug, Clone)]/// infromation about a host hydrant is consuming from.pub struct Host { /// hostname of the host. pub name: SmolStr, /// latest seq hydrant has processed from this host. pub seq: i64, /// the amount of accounts hydrant has seen from this host. pub account_count: u64, /// the status of this host in hydrant. pub status: crate::pds_meta::HostStatus,}
/// an event emitted by the hydrant event stream.////// three variants are possible depending on the `type` field:/// - `"record"`: a repo record was created, updated, or deleted. carries a [`RecordEvt`]./// - `"identity"`: a DID's handle or PDS changed. carries an [`IdentityEvt`]. ephemeral, not replayable./// - `"account"`: a repo's active/inactive status changed. carries an [`AccountEvt`]. ephemeral, not replayable.////// the `id` field is a monotonically increasing sequence number usable as a cursor for [`Hydrant::subscribe`].#[cfg(feature = "indexer_stream")]pub type Event = MarshallableEvt<'static>;
/// the top-level handle to a hydrant instance.////// `Hydrant` is cheaply cloneable. all sub-handles share the same underlying state./// construct it via [`Hydrant::new`] or [`Hydrant::from_env`], configure the filter/// and repos as needed, then call [`Hydrant::run`] to start all background components.////// # example////// ```rust,no_run/// use hydrant::control::{ApiBinds, Hydrant};////// #[tokio::main]/// async fn main() -> miette::Result<()> {/// let hydrant = Hydrant::from_env().await?;/// let binds = ApiBinds::new("0.0.0.0:3000".parse().unwrap());////// tokio::select! {/// r = hydrant.run()? => r,/// r = hydrant.serve(binds) => r,/// }/// }/// ```#[derive(Clone)]pub struct Hydrant { #[cfg(feature = "indexer")] pub crawler: crawler::CrawlerHandle, pub firehose: FirehoseHandle, #[cfg(feature = "indexer")] pub backfill: BackfillHandle, pub filter: FilterControl, pub pds: PdsControl, pub repos: ReposControl, pub db: DbControl, #[cfg(feature = "backlinks")] pub backlinks: crate::backlinks::BacklinksControl, pub(crate) state: Arc<AppState>, config: Arc<Config>, started: Arc<AtomicBool>, _priv: (),}
impl Hydrant { /// Returns a reference to the internal DID resolver. pub fn resolver(&self) -> &crate::resolver::Resolver { &self.state.resolver }
/// open the database and configure hydrant from `config`. /// /// this sets up the database, applies any filter configuration from `config`, and /// initializes all sub-handles. no background tasks are started yet: call /// [`run`](Self::run) to start all components and drive the instance. pub async fn new(config: Config) -> Result<Self> { info!("{config}");
#[cfg(feature = "relay")] if config.only_index_links { miette::bail!("HYDRANT_ONLY_INDEX_LINKS is not supported in relay mode"); }
// 1. open database and construct AppState let state = AppState::new(&config)?;
// 2. apply any filter config from env variables if config.full_network || config.filter_signals.is_some() || config.filter_collections.is_some() || config.filter_excludes.is_some() { let filter_ks = state.db.filter.clone(); let inner = state.db.inner.clone(); let mode = config.full_network.then_some(FilterMode::Full); let signals = config .filter_signals .clone() .map(crate::patch::SetUpdate::Set); let collections = config .filter_collections .clone() .map(crate::patch::SetUpdate::Set); let excludes = config .filter_excludes .clone() .map(crate::patch::SetUpdate::Set);
tokio::task::spawn_blocking(move || { let mut batch = inner.batch(); db_filter::apply_patch( &mut batch, &filter_ks, mode, signals, collections, excludes, )?; batch.commit().into_diagnostic() }) .await .into_diagnostic()??;
// 3. reload the live filter into the hot-path arc-swap let new_filter = tokio::task::spawn_blocking({ let filter_ks = state.db.filter.clone(); move || db_filter::load(&filter_ks) }) .await .into_diagnostic()??; state.filter.store(Arc::new(new_filter)); }
#[cfg(feature = "indexer")] { // 4. set crawler enabled state from config, evaluated against the post-patch filter let post_patch_crawler = match config.enable_crawler { Some(b) => b, None => { state.filter.load().mode == FilterMode::Full || !config.crawler_sources.is_empty() } }; state.crawler_enabled.send_replace(post_patch_crawler); }
let state = Arc::new(state);
Ok(Self { firehose: FirehoseHandle::new(state.clone()), filter: FilterControl(state.clone()), pds: pds::PdsControl(state.clone()), repos: ReposControl(state.clone()), db: DbControl(state.clone()), #[cfg(feature = "indexer")] crawler: crawler::CrawlerHandle { state: state.clone(), shared: Arc::new(std::sync::OnceLock::new()), tasks: Arc::new(scc::HashMap::new()), persisted: Arc::new(scc::HashSet::new()), }, #[cfg(feature = "indexer")] backfill: BackfillHandle::new(state.clone()), #[cfg(feature = "backlinks")] backlinks: crate::backlinks::BacklinksControl(state.clone()), state, config: Arc::new(config), started: Arc::new(AtomicBool::new(false)), _priv: (), }) }
/// reads config from environment variables and calls [`Hydrant::new`]. pub async fn from_env() -> Result<Self> { Self::new(Config::from_env()?).await }
/// start all background components and return a future that resolves when any /// fatal component exits. /// /// starts the backfill worker, firehose ingestors, crawler, and worker thread. /// resolves with `Ok(())` if a fatal component exits cleanly, or `Err(e)` if it /// fails. intended for use in `tokio::select!` alongside [`serve`](Self::serve). /// /// returns an error if called more than once on the same `Hydrant` instance. pub fn run(&self) -> Result<impl Future<Output = Result<()>>> { let state = self.state.clone(); let config = self.config.clone(); #[cfg(feature = "indexer")] let crawler = self.crawler.clone(); let firehose = self.firehose.clone();
if self.started.swap(true, Ordering::SeqCst) { miette::bail!("Hydrant::run() called more than once"); }
let fut = async move { // validated IndexerMessages from RelayWorker/backfill to FirehoseWorker. #[cfg(feature = "indexer")] let (indexer_tx, firehose_worker) = FirehoseWorker::new(state.clone(), config.firehose_workers);
// raw firehose events from pds/relay to RelayWorker. let (buffer_tx, relay_worker) = crate::ingest::relay::RelayWorker::new( state.clone(), #[cfg(feature = "indexer")] indexer_tx.clone(), matches!(config.verify_signatures, SignatureVerification::Full), config.firehose_workers, crate::ingest::validation::ValidationOptions { verify_mst: config.verify_mst, rev_clock_skew_secs: config.rev_clock_skew_secs, }, );
// 5. spawn the backfill worker (not used in relay mode) #[cfg(feature = "indexer")] tokio::spawn({ let state = state.clone(); BackfillWorker::new( state.clone(), indexer_tx.clone(), config.repo_fetch_timeout, config.backfill_concurrency_limit, matches!( config.verify_signatures, SignatureVerification::Full | SignatureVerification::BackfillOnly ), config.backfill_strategy, state.backfill_enabled.subscribe(), ) .run() });
// 6. re-queue any repos that lost their backfill state, then start the retry worker #[cfg(feature = "indexer")] { if let Err(e) = tokio::task::spawn_blocking({ let state = state.clone(); move || crate::backfill::manager::queue_gone_backfills(&state) }) .await .into_diagnostic()? { error!(err = %e, "failed to queue gone backfills"); db::check_poisoned_report(&e); }
std::thread::spawn({ let state = state.clone(); move || crate::backfill::manager::retry_worker(state) }); }
// 7. ephemeral GC thread (not used in relay mode) #[cfg(feature = "indexer_stream")] if config.ephemeral { let state = state.clone(); std::thread::Builder::new() .name("ephemeral-gc".into()) .spawn(move || crate::db::ephemeral::ephemeral_ttl_worker(state)) .into_diagnostic()?; }
// relay events TTL: relay_events keyspace grows unbounded without pruning #[cfg(feature = "relay")] { let state = state.clone(); std::thread::Builder::new() .name("relay-events-gc".into()) .spawn(move || crate::db::ephemeral::relay_events_ttl_worker(state)) .into_diagnostic()?; }
// 8. cursor / counts persist thread std::thread::spawn({ let state = state.clone(); let persist_interval = config.cursor_save_interval; move || loop { std::thread::sleep(persist_interval);
state.firehose_cursors.iter_sync(|relay, cursor| { let seq = cursor.load(Ordering::SeqCst); if seq > 0 && let Err(e) = db::set_firehose_cursor(&state.db, relay, seq) { error!(relay = %relay, err = %e, "failed to save cursor"); db::check_poisoned_report(&e); } true });
let checkpoint_watermark = match state.db.checkpoint_count_deltas() { Ok(watermark) => watermark, Err(e) => { error!(err = %e, "failed to checkpoint count deltas"); db::check_poisoned_report(&e); None } };
if let Err(e) = state.db.persist() { error!(err = %e, "db persist failed"); db::check_poisoned_report(&e); } else { let watermark = checkpoint_watermark .map(Ok) .unwrap_or_else(|| db::load_count_delta_watermark(&state.db)); match watermark { Ok(watermark) => state.db.mark_count_checkpoint_persisted(watermark), Err(e) => { error!(err = %e, "failed to load durable count checkpoint watermark"); db::check_poisoned_report(&e); } } } } });
// 9. events/sec stats ticker #[cfg(any(feature = "indexer_stream", feature = "relay"))] tokio::spawn({ let state = state.clone(); let get_id = |state: &AppState| { #[cfg(feature = "indexer_stream")] let id = state.db.next_event_id.load(Ordering::Relaxed); #[cfg(feature = "relay")] let id = state.db.next_relay_seq.load(Ordering::Relaxed); id }; let mut last_id = get_id(&state); let mut last_time = std::time::Instant::now(); let mut interval = tokio::time::interval(std::time::Duration::from_secs(60)); async move { loop { interval.tick().await;
let current_id = get_id(&state); let current_time = std::time::Instant::now(); let delta = current_id.saturating_sub(last_id);
if delta == 0 { debug!("no new events in 60s"); continue; }
let elapsed = current_time.duration_since(last_time).as_secs_f64(); let rate = if elapsed > 0.0 { delta as f64 / elapsed } else { 0.0 }; info!("{rate:.2} events/s ({delta} events in {elapsed:.1}s)");
last_id = current_id; last_time = current_time; } } });
let (fatal_tx_inner, mut fatal_rx) = watch::channel(None); let fatal_tx = Arc::new(fatal_tx_inner);
// 10. set shared and spawn firehose ingestors firehose .shared .set(FirehoseShared { buffer_tx: buffer_tx.clone(), verify_signatures: matches!( config.verify_signatures, SignatureVerification::Full ), max_failures: config.firehose_max_failures, }) .ok() .expect("firehose shared already set"); let fire_shared = firehose.shared.get().unwrap();
// refresh seed snapshots before spawning any direct PDS sources. persisted // sources may predate cursor seeding, and an already-open websocket will not // pick up a later cursor update until it reconnects. if !config.seed_hosts.is_empty() { seed::refresh_seed_snapshots(&config.seed_hosts, &state).await; }
// add hosts from config let relay_hosts = config.relays.clone(); if !relay_hosts.is_empty() { info!( relay_count = relay_hosts.len(), hosts = relay_hosts .iter() .map(|h| h.url.as_str()) .collect::<Vec<_>>() .join(", "), "starting firehose ingestor(s)" ); for source in &relay_hosts { let _ = firehose .known_sources .insert_async(source.url.clone(), source.is_pds) .await; firehose .spawn_firehose_ingestor(source, fire_shared, true) .await?; } }
// add persisted hosts let persisted_sources = tokio::task::spawn_blocking({ let state = state.clone(); move || load_persisted_firehose_sources(&state.db) }) .await .into_diagnostic()??; for source in &persisted_sources { let _ = firehose .known_sources .insert_async(source.url.clone(), source.is_pds) .await; if firehose.tasks.contains_async(&source.url).await { continue; } firehose .spawn_firehose_ingestor(source, fire_shared, true) .await?; } // we use spawn_firehose_ingestor directly here since we dont want // to go through the whole add_source machinery and checks. seed // cursor snapshots were refreshed before this loop.
// 10c. seed firehose PDS sources from listHosts on configured seed URLs if !config.seed_hosts.is_empty() { let seed_urls = config.seed_hosts.clone(); let firehose = firehose.clone(); let state = state.clone(); tokio::spawn(async move { seed::seed_from_list_hosts(&seed_urls, &firehose, &state).await; }); }
// 10d. periodic retry of offline firehose sources if let Some(retry_interval) = config.offline_host_retry_interval { tokio::spawn({ let firehose = firehose.clone(); async move { loop { tokio::time::sleep(retry_interval).await;
let mut to_restart: Vec<(Url, bool)> = Vec::new(); let mut banned = 0usize; { let meta = firehose.state.pds_meta.load(); firehose .known_sources .iter_async(|url, &is_pds| { if firehose.tasks.contains_sync(url) { return true; } let host = url.host_str().unwrap_or(url.as_str()); if meta.is_banned(host) { banned += 1; return true; } to_restart.push((url.clone(), is_pds)); true }) .await; }
if !to_restart.is_empty() || banned != 0 { info!( restart_count = to_restart.len(), banned, retry_interval_secs = retry_interval.as_secs(), "offline firehose retry tick" ); }
for (url, is_pds) in to_restart { if let Err(e) = firehose.restart_source(url.clone(), is_pds).await { warn!(url = %url, is_pds, err = %e, "failed to restart firehose source"); } } } } }); }
// 11. spawn crawler infrastructure #[cfg(feature = "indexer")] { use crate::crawler::{ CrawlerStats, CrawlerWorker, InFlight, RetryProducer, SignalChecker, }; use crate::util::throttle::Throttler;
let http = reqwest::Client::builder() .user_agent(concat!( env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION") )) .gzip(true) .build() .expect("that reqwest will build"); let pds_throttler = state.throttler.clone(); let in_flight = InFlight::new(); let stats = CrawlerStats::new( state.clone(), config .crawler_sources .iter() .map(|s| s.url.clone()) .collect(), pds_throttler.clone(), ); let checker = SignalChecker { http: http.clone(), state: state.clone(), throttler: pds_throttler, };
info!( max_pending = config.crawler_max_pending_repos, resume_pending = config.crawler_resume_pending_repos, enabled = *state.crawler_enabled.borrow(), "starting crawler worker" ); let (worker, tx) = CrawlerWorker::new( state.clone(), config.crawler_max_pending_repos, config.crawler_resume_pending_repos, stats.clone(), ); tokio::spawn(async move { worker.run().await; error!("crawler worker exited unexpectedly, aborting"); std::process::abort(); });
let ticker = tokio::spawn(stats.clone().task()); tokio::spawn(async move { match ticker.await { Err(e) => error!(err = ?e, "stats ticker panicked, aborting"), Ok(()) => error!("stats ticker exited unexpectedly, aborting"), } std::process::abort(); });
tokio::spawn( RetryProducer { checker: checker.clone(), in_flight: in_flight.clone(), tx: tx.clone(), } .run(), );
// set shared objects so CrawlerHandle methods can use them crawler .shared .set(crawler::CrawlerShared { http, checker, in_flight, tx, stats, }) .ok() .expect("crawler shared already set"); let shared = crawler.shared.get().unwrap();
// spawn initial sources from config for source in config.crawler_sources.iter() { let enabled_rx = state.crawler_enabled.subscribe(); let handle = crawler::spawn_crawler_producer( source, &shared.http, &state, &shared.checker, &shared.in_flight, &shared.tx, &shared.stats, enabled_rx, ); let _ = crawler.tasks.insert_async(source.url.clone(), handle).await; }
let persisted_sources = tokio::task::spawn_blocking({ let state = state.clone(); move || load_persisted_crawler_sources(&state.db) }) .await .into_diagnostic()??;
for source in &persisted_sources { let _ = crawler.persisted.insert_async(source.url.clone()).await; if crawler.tasks.contains_async(&source.url).await { continue; } let enabled_rx = state.crawler_enabled.subscribe(); let handle = crawler::spawn_crawler_producer( source, &shared.http, &state, &shared.checker, &shared.in_flight, &shared.tx, &shared.stats, enabled_rx, ); let _ = crawler.tasks.insert_async(source.url.clone(), handle).await; } }
// 12. spawn the relay worker let relay_worker = std::thread::spawn({ let handle = tokio::runtime::Handle::current(); move || relay_worker.run(handle) });
let tx = Arc::clone(&fatal_tx); tokio::spawn( tokio::task::spawn_blocking(move || { relay_worker .join() .map_err(|e| miette::miette!("relay worker died: {e:?}")) }) .map(move |r| { let result = r.into_diagnostic().flatten().flatten(); let _ = tx.send(Some(result.map_err(|e| e.to_string()))); }), );
// 13. spawn the firehose worker (if enabled) #[cfg(feature = "indexer")] let firehose_worker = std::thread::spawn({ let handle = tokio::runtime::Handle::current(); move || firehose_worker.run(handle) });
#[cfg(feature = "indexer")] { let tx = Arc::clone(&fatal_tx); tokio::spawn( tokio::task::spawn_blocking(move || { firehose_worker .join() .map_err(|e| miette::miette!("firehose worker died: {e:?}")) }) .map(move |r| { let result = r.into_diagnostic().flatten().flatten(); let _ = tx.send(Some(result.map_err(|e| e.to_string()))); }), ); }
// drop the local fatal_tx so the watch channel is only kept alive by the // spawned tasks. when all fatal tasks exit (and drop their tx clones), // fatal_rx.changed() returns Err and we return Ok(()). drop(fatal_tx);
loop { match fatal_rx.changed().await { Ok(()) => { if let Some(result) = fatal_rx.borrow().clone() { return result.map_err(|s| miette::miette!("{s}")); } } // all fatal_tx clones dropped: all tasks finished cleanly Err(_) => return Ok(()), } } }; Ok(fut) }
/// return database counts and on-disk sizes for all keyspaces. /// /// counts include: `repos`, `pending`, `resync`, `records`, `blocks`, `events`, /// `error_ratelimited`, `error_transport`, `error_generic`. /// /// sizes are in bytes, reported per keyspace. pub async fn stats(&self) -> Result<StatsResponse> { let state = self.state.clone();
#[allow(unused_mut)] let mut count_keys = vec![ "repos", "error_ratelimited", "error_transport", "error_generic", ];
#[cfg(feature = "indexer")] { count_keys.push("pending"); count_keys.push("records"); count_keys.push("blocks"); count_keys.push("resync"); }
#[cfg_attr( not(any(feature = "indexer_stream", feature = "relay")), allow(unused_mut) )] let mut counts: BTreeMap<&'static str, u64> = futures::future::join_all(count_keys.into_iter().map(|name| { let state = state.clone(); async move { (name, state.db.get_count(name).await) } })) .await .into_iter() .collect();
#[cfg(feature = "indexer_stream")] counts.insert("events", state.db.events.approximate_len() as u64);
#[cfg(feature = "relay")] counts.insert( "relay_events", state.db.relay_events.approximate_len() as u64, ); #[cfg(feature = "jetstream")] counts.insert( "jetstream_events", state.db.jetstream_events.approximate_len() as u64, );
let sizes = tokio::task::spawn_blocking(move || { let mut s = BTreeMap::new(); s.insert("repos", state.db.repos.disk_space()); s.insert("cursors", state.db.cursors.disk_space()); s.insert("counts", state.db.counts.disk_space()); s.insert("filter", state.db.filter.disk_space()); s.insert("crawler", state.db.crawler.disk_space());
#[cfg(feature = "indexer")] { s.insert("records", state.db.records.disk_space()); s.insert("blocks", state.db.blocks.disk_space()); s.insert("pending", state.db.pending.disk_space()); s.insert("resync", state.db.resync.disk_space()); s.insert("resync_buffer", state.db.resync_buffer.disk_space()); } #[cfg(feature = "indexer_stream")] s.insert("events", state.db.events.disk_space());
#[cfg(feature = "relay")] s.insert("relay_events", state.db.relay_events.disk_space()); #[cfg(feature = "jetstream")] s.insert("jetstream_events", state.db.jetstream_events.disk_space());
#[cfg(feature = "backlinks")] s.insert("backlinks", state.db.backlinks.disk_space());
s }) .await .into_diagnostic()?;
Ok(StatsResponse { counts, sizes }) }
/// returns a future that runs the HTTP management API server on the given bind addresses. /// /// the server exposes all management endpoints (`/filter`, `/repos`, `/ingestion`, /// `/stream`, `/stats`, `/db/*`, `/xrpc/*`). it runs indefinitely and resolves /// only on error. /// /// intended for `tokio::spawn` or inclusion in a `select!` / task list. the clone /// of `self` is deferred until the future is first polled. /// /// to disable the HTTP API entirely, simply don't call this method. pub fn serve(&self, binds: ApiBinds) -> impl Future<Output = Result<()>> { let hydrant = self.clone(); async move { crate::api::serve(hydrant, binds).await } }
/// returns a future that runs the debug HTTP API server on `127.0.0.1:{port}`. /// /// exposes internal inspection endpoints (`/debug/get`, `/debug/iter`, etc.). /// binds only to loopback. pub fn serve_debug(&self, port: u16) -> impl Future<Output = Result<()>> { let state = self.state.clone(); async move { crate::api::serve_debug(state, port).await } }
/// get the status of a (firehose) host we are consuming from. /// /// returns the seq we are on for this host. pub async fn get_host_status(&self, hostname: &str) -> Result<Option<Host>> { let state = self.state.clone(); let hostname = hostname.to_smolstr();
tokio::task::spawn_blocking(move || { let key = keys::firehose_cursor_key(&hostname);
let mut seq = 0; if let Some(cursor_bytes) = state.db.cursors.get(&key).into_diagnostic()? { seq = i64::from_be_bytes(cursor_bytes.as_ref().try_into().into_diagnostic()?); } else { // if it has no cursor, check if it's explicitly tracked in hosts map // or firehose tasks (recently added via API but no messages yet) let meta = state.pds_meta.load(); if !meta.hosts.contains_key(hostname.as_str()) { // we should also allow it if it's an active firehose ingestor let mut found_in_cursors = false; state.firehose_cursors.iter_sync(|u, _| { if u.host_str() == Some(hostname.as_str()) { found_in_cursors = true; } !found_in_cursors // continue if not found });
if !found_in_cursors { return Ok(None); } } }
let account_count = state .db .get_count_sync(&keys::pds_account_count_key(&hostname)); let status = state.pds_meta.load().status(&hostname);
Ok(Some(Host { name: hostname, seq, account_count, status, })) }) .await .into_diagnostic()? }
/// enumerates all hosts hydrant is consuming from. /// /// returns hosts enumerated in this pagination and the cursor to paginate from. pub async fn list_hosts( &self, cursor: Option<&str>, limit: usize, ) -> Result<(Vec<Host>, Option<SmolStr>)> { let state = self.state.clone(); let cursor = cursor.map(str::to_string);
tokio::task::spawn_blocking(move || { let prefix_end = { let mut end = keys::FIREHOSE_CURSOR_PREFIX.to_vec(); *end.last_mut().unwrap() += 1; end };
let mut all_hostnames = BTreeSet::new(); for item in state.db.cursors.range(( std::ops::Bound::Included(keys::FIREHOSE_CURSOR_PREFIX.to_vec()), std::ops::Bound::Excluded(prefix_end), )) { let (k, _) = item.into_inner().into_diagnostic()?; let hostname = std::str::from_utf8(&k[keys::FIREHOSE_CURSOR_PREFIX.len()..]) .into_diagnostic() .wrap_err("firehose cursor key contains non-utf8 hostname")?; all_hostnames.insert(SmolStr::new(hostname)); }
{ let meta = state.pds_meta.load(); for hostname in meta.hosts.keys() { all_hostnames.insert(SmolStr::new(hostname)); } }
let hostnames = all_hostnames.into_iter().collect::<Vec<_>>(); let start_idx = cursor .as_deref() .map(|after| hostnames.partition_point(|host| host.as_str() <= after)) .unwrap_or(0);
let selected = hostnames .iter() .skip(start_idx) .take(limit + 1) .cloned() .collect::<Vec<_>>();
let mut hosts: Vec<Host> = Vec::with_capacity(selected.len().min(limit)); for hostname in selected.iter().take(limit) { let seq = state .db .cursors .get(keys::firehose_cursor_key(hostname)) .into_diagnostic()? .map(|v| { v.as_ref() .try_into() .into_diagnostic() .wrap_err("cursor value is not 8 bytes") .map(i64::from_be_bytes) }) .transpose()? .unwrap_or(0); let account_count = state .db .get_count_sync(&keys::pds_account_count_key(hostname)); let status = state.pds_meta.load().status(hostname); hosts.push(Host { name: hostname.clone(), seq, account_count, status, }); }
let next_cursor = if selected.len() > limit { hosts.last().map(|h| h.name.clone()) } else { None };
Ok((hosts, next_cursor)) }) .await .into_diagnostic()? }}
impl axum::extract::FromRef<Hydrant> for Arc<AppState> { fn from_ref(h: &Hydrant) -> Self { h.state.clone() }}
/// database statistics returned by [`Hydrant::stats`].#[derive(serde::Serialize)]pub struct StatsResponse { /// record counts per logical category (repos, records, events, error kinds, etc.) pub counts: BTreeMap<&'static str, u64>, /// on-disk size in bytes per keyspace pub sizes: BTreeMap<&'static str, u64>,}
/// control over database maintenance operations.////// all methods pause the crawler, firehose, and backfill worker for the duration/// of the operation and restore their prior state on completion, whether or not/// the operation succeeds.#[derive(Clone)]pub struct DbControl(Arc<AppState>);
impl DbControl { /// trigger a major compaction of all keyspaces in parallel. /// /// compaction reclaims disk space from deleted/updated keys and improves /// read performance. can take several minutes on large datasets. pub async fn compact(&self) -> Result<()> { let state = self.0.clone(); state .with_ingestion_paused(async || state.db.compact().await) .await }
/// train zstd compression dictionaries for the `repos`, `blocks`, and `events` keyspaces. /// /// dictionaries are written to `dict_{name}.bin` files inside the database folder. /// a restart is required to apply them. training samples data blocks from the /// existing database, so the database must have a reasonable amount of data first. pub async fn train_dicts(&self) -> Result<()> { let state = self.0.clone(); state .with_ingestion_paused(async || { let train = |name: &'static str| { let state = state.clone(); tokio::task::spawn_blocking(move || state.db.train_dict(name)) .map(|res: Result<_, _>| res.into_diagnostic().flatten()) }; tokio::try_join!(train("repos"), train("blocks"), train("events")).map(|_| ()) }) .await }
/// open a user-defined keyspace. /// /// the keyspace name is prefixed to prevent collision with hydrant's internal keyspaces. #[cfg(feature = "user-keyspace")] pub fn open_keyspace<F>(&self, name: &str, setup: F) -> Result<fjall::Keyspace> where F: FnOnce() -> fjall::KeyspaceCreateOptions, { let name = format!("user:{name}"); self.0.db.inner.keyspace(&name, setup).into_diagnostic() }
/// create an owned write batch for batch operations. #[cfg(feature = "user-keyspace")] pub fn write_batch(&self) -> fjall::OwnedWriteBatch { self.0.db.inner.batch() }}
#[cfg(all(test, feature = "user-keyspace"))]mod tests { use super::*; use crate::config::Config;
fn test_config(path: &std::path::Path) -> Config { Config { database_path: path.to_path_buf(), ..Default::default() } }
#[tokio::test] async fn test_db_control_user_keyspace() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = test_config(tmp.path()); let hydrant = Hydrant::new(cfg).await?;
// 1. Open keyspace with custom options let ks = hydrant .db .open_keyspace("custom", fjall::KeyspaceCreateOptions::default)?;
// 2. Put a key/value ks.insert("key1", "value1").into_diagnostic()?; assert_eq!( ks.get("key1").into_diagnostic()?.as_deref(), Some(b"value1" as &[u8]) );
// 3. Verify it is prefixed (maps to user_custom) let prefixed_ks = hydrant .state .db .inner .keyspace("user:custom", fjall::KeyspaceCreateOptions::default) .into_diagnostic()?; assert_eq!( prefixed_ks.get("key1").into_diagnostic()?.as_deref(), Some(b"value1" as &[u8]) );
// 4. Verify it does not map to unprefixed "custom" let unprefixed_ks = hydrant .state .db .inner .keyspace("custom", fjall::KeyspaceCreateOptions::default) .into_diagnostic()?; assert_eq!( unprefixed_ks.get("key1").into_diagnostic()?.as_deref(), None );
// 5. Test batch functionality let mut batch = hydrant.db.write_batch(); batch.insert(&ks, "key2", "value2"); batch.commit().into_diagnostic()?;
assert_eq!( ks.get("key2").into_diagnostic()?.as_deref(), Some(b"value2" as &[u8]) );
Ok(()) }}
#[cfg(test)]mod host_listing_tests { use super::*; use crate::db::{keys, set_ks_count}; use crate::pds_meta::HostStatus;
fn test_config(path: &std::path::Path) -> Config { Config { database_path: path.to_path_buf(), ..Default::default() } }
#[tokio::test] async fn list_hosts_includes_seeded_hosts_without_cursors() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let hydrant = Hydrant::new(test_config(tmp.path())).await?;
{ let state = hydrant.state.clone(); tokio::task::spawn_blocking(move || -> Result<()> { let mut batch = state.db.inner.batch(); crate::db::pds_meta::set_status( &mut batch, &state.db.filter, "offline.example", HostStatus::Offline, )?; crate::db::pds_meta::set_status( &mut batch, &state.db.filter, "active.example", HostStatus::Active, )?; set_ks_count( &mut batch, &state.db, &keys::pds_account_count_key("offline.example"), 7, ); set_ks_count( &mut batch, &state.db, &keys::pds_account_count_key("active.example"), 42, ); state .db .cursors .insert( keys::firehose_cursor_key("active.example"), 123_i64.to_be_bytes(), ) .into_diagnostic()?; batch.commit().into_diagnostic()?; state.db.persist() }) .await .into_diagnostic()??;
crate::pds_meta::PdsMeta::update_host( &hydrant.state.pds_meta, "offline.example", |h| { h.status = HostStatus::Offline; }, ); crate::pds_meta::PdsMeta::update_host(&hydrant.state.pds_meta, "active.example", |h| { h.status = HostStatus::Active; }); hydrant.state.db.update_count("p|offline.example", 7); hydrant.state.db.update_count("p|active.example", 42); }
let (hosts, next) = hydrant.list_hosts(None, 10).await?; assert!(next.is_none());
let offline = hosts .iter() .find(|h| h.name == "offline.example") .expect("seeded host without cursor should be listed"); let active = hosts .iter() .find(|h| h.name == "active.example") .expect("host with cursor should be listed");
assert_eq!(offline.seq, 0); assert_eq!(offline.account_count, 7); assert_eq!(offline.status, HostStatus::Offline);
assert_eq!(active.seq, 123); assert_eq!(active.account_count, 42); assert_eq!(active.status, HostStatus::Active);
Ok(()) }}