//! Loading, reloading and sharing named sources. //! //! Sources are declared once from the top-level `[sources.]` tables, //! before any filter is built, and live in a process-global registry. Filters //! name the sources they use in their own config (`exempt_source = "premium"`) //! and resolve them while they deserialize, through [`PubkeyRef`] and //! [`WordsRef`]. A typo is therefore a startup error, like any other bad //! config, never a silently empty list. //! //! ## Why a snapshot and a background thread //! //! `filter_note` runs synchronously on strfry's ingest path, so no fetch may //! happen there. Each source holds an `Arc` snapshot behind an `RwLock`; a note //! only clones the `Arc` (a refcount bump), while one background thread per //! process refetches every `reload_secs` and swaps in a new snapshot when the //! body parses. On any failure the last good snapshot stays in place. //! //! The first load happens synchronously at startup, bounded by `timeout_secs`, //! so a list-gated relay does not reject the first notes after every restart. //! If it fails, the optional `cache_path` (the last good body, written after //! every successful fetch) is used instead, which covers a restart during an //! API outage. //! //! strfry runs one plugin process per ingester thread, so each source is //! fetched by each process. Cache writes go through a per-process temp file //! and an atomic rename, so concurrent writers never leave a torn file. use super::parse::{parse_nip05, parse_pubkeys, parse_words, Format, PubkeySet, WordList}; use log::{error, info, warn}; use serde::{Deserialize, Deserializer}; use std::collections::HashMap; use std::io::Read; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; /// Floor for `reload_secs`, so a typo cannot hammer the API. pub const MIN_RELOAD_SECS: u64 = 30; const DEFAULT_RELOAD_SECS: u64 = 300; const DEFAULT_TIMEOUT_SECS: u64 = 10; const DEFAULT_MAX_BYTES: u64 = 10 * 1024 * 1024; /// One `[sources.]` table. #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct SourceConfig { /// `https://...`, `http://...`, `file:///abs/path` or a plain file path. pub url: String, /// How the body is parsed. pub format: Format, /// Name of the env var holding a bearer token for HTTP sources. The token /// itself never goes in the config file. #[serde(default)] pub token_env: Option, /// Seconds between reloads. Default 300, minimum [`MIN_RELOAD_SECS`]. #[serde(default)] pub reload_secs: Option, /// Per-request timeout in seconds for HTTP sources. Default 10. #[serde(default)] pub timeout_secs: Option, /// Bodies larger than this are rejected. Default 10 MiB. #[serde(default)] pub max_bytes: Option, /// Where to keep the last good body for restarts during an outage. #[serde(default)] pub cache_path: Option, } impl SourceConfig { pub fn reload_interval(&self) -> Duration { Duration::from_secs( self.reload_secs .unwrap_or(DEFAULT_RELOAD_SECS) .max(MIN_RELOAD_SECS), ) } pub fn timeout(&self) -> Duration { Duration::from_secs(self.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS).max(1)) } pub fn max_bytes(&self) -> u64 { self.max_bytes.unwrap_or(DEFAULT_MAX_BYTES) } pub fn is_http(&self) -> bool { self.url.starts_with("http://") || self.url.starts_with("https://") } } /// Seconds since the unix epoch, the clock list expiries are compared to. pub fn now_unix() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } /// Read all of `reader`, failing if it holds more than `max` bytes. pub(crate) fn read_capped(reader: impl Read, max: u64) -> Result, String> { let mut body = Vec::new(); reader .take(max.saturating_add(1)) .read_to_end(&mut body) .map_err(|e| e.to_string())?; if body.len() as u64 > max { return Err(format!("body exceeds max_bytes ({max})")); } Ok(body) } fn read_file(path: &str, max: u64) -> Result, String> { let file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?; read_capped(file, max).map_err(|e| format!("{path}: {e}")) } /// Fetch a source's raw body from wherever its `url` points. fn fetch(config: &SourceConfig) -> Result, String> { if config.is_http() { #[cfg(feature = "remote")] return super::http::fetch(config); #[cfg(not(feature = "remote"))] return Err("http(s) sources need the `remote` build feature".to_string()); } let path = config.url.strip_prefix("file://").unwrap_or(&config.url); read_file(path, config.max_bytes()) } /// Atomically replace `path` with `body`: write a per-process temp file, then /// rename it over the target. fn write_cache(path: &str, body: &[u8]) -> std::io::Result<()> { let tmp = format!("{path}.tmp.{}", std::process::id()); std::fs::write(&tmp, body)?; std::fs::rename(&tmp, path) } /// A list type a source can hold. pub trait List: Send + Sync + Sized + 'static { /// Parse a body. Returns the list and how many entries were skipped. fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String>; fn len(&self) -> usize; } impl List for PubkeySet { fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> { match format { Format::Pubkeys => parse_pubkeys(body), Format::Nip05 => parse_nip05(body), Format::Words => Err("format `words` does not hold pubkeys".to_string()), } } fn len(&self) -> usize { PubkeySet::len(self) } } impl List for WordList { fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> { match format { Format::Words => parse_words(body), Format::Pubkeys | Format::Nip05 => { Err(format!("format `{format:?}` does not hold words")) } } } fn len(&self) -> usize { self.0.len() } } /// A named, reloadable list. `None` in the snapshot means it has never loaded /// (no fetch and no cache succeeded), which a gate treats differently from an /// empty list. pub struct Source { name: String, config: SourceConfig, snapshot: RwLock>>, loaded_at: Mutex>, } impl Source { fn new(name: &str, config: SourceConfig) -> Self { Source { name: name.to_string(), config, snapshot: RwLock::new(None), loaded_at: Mutex::new(None), } } pub fn name(&self) -> &str { &self.name } /// The current list, or `None` if it has never loaded. Cheap: one `Arc` /// clone under a read lock. pub fn get(&self) -> Option> { self.snapshot .read() .unwrap_or_else(PoisonError::into_inner) .clone() } pub fn is_loaded(&self) -> bool { self.get().is_some() } fn swap(&self, list: T) { *self .snapshot .write() .unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(list)); *self .loaded_at .lock() .unwrap_or_else(PoisonError::into_inner) = Some(Instant::now()); } /// Fetch, parse and swap in a new snapshot, then refresh the cache. On any /// error the current snapshot is left untouched. Returns the entry count. pub fn reload(&self) -> Result { let body = fetch(&self.config)?; let (list, skipped) = T::parse(self.config.format, &body)?; let count = list.len(); self.swap(list); info!( "source {}: loaded {count} entries ({skipped} skipped)", self.name ); if let Some(path) = &self.config.cache_path { if let Err(e) = write_cache(path, &body) { warn!("source {}: could not write cache {path}: {e}", self.name); } } Ok(count) } fn load_cache(&self) -> Result { let path = self.config.cache_path.as_deref().ok_or("no cache_path")?; let body = read_file(path, self.config.max_bytes())?; let (list, _) = T::parse(self.config.format, &body)?; let count = list.len(); self.swap(list); Ok(count) } /// Startup load: the source itself, else the disk cache, else leave the /// list unavailable (logged as an error). pub fn initial_load(&self) { let Err(e) = self.reload() else { return }; match self.load_cache() { Ok(n) => warn!( "source {}: fetch failed ({e}); using cached copy with {n} entries", self.name ), Err(cache_err) => error!( "source {}: fetch failed ({e}) and no usable cache ({cache_err}); \ list unavailable until a reload succeeds", self.name ), } } } /// The type-erased view the reload thread needs. trait Reload: Send + Sync { fn initial_load(&self); fn reload_logged(&self); fn interval(&self) -> Duration; } impl Reload for Source { fn initial_load(&self) { Source::initial_load(self) } fn reload_logged(&self) { if let Err(e) = self.reload() { let age = self .loaded_at .lock() .unwrap_or_else(PoisonError::into_inner) .map(|t| format!("{}s old", t.elapsed().as_secs())) .unwrap_or_else(|| "never loaded".to_string()); warn!( "source {}: reload failed, keeping last good copy ({age}): {e}", self.name ); } } fn interval(&self) -> Duration { self.config.reload_interval() } } #[derive(Clone)] enum Entry { Pubkeys(Arc>), Words(Arc>), } static REGISTRY: OnceLock>> = OnceLock::new(); fn registry() -> MutexGuard<'static, HashMap> { REGISTRY .get_or_init(Default::default) .lock() .unwrap_or_else(PoisonError::into_inner) } /// Sources registered by [`declare`] and not yet loaded; hand them to [`start`]. pub struct Declared(Vec>); /// Register every `[sources.]` table so filters can resolve them, without /// loading anything yet. Fails on a config that can never work. pub fn declare(configs: &HashMap) -> Result { let mut declared: Vec> = Vec::new(); let mut reg = registry(); for (name, config) in configs { if config.is_http() && !cfg!(feature = "remote") { return Err(format!( "source `{name}`: http(s) url needs a build with --features remote" )); } // Log whether the token is there, never the token itself. A missing // token is not fatal: the fetch fails and the cache (if any) is used. if let Some(var) = &config.token_env { if std::env::var_os(var).is_some() { info!("source {name}: bearer token from ${var}"); } else { error!("source {name}: token_env ${var} is not set"); } } let entry = match config.format { Format::Pubkeys | Format::Nip05 => { let source = Arc::new(Source::::new(name, config.clone())); declared.push(source.clone()); Entry::Pubkeys(source) } Format::Words => { let source = Arc::new(Source::::new(name, config.clone())); declared.push(source.clone()); Entry::Words(source) } }; reg.insert(name.clone(), entry); } Ok(Declared(declared)) } /// Load every declared source once (synchronously), then reload each on its /// own interval from one background thread. pub fn start(declared: Declared) { let sources = declared.0; if sources.is_empty() { return; } for source in &sources { source.initial_load(); } std::thread::Builder::new() .name("noteguard-sources".to_string()) .spawn(move || { let mut next: Vec = sources .iter() .map(|s| Instant::now() + s.interval()) .collect(); loop { let (i, due) = next .iter() .copied() .enumerate() .min_by_key(|(_, due)| *due) .expect("sources is non-empty"); std::thread::sleep(due.saturating_duration_since(Instant::now())); sources[i].reload_logged(); next[i] = Instant::now() + sources[i].interval(); } }) .expect("spawn source reload thread"); } fn unknown(name: &str) -> String { format!("unknown source `{name}`: declare it under [sources.{name}]") } /// Resolve a declared pubkey source by name. pub fn pubkey_source(name: &str) -> Result>, String> { match registry().get(name) { Some(Entry::Pubkeys(source)) => Ok(source.clone()), Some(_) => Err(format!("source `{name}` is not a pubkey list")), None => Err(unknown(name)), } } /// Resolve a declared word source by name. pub fn word_source(name: &str) -> Result>, String> { match registry().get(name) { Some(Entry::Words(source)) => Ok(source.clone()), Some(_) => Err(format!("source `{name}` is not a word list")), None => Err(unknown(name)), } } /// A filter config field naming a pubkey source, resolved while the filter /// deserializes (`exempt_source = "premium"`). pub struct PubkeyRef(Arc>); impl<'de> Deserialize<'de> for PubkeyRef { fn deserialize>(deserializer: D) -> Result { let name = String::deserialize(deserializer)?; pubkey_source(&name) .map(PubkeyRef) .map_err(serde::de::Error::custom) } } impl PubkeyRef { /// Whether `pubkey` is in the list and not expired. `false` while the list /// has never loaded. pub fn is_active(&self, pubkey: &str) -> bool { self.0 .get() .is_some_and(|set| set.is_active(pubkey, now_unix())) } pub fn is_loaded(&self) -> bool { self.0.is_loaded() } pub fn name(&self) -> &str { self.0.name() } } /// A filter config field naming a word source (`words_source = "words"`). pub struct WordsRef(Arc>); impl<'de> Deserialize<'de> for WordsRef { fn deserialize>(deserializer: D) -> Result { let name = String::deserialize(deserializer)?; word_source(&name) .map(WordsRef) .map_err(serde::de::Error::custom) } } impl WordsRef { /// The current word list, or `None` if it has never loaded. pub fn get(&self) -> Option> { self.0.get() } } /// Helpers for filter tests: register in-memory sources under unique names. #[cfg(test)] #[allow(dead_code)] // used by the filter tests as each filter gains sources pub(crate) mod testing { use super::*; fn config(format: Format) -> SourceConfig { SourceConfig { url: "/nonexistent/noteguard-test-source".to_string(), format, token_env: None, reload_secs: None, timeout_secs: None, max_bytes: None, cache_path: None, } } /// Register pubkey source `name`. `None` leaves it never loaded. pub fn pubkeys(name: &str, entries: Option<&[(&str, Option)]>) { let source = Arc::new(Source::::new(name, config(Format::Pubkeys))); if let Some(entries) = entries { let mut set = PubkeySet::default(); for (pk, exp) in entries { set.insert(pk.to_string(), *exp); } source.swap(set); } registry().insert(name.to_string(), Entry::Pubkeys(source)); } /// Register word source `name`, or replace its snapshot if it exists (a /// simulated reload). `None` leaves a new source never loaded. pub fn words(name: &str, words: Option<&[&str]>) { let existing = word_source(name).ok(); let source = existing .clone() .unwrap_or_else(|| Arc::new(Source::::new(name, config(Format::Words)))); if let Some(words) = words { source.swap(WordList(words.iter().map(|w| w.to_string()).collect())); } if existing.is_none() { registry().insert(name.to_string(), Entry::Words(source)); } } } #[cfg(test)] mod tests { use super::*; const A: &str = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93"; const B: &str = "879d67486027539073d6531d271e3791b15c3e48becbfe4c3727e93355330cc8"; /// A per-test temp path, so parallel tests never share files. fn tmp(name: &str) -> String { std::env::temp_dir() .join(format!("noteguard-src-{}-{name}", std::process::id())) .to_string_lossy() .into_owned() } fn cfg(toml_cfg: &str) -> SourceConfig { toml::from_str(toml_cfg).expect("valid source config") } /// Declare one source called `name` and return its pubkey handle. fn declare_pubkeys(name: &str, config: SourceConfig) -> Arc> { declare(&HashMap::from([(name.to_string(), config)])).expect("declares"); pubkey_source(name).expect("resolves") } #[test] fn file_source_loads_at_start() { let path = tmp("loads"); std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap(); let src = declare_pubkeys( "t_loads", cfg(&format!("url = \"file://{path}\"\nformat = \"pubkeys\"")), ); assert!(!src.is_loaded()); src.initial_load(); assert!(src.get().unwrap().is_active(A, 0)); } #[test] fn reload_picks_up_change() { let path = tmp("change"); std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap(); let src = declare_pubkeys( "t_change", cfg(&format!("url = \"{path}\"\nformat = \"pubkeys\"")), ); src.initial_load(); std::fs::write(&path, format!(r#"["{B}"]"#)).unwrap(); assert_eq!(src.reload(), Ok(1)); let set = src.get().unwrap(); assert!(!set.is_active(A, 0)); assert!(set.is_active(B, 0)); } #[test] fn bad_reload_keeps_last_good() { let path = tmp("bad"); std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap(); let src = declare_pubkeys( "t_bad", cfg(&format!("url = \"{path}\"\nformat = \"pubkeys\"")), ); src.initial_load(); std::fs::write(&path, "502").unwrap(); assert!(src.reload().is_err()); std::fs::remove_file(&path).unwrap(); assert!(src.reload().is_err()); assert!(src.get().unwrap().is_active(A, 0)); } #[test] fn oversize_rejected_keeps_last_good() { let path = tmp("oversize"); let body = format!(r#"["{A}"]"#); std::fs::write(&path, &body).unwrap(); let src = declare_pubkeys( "t_oversize", cfg(&format!( "url = \"{path}\"\nformat = \"pubkeys\"\nmax_bytes = {}", body.len() )), ); src.initial_load(); assert!(src.is_loaded()); // One byte over the cap is rejected. std::fs::write(&path, format!(r#"["{B}" ]"#)).unwrap(); assert!(src.reload().unwrap_err().contains("max_bytes")); assert!(src.get().unwrap().is_active(A, 0)); } #[test] fn cache_written_after_success() { let (path, cache) = (tmp("cw-src"), tmp("cw-cache")); let body = format!(r#"["{A}"]"#); std::fs::write(&path, &body).unwrap(); let src = declare_pubkeys( "t_cache_write", cfg(&format!( "url = \"{path}\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\"" )), ); src.initial_load(); assert_eq!(std::fs::read_to_string(&cache).unwrap(), body); } #[test] fn cache_used_when_source_missing_at_start() { let cache = tmp("cu-cache"); std::fs::write( &cache, format!(r#"[{{"pubkey": "{A}", "expires_at": null}}]"#), ) .unwrap(); let src = declare_pubkeys( "t_cache_use", cfg(&format!( "url = \"{}\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\"", tmp("cu-missing") )), ); src.initial_load(); assert!(src.get().unwrap().is_active(A, 0)); } #[test] fn never_loaded_is_none() { let src = declare_pubkeys( "t_never", cfg(&format!( "url = \"{}\"\nformat = \"pubkeys\"", tmp("never-missing") )), ); src.initial_load(); assert!(src.get().is_none()); } #[test] fn format_mismatch_is_error() { declare(&HashMap::from([( "t_words_only".to_string(), cfg("url = \"/x\"\nformat = \"words\""), )])) .unwrap(); assert!(pubkey_source("t_words_only") .err() .unwrap() .contains("not a pubkey list")); assert!(word_source("t_words_only").is_ok()); assert!(pubkey_source("t_nobody_declared_this") .err() .unwrap() .contains("unknown source")); } #[test] fn ref_resolves_while_deserializing() { testing::pubkeys("t_ref", Some(&[("pk", None)])); #[derive(Deserialize)] struct Filter { exempt_source: PubkeyRef, } let f: Filter = toml::from_str("exempt_source = \"t_ref\"").unwrap(); assert!(f.exempt_source.is_active("pk")); assert_eq!(f.exempt_source.name(), "t_ref"); let err = toml::from_str::("exempt_source = \"t_ref_typo\"") .err() .unwrap(); assert!(err.to_string().contains("unknown source")); } #[test] fn reload_interval_clamped() { assert_eq!( cfg("url = \"/x\"\nformat = \"words\"").reload_interval(), Duration::from_secs(300) ); assert_eq!( cfg("url = \"/x\"\nformat = \"words\"\nreload_secs = 1").reload_interval(), Duration::from_secs(MIN_RELOAD_SECS) ); } #[test] fn config_rejects_unknown_keys() { assert!( toml::from_str::("url = \"/x\"\nformat = \"words\"\nreload = 5").is_err() ); assert!(toml::from_str::("url = \"/x\"\nformat = \"nope\"").is_err()); } #[cfg(not(feature = "remote"))] #[test] fn http_url_without_feature_fails_declare() { let err = declare(&HashMap::from([( "t_http_nofeature".to_string(), cfg("url = \"https://example.com/list\"\nformat = \"pubkeys\""), )])) .err() .unwrap(); assert!(err.contains("--features remote")); } }