From 4e040d728fc9df82c1ecfee2e6762fe0ffca6bd9 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Sun, 26 Jul 2026 11:46:27 +0300 Subject: [PATCH] [crawler] add relay-first deep discovery --- docs/api/crawler.md | 8 +- docs/concepts/relay.md | 11 +- docs/configuration.md | 2 +- src/api/crawler.rs | 23 +- src/config/env.rs | 1 + src/config/types.rs | 29 +- src/control/crawler.rs | 75 ++- src/control/seed.rs | 45 +- src/crawler/by_collection.rs | 14 +- src/crawler/list_repos/checker.rs | 2 +- src/crawler/list_repos/producer.rs | 243 +++++++- src/crawler/list_repos/retry.rs | 2 +- src/crawler/mod.rs | 2 + src/crawler/relay_first.rs | 901 +++++++++++++++++++++++++++++ src/crawler/worker.rs | 111 +++- src/db/keys/indexer.rs | 32 + src/lib.rs | 1 + src/pds_discovery.rs | 99 ++++ tests/api_crawler_sources.nu | 11 + 19 files changed, 1503 insertions(+), 109 deletions(-) create mode 100644 src/crawler/relay_first.rs create mode 100644 src/pds_discovery.rs diff --git a/docs/api/crawler.md b/docs/api/crawler.md index 0f113ff..f3a98b3 100644 --- a/docs/api/crawler.md +++ b/docs/api/crawler.md @@ -4,9 +4,7 @@ title: crawler management ## GET /crawler/sources -list all currently active crawler sources. returns a JSON array of `{ "url": string, "mode": "relay" | "by_collection", "persisted": bool }`. - -`persisted: true` means the source was added via the API and is stored in the database; it will survive a restart. `persisted: false` means the source came from `CRAWLER_URLS` and is not written to the database. +list all currently active crawler sources. returns a JSON array of `{ "url": string, "mode": "list_repos" | "relay_first" | "by_collection" }`. ## POST /crawler/sources @@ -15,7 +13,7 @@ add a crawler source at runtime. | field | description | | :--- | :--- | | `url` | URL of the crawler source | -| `mode` | `"relay"` or `"by_collection"` | +| `mode` | `"list_repos"`, `"relay_first"`, or `"by_collection"`. `relay_first` is the explicit coverage-over-moderation mode described in [relay crawler sources](../concepts/relay.md#crawler-sources) | the source is written to the database before the producer task is started, so it is safe to add sources and then immediately restart without losing them. @@ -47,4 +45,4 @@ reset stored cursors for a given crawler URL. | :--- | :--- | | `key` | URL of the crawler source to reset | -clears the list-repos crawler cursor as well as any by-collection cursors associated with that URL. causes the next crawler pass to restart from the beginning. +clears the list-repos crawler cursor as well as any by-collection or relay-first pass, host, and per-PDS cursors associated with that URL. causes the next crawler pass to restart from the beginning. diff --git a/docs/concepts/relay.md b/docs/concepts/relay.md index 0a1a75e..7394712 100644 --- a/docs/concepts/relay.md +++ b/docs/concepts/relay.md @@ -42,13 +42,22 @@ seeding runs from latest cursor on restart so new PDS' added to the upstream rel the crawler is configured separately from the firehose via `CRAWLER_URLS`. each source is a `[mode::]url` entry where the mode prefix is optional and defaults to `by_collection` in filter mode or `list_repos` in full-network mode. -- `list_repos`: enumerates the network via `com.atproto.sync.listRepos`, checks each repo's collections via `describeRepo`. +- `list_repos`: enumerates the relay via `com.atproto.sync.listRepos`. relay account status is reconciled for repos already known to hydrant; filtered indexes check unknown repos with `describeRepo` before enqueueing them. +- `relay_first`: an explicit coverage-over-moderation opt-in. it completes the relay's authoritative `listRepos` pass first, then calls the same relay's `listHosts` and crawls `listRepos` on each safe, non-banned PDS. relay-listed inactive repos are retained as status tombstones, so deep pages can only add DIDs the relay did not list and never update relay-authoritative status or revision state. this may discover inactive or other repositories omitted by the relay, which also means it deliberately bypasses relay-level repository moderation for those unknown DIDs. local PDS bans and filter excludes still win. - `by_collection`: queries `com.atproto.sync.listReposByCollection` for each configured signal. more efficient for filtered indexing since it only surfaces repos that have matching records. cursors are stored per collection. note that it won't crawl anything if no signals are specified. ``` CRAWLER_URLS=by_collection::https://lightrail.microcosm.blue,list_repos::wss://bsky.network ``` +for deep discovery in a full-network indexer: + +``` +CRAWLER_URLS=relay_first::https://relay.fire.hose.cam +``` + +`relay_first` processes at most four PDSes concurrently. each PDS request uses the shared per-PDS concurrency gate and rate-tier pacing, holds its permit through the bounded response read, and feeds 429/hard failures back into the normal PDS throttler. unsafe/private DNS targets, locally or upstream-banned hosts, offline hosts, and PDSes without `listRepos` support are skipped. relay-pass, `listHosts`, and per-PDS cursors are durable; a restart resumes the last committed page, and `/crawler/cursors` clears all of them for the source. + each source maintains its own cursor so restarts resume mid-pass. sources can also be added and removed at runtime via the `/crawler/sources` API (see [crawler management](../api/crawler.md)). dynamically added sources are persisted to the database and survive restarts. `CRAWLER_URLS` sources are startup-only: they are not written to the database and will always reappear after a restart regardless of runtime changes (unless you change the config of course). diff --git a/docs/configuration.md b/docs/configuration.md index 027ab5e..d069e1c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -46,7 +46,7 @@ hydrant is configured via environment variables, all prefixed with `HYDRANT_` (e | variable | default | description | | :--- | :--- | :--- | -| `CRAWLER_URLS` | relay hosts (full network), `https://lightrail.microcosm.blue` (filter) | comma-separated list of `[mode::]url` crawler sources. mode is `relay` or `by_collection`; bare URLs use the default mode. set to empty string to disable crawling | +| `CRAWLER_URLS` | relay hosts (full network), `https://lightrail.microcosm.blue` (filter) | comma-separated list of `[mode::]url` crawler sources. mode is `list_repos`, `relay_first`, or `by_collection`; bare URLs use the default mode. `relay_first` is an explicit coverage-over-moderation opt-in. set to empty string to disable crawling | | `ENABLE_CRAWLER` | `true` if full network or sources configured | whether to actively query the network for unknown repositories | | `CRAWLER_MAX_PENDING_REPOS` | `2000` (`25000` full network) | persistent discovery lookahead retained in the pending queue before the crawler pauses; this does not increase active backfill task concurrency | | `CRAWLER_RESUME_PENDING_REPOS` | `1000` (`12500` full network) | pending-repo count at which discovery resumes | diff --git a/src/api/crawler.rs b/src/api/crawler.rs index 45248d2..369fafb 100644 --- a/src/api/crawler.rs +++ b/src/api/crawler.rs @@ -1,4 +1,3 @@ -use std::net::IpAddr; use std::time::Duration; use axum::{ @@ -31,24 +30,6 @@ pub struct AddSourceRequest { pub mode: CrawlerMode, } -fn is_private_ip(ip: IpAddr) -> bool { - match ip { - IpAddr::V4(ip) => { - ip.is_loopback() - || ip.is_private() - || ip.is_link_local() - || ip.is_multicast() - || ip.is_unspecified() - } - IpAddr::V6(ip) => { - ip.is_loopback() || ip.is_multicast() || ip.is_unspecified() || { - let octets = ip.octets(); - (octets[0] & 0xfe) == 0xfc || (octets[0] == 0xfe && (octets[1] & 0xc0) == 0x80) - } - } - } -} - async fn validate_source_url(url: &Url) -> Result<(), String> { use std::net::IpAddr; let scheme = url.scheme(); @@ -67,14 +48,14 @@ async fn validate_source_url(url: &Url) -> Result<(), String> { return Err("local/internal hostnames are not allowed".to_string()); } if let Ok(ip) = host.parse::() { - if is_private_ip(ip) { + if crate::pds_discovery::is_private_ip(ip) { return Err("private IP addresses are not allowed".to_string()); } } else { match tokio::net::lookup_host(format!("{}:80", host)).await { Ok(addrs) => { for addr in addrs { - if is_private_ip(addr.ip()) { + if crate::pds_discovery::is_private_ip(addr.ip()) { return Err("host resolves to a private IP address".to_string()); } } diff --git a/src/config/env.rs b/src/config/env.rs index f7991d0..b69ca93 100644 --- a/src/config/env.rs +++ b/src/config/env.rs @@ -344,6 +344,7 @@ impl Config { mode: CrawlerMode::ListRepos, }) .collect(), + CrawlerMode::RelayFirst => unreachable!("relay_first is never a default mode"), CrawlerMode::ByCollection => defaults.crawler_sources.clone(), }, }; diff --git a/src/config/types.rs b/src/config/types.rs index 1bc92ed..8c99733 100644 --- a/src/config/types.rs +++ b/src/config/types.rs @@ -65,6 +65,9 @@ impl RateTier { pub enum CrawlerMode { /// enumerate via `com.atproto.sync.listRepos`, check signals with `describeRepo`. ListRepos, + /// enumerate the relay first, then opt in to unknown-repository discovery through the + /// relay's `listHosts` PDS set. relay listings remain authoritative for known repos. + RelayFirst, /// enumerate via `com.atproto.sync.listReposByCollection` for each configured signal. /// note: if no signals are specified, this won't crawl for any repos. ByCollection, @@ -102,9 +105,10 @@ impl FromStr for CrawlerMode { fn from_str(s: &str) -> Result { match s { "list_repos" | "list-repos" => Ok(Self::ListRepos), + "relay_first" | "relay-first" => Ok(Self::RelayFirst), "by_collection" | "by-collection" => Ok(Self::ByCollection), _ => Err(miette::miette!( - "invalid crawler mode: expected 'list_repos' or 'by_collection'" + "invalid crawler mode: expected 'list_repos', 'relay_first', or 'by_collection'" )), } } @@ -114,6 +118,7 @@ impl fmt::Display for CrawlerMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::ListRepos => write!(f, "list_repos"), + Self::RelayFirst => write!(f, "relay_first"), Self::ByCollection => write!(f, "by_collection"), } } @@ -262,3 +267,25 @@ impl fmt::Display for BackfillStrategy { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relay_first_crawler_mode_round_trips() { + assert_eq!( + "relay_first".parse::().unwrap(), + CrawlerMode::RelayFirst + ); + assert_eq!( + "relay-first".parse::().unwrap(), + CrawlerMode::RelayFirst + ); + assert_eq!(CrawlerMode::RelayFirst.to_string(), "relay_first"); + assert_eq!( + serde_json::from_str::("\"relay_first\"").unwrap(), + CrawlerMode::RelayFirst + ); + } +} diff --git a/src/control/crawler.rs b/src/control/crawler.rs index c5fa29d..cc01eb6 100644 --- a/src/control/crawler.rs +++ b/src/control/crawler.rs @@ -46,7 +46,7 @@ pub(super) fn spawn_crawler_producer( enabled: watch::Receiver, ) -> ProducerHandle { use crate::config::CrawlerMode; - use crate::crawler::{ByCollectionProducer, ListReposProducer}; + use crate::crawler::{ByCollectionProducer, ListReposProducer, RelayFirstProducer}; use std::time::Duration; use tracing::Instrument; @@ -62,6 +62,25 @@ pub(super) fn spawn_crawler_producer( tx: tx.clone(), enabled, stats: stats.clone(), + completion_key: None, + last_completion: None, + } + .run() + .instrument(span), + ) + .abort_handle() + } + CrawlerMode::RelayFirst => { + info!(relay = %source.url, enabled = *state.crawler_enabled.borrow(), "starting relay-first crawler"); + let span = tracing::info_span!("relay_first", url = %source.url); + tokio::spawn( + RelayFirstProducer { + url: source.url.clone(), + checker: checker.clone(), + in_flight: in_flight.clone(), + tx: tx.clone(), + enabled, + stats: stats.clone(), } .run() .instrument(span), @@ -149,6 +168,7 @@ impl CrawlerHandle { pub async fn reset_cursor(&self, url: &str) -> Result<()> { let point_keys = [keys::crawler_cursor_key(url)]; let by_collection_prefix = keys::by_collection_cursor_prefix(url); + let relay_first_prefix = keys::relay_first_cursor_prefix(url); self.state .db .run(move |db| { @@ -160,6 +180,10 @@ impl CrawlerHandle { let k = entry.key().into_diagnostic()?; batch.remove(&db.cursors, k); } + for entry in db.cursors.prefix(&relay_first_prefix) { + let k = entry.key().into_diagnostic()?; + batch.remove(&db.cursors, k); + } batch.commit().into_diagnostic()?; db.persist() }) @@ -263,3 +287,52 @@ impl CrawlerHandle { Ok(true) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Config; + use tempfile::tempdir; + + #[tokio::test] + async fn reset_cursor_clears_relay_first_progress_for_only_that_source() -> Result<()> { + let tmp = tempdir().into_diagnostic()?; + let config = Config { + database_path: tmp.path().to_path_buf(), + ..Default::default() + }; + let state = Arc::new(AppState::new(&config)?); + let handle = CrawlerHandle { + state: state.clone(), + shared: Arc::new(std::sync::OnceLock::new()), + tasks: Arc::new(scc::HashMap::new()), + persisted: Arc::new(scc::HashSet::new()), + }; + let relay = "https://relay.example/"; + let other = "https://other.example/"; + let relay_keys = [ + keys::crawler_cursor_key(relay), + keys::relay_first_pass_key(relay), + keys::relay_first_handled_key(relay), + keys::relay_first_hosts_cursor_key(relay), + keys::relay_first_pds_cursor_key(relay, "pds.example"), + ]; + for key in &relay_keys { + state.db.cursors.insert(key, b"value").into_diagnostic()?; + } + let other_key = keys::relay_first_pass_key(other); + state + .db + .cursors + .insert(&other_key, b"other") + .into_diagnostic()?; + + handle.reset_cursor(relay).await?; + + for key in relay_keys { + assert!(state.db.cursors.get(key).into_diagnostic()?.is_none()); + } + assert!(state.db.cursors.get(other_key).into_diagnostic()?.is_some()); + Ok(()) + } +} diff --git a/src/control/seed.rs b/src/control/seed.rs index 087b5c8..93c94f9 100644 --- a/src/control/seed.rs +++ b/src/control/seed.rs @@ -9,6 +9,7 @@ use tracing::{debug, info, warn}; use url::Url; use super::firehose::FirehoseHandle; +use crate::pds_discovery::{is_safe_seed_host, list_hosts_url}; use crate::state::AppState; const MAX_CONCURRENT_SEEDS: usize = 4; @@ -228,19 +229,6 @@ fn body_preview(bytes: &[u8]) -> String { body } -fn list_hosts_url(base: &Url, cursor: Option<&str>) -> Url { - let mut url = base.clone(); - url.set_path("/xrpc/com.atproto.sync.listHosts"); - { - let mut pairs = url.query_pairs_mut(); - pairs.append_pair("limit", "1000"); - if let Some(c) = cursor { - pairs.append_pair("cursor", c); - } - } - url -} - fn apply_seed_snapshot(state: &Arc, hosts: &[Host<'_>]) -> miette::Result<()> { let mut batch = state.db.inner.batch(); let mut status_updates = Vec::with_capacity(hosts.len()); @@ -426,34 +414,3 @@ async fn read_limited_response( } Ok(buf.freeze()) } - -fn is_private_ip(ip: std::net::IpAddr) -> bool { - match ip { - std::net::IpAddr::V4(ip) => { - ip.is_loopback() - || ip.is_private() - || ip.is_link_local() - || ip.is_multicast() - || ip.is_unspecified() - } - std::net::IpAddr::V6(ip) => { - ip.is_loopback() || ip.is_multicast() || ip.is_unspecified() || { - let octets = ip.octets(); - (octets[0] & 0xfe) == 0xfc || (octets[0] == 0xfe && (octets[1] & 0xc0) == 0x80) - } - } - } -} - -fn is_safe_seed_host(host: &str) -> bool { - if host.is_empty() { - return false; - } - if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") { - return false; - } - if let Ok(ip) = host.parse::() { - return !is_private_ip(ip); - } - true -} diff --git a/src/crawler/by_collection.rs b/src/crawler/by_collection.rs index 3ce1ba5..e8b3c87 100644 --- a/src/crawler/by_collection.rs +++ b/src/crawler/by_collection.rs @@ -220,16 +220,20 @@ impl ByCollectionProducer { self.stats.record_crawled(count); cursor = next_cursor; - let cursor_update = cursor.as_ref().map(|c| CursorUpdate { - key: cursor_key.clone(), - value: Some(c.as_bytes().to_vec()), - }); + let cursor_updates = cursor + .as_ref() + .map(|c| CursorUpdate { + key: cursor_key.clone(), + value: Some(c.as_bytes().to_vec()), + }) + .into_iter() + .collect(); self.tx .send(CrawlerBatch { guards: in_flight, listings: Vec::new(), - cursor_update, + cursor_updates, }) .await .ok(); diff --git a/src/crawler/list_repos/checker.rs b/src/crawler/list_repos/checker.rs index ff1b465..f929728 100644 --- a/src/crawler/list_repos/checker.rs +++ b/src/crawler/list_repos/checker.rs @@ -290,7 +290,7 @@ impl SignalChecker { /// guards for non-confirmed DIDs are dropped here, releasing their in-flight slots. /// confirmed DIDs' retry entries are NOT removed here. the worker removes them /// atomically with the pending insert. - pub(super) async fn check_signals_batch( + pub(crate) async fn check_signals_batch( &self, in_flight: Vec, filter: &Arc, diff --git a/src/crawler/list_repos/producer.rs b/src/crawler/list_repos/producer.rs index 8694633..e46f8c7 100644 --- a/src/crawler/list_repos/producer.rs +++ b/src/crawler/list_repos/producer.rs @@ -28,6 +28,8 @@ pub(crate) struct ListReposProducer { pub(crate) tx: mpsc::Sender, pub(crate) enabled: watch::Receiver, pub(crate) stats: CrawlerStats, + pub(crate) completion_key: Option>, + pub(crate) last_completion: Option, } impl ListReposProducer { @@ -53,8 +55,36 @@ impl ListReposProducer { .and_then(|b| rmp_serde::from_slice::(b).ok())) } + async fn next_completion(&mut self, pass_complete: bool) -> Result, u64)>> { + let Some(key) = self.completion_key.clone().filter(|_| pass_complete) else { + return Ok(None); + }; + let lookup_key = key.clone(); + let current = self + .checker + .state + .db + .run(move |db| { + db.cursors + .get(lookup_key) + .into_diagnostic()? + .map(|value| { + value + .as_ref() + .try_into() + .into_diagnostic() + .map(u64::from_be_bytes) + }) + .transpose() + }) + .await?; + let next = next_completion_number(current, self.last_completion)?; + self.last_completion = Some(next); + Ok(Some((key, next))) + } + async fn crawl(&mut self) -> Result<()> { - let db = &self.checker.state.db; + let db = self.checker.state.db.clone(); let base = base_url(&self.url)?; let mut cursor = self.get_cursor().await?; @@ -118,6 +148,7 @@ impl ListReposProducer { let repos = db.repos.clone(); let filter_ks = db.filter.clone(); let crawler_ks = db.crawler.clone(); + let persist_inactive_unknown = self.completion_key.is_some(); match tokio::time::timeout( BLOCKING_TASK_TIMEOUT, @@ -144,6 +175,7 @@ impl ListReposProducer { rev: crate::db::types::DbTid::from(&repo.rev), active, status: repo.status.map(IntoStatic::into_static), + create_if_missing: false, }); } continue; @@ -152,6 +184,21 @@ impl ListReposProducer { if crawler_ks.contains_key(&retry_key).into_diagnostic()? { continue; } + if persist_inactive_unknown + && should_persist_inactive_unknown( + repo.active, + repo.status.is_some(), + ) + { + listings.push(RepoListing { + did: repo.did.into_static(), + rev: crate::db::types::DbTid::from(&repo.rev), + active: false, + status: repo.status.map(IntoStatic::into_static), + create_if_missing: true, + }); + continue; + } if should_enqueue_unknown(repo.active) { unknown.push(repo.did.into_static()); } @@ -199,18 +246,9 @@ impl ListReposProducer { pass_complete = true; } - let cursor_value = cursor - .as_ref() - .map(|c| { - rmp_serde::to_vec(c.as_str()) - .into_diagnostic() - .wrap_err("cant serialize cursor") - }) - .transpose()?; - let cursor_update = Some(CursorUpdate { - key: crawler_cursor_key(self.url.as_str()), - value: cursor_value, - }); + let completion = self.next_completion(pass_complete).await?; + let cursor_updates = + pass_cursor_updates(self.url.as_str(), cursor.as_ref(), completion)?; let in_flight = self.in_flight.acquire(unknown_dids).await; let confirmed = if filter.check_signals() && !in_flight.is_empty() { @@ -234,7 +272,7 @@ impl ListReposProducer { .send(CrawlerBatch { guards: confirmed, listings, - cursor_update, + cursor_updates, }) .await .ok(); @@ -258,9 +296,63 @@ fn should_enqueue_unknown(active: Option) -> bool { active != Some(false) } +fn should_persist_inactive_unknown(active: Option, has_status: bool) -> bool { + active == Some(false) || (active.is_none() && has_status) +} + +fn next_completion_number(persisted: Option, last_issued: Option) -> Result { + persisted + .into_iter() + .chain(last_issued) + .max() + .unwrap_or(0) + .checked_add(1) + .ok_or_else(|| miette::miette!("relay-first pass counter overflow")) +} + +fn pass_cursor_updates( + relay: &str, + cursor: Option<&SmolStr>, + completion: Option<(Vec, u64)>, +) -> Result> { + let cursor_value = cursor + .map(|cursor| { + rmp_serde::to_vec(cursor.as_str()) + .into_diagnostic() + .wrap_err("cant serialize cursor") + }) + .transpose()?; + let mut updates = vec![CursorUpdate { + key: crawler_cursor_key(relay), + value: cursor_value, + }]; + if let Some((key, pass)) = completion { + updates.push(CursorUpdate { + key, + value: Some(pass.to_be_bytes().to_vec()), + }); + } + Ok(updates) +} + #[cfg(test)] mod tests { - use super::should_enqueue_unknown; + use super::{ + ListReposProducer, next_completion_number, pass_cursor_updates, should_enqueue_unknown, + should_persist_inactive_unknown, + }; + use crate::config::Config; + use crate::crawler::{CrawlerStats, CrawlerWorker, InFlight, SignalChecker}; + use crate::db::keys; + use crate::state::AppState; + use axum::{Json, Router, routing::get}; + use jacquard_common::types::string::Did; + use miette::{IntoDiagnostic, Result}; + use serde_json::json; + use std::sync::Arc; + use std::time::Duration; + use tempfile::tempdir; + use url::Url; #[test] fn inactive_unknown_repo_is_not_backfilled() { @@ -268,6 +360,127 @@ mod tests { assert!(should_enqueue_unknown(Some(true))); assert!(should_enqueue_unknown(None)); } + + #[test] + fn relay_first_persists_authoritative_inactive_unknown_repo() { + assert!(should_persist_inactive_unknown(Some(false), false)); + assert!(should_persist_inactive_unknown(None, true)); + assert!(!should_persist_inactive_unknown(Some(true), true)); + assert!(!should_persist_inactive_unknown(None, false)); + } + + #[test] + fn relay_first_marker_is_only_written_with_the_terminal_cursor() { + let completion_key = b"relay_first_cursor|relay|pass"; + let cursor = "next".into(); + let mid_pass = pass_cursor_updates("https://relay.example", Some(&cursor), None).unwrap(); + assert_eq!(mid_pass.len(), 1); + assert!(mid_pass[0].value.is_some()); + + let terminal = pass_cursor_updates( + "https://relay.example", + None, + Some((completion_key.to_vec(), 7)), + ) + .unwrap(); + assert_eq!(terminal.len(), 2); + assert!(terminal[0].value.is_none()); + assert_eq!(terminal[1].key, completion_key); + assert_eq!( + terminal[1].value.as_deref(), + Some(7u64.to_be_bytes().as_slice()) + ); + } + + #[test] + fn relay_first_marker_advances_past_an_uncommitted_marker() { + assert_eq!(next_completion_number(Some(5), None).unwrap(), 6); + assert_eq!(next_completion_number(Some(5), Some(6)).unwrap(), 7); + assert!(next_completion_number(Some(u64::MAX), None).is_err()); + } + + #[tokio::test] + async fn relay_first_pass_persists_relay_inactive_unknown_as_authoritative() -> Result<()> { + const DID: &str = "did:web:relay-inactive.example"; + const HEAD: &str = "bafyreidf747c4x3lps3k4n357l3a3r57k3k465743k573k465743k5"; + let app = Router::new().route( + "/xrpc/com.atproto.sync.listRepos", + get(|| async { + Json(json!({ + "repos": [{ + "did": DID, + "head": HEAD, + "rev": "3j6s746574657", + "active": false, + "status": "takendown" + }] + })) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .into_diagnostic()?; + let address = listener.local_addr().into_diagnostic()?; + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + + let tmp = tempdir().into_diagnostic()?; + let config = Config { + database_path: tmp.path().to_path_buf(), + full_network: true, + enable_crawler: Some(true), + ..Default::default() + }; + let state = Arc::new(AppState::new(&config)?); + let stats = CrawlerStats::new(state.clone(), Vec::new(), state.throttler.clone()); + let (worker, tx) = CrawlerWorker::new(state.clone(), 100, 50, stats.clone()); + let worker = tokio::spawn(worker.run()); + let pass_key = keys::relay_first_pass_key("http://relay.example/"); + let producer = tokio::spawn( + ListReposProducer { + url: Url::parse(&format!("http://{address}/")).into_diagnostic()?, + checker: SignalChecker { + http: reqwest::Client::new(), + state: state.clone(), + throttler: state.throttler.clone(), + }, + in_flight: InFlight::new(), + tx, + enabled: state.crawler_enabled.subscribe(), + stats, + completion_key: Some(pass_key.clone()), + last_completion: None, + } + .run(), + ); + + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if state.db.cursors.get(&pass_key).ok().flatten().is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .into_diagnostic()?; + + let did = Did::new_static(DID)?; + let bytes = state + .db + .repos + .get(keys::repo_key(&did)) + .into_diagnostic()? + .expect("relay-inactive repo should be persisted"); + let repo = crate::db::deser_repo_state(&bytes)?; + assert!(!repo.active); + assert_eq!(repo.status, crate::types::RepoStatus::Takendown); + assert_eq!(state.db.indexer.pending.iter().count(), 0); + + producer.abort(); + worker.abort(); + server.abort(); + Ok(()) + } } pub(crate) async fn cursor_display(state: &AppState, relay_host: &Url) -> SmolStr { diff --git a/src/crawler/list_repos/retry.rs b/src/crawler/list_repos/retry.rs index 2f684a8..979d250 100644 --- a/src/crawler/list_repos/retry.rs +++ b/src/crawler/list_repos/retry.rs @@ -133,7 +133,7 @@ impl RetryProducer { .send(CrawlerBatch { guards: confirmed, listings: Vec::new(), - cursor_update: None, + cursor_updates: Vec::new(), }) .await .ok(); diff --git a/src/crawler/mod.rs b/src/crawler/mod.rs index 050b64c..910edf7 100644 --- a/src/crawler/mod.rs +++ b/src/crawler/mod.rs @@ -14,12 +14,14 @@ use url::Url; mod by_collection; mod list_repos; +mod relay_first; mod worker; use crate::util::throttle::Throttler; pub(crate) use by_collection::ByCollectionProducer; pub(crate) use list_repos::{ListReposProducer, RetryProducer, SignalChecker}; +pub(crate) use relay_first::RelayFirstProducer; pub(crate) use worker::{CrawlerBatch, CrawlerWorker}; #[derive(Clone)] diff --git a/src/crawler/relay_first.rs b/src/crawler/relay_first.rs new file mode 100644 index 0000000..0484124 --- /dev/null +++ b/src/crawler/relay_first.rs @@ -0,0 +1,901 @@ +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use jacquard_api::com_atproto::sync::HostStatus; +use jacquard_api::com_atproto::sync::list_hosts::{Host, ListHostsOutput}; +use jacquard_api::com_atproto::sync::list_repos::ListReposOutput; +use jacquard_common::{IntoStatic, types::string::Did}; +use miette::{Context, IntoDiagnostic, Result}; +use reqwest::StatusCode; +use reqwest::redirect::Policy; +use serde::{Deserialize, Serialize}; +use smol_str::SmolStr; +use tokio::sync::{mpsc, watch}; +use tracing::{debug, error, info, trace, warn}; +use url::Url; + +use super::list_repos::ListReposProducer; +use super::worker::{CrawlerBatch, CursorUpdate}; +use super::{CrawlerStats, InFlight, SignalChecker, base_url}; +use crate::db::keys; +use crate::pds_discovery; +use crate::state::AppState; +use crate::util::{WatchEnabledExt, parse_retry_after}; + +const MAX_CONCURRENT_PDS_CRAWLS: usize = 4; +const MAX_LIST_RESPONSE_BYTES: usize = 10 * 1024 * 1024; +const PASS_POLL_INTERVAL: Duration = Duration::from_secs(1); +const RETRY_DELAY: Duration = Duration::from_secs(30); +const BLOCKING_TASK_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_LIST_HOSTS_PAGES: usize = 100; +const MAX_PDS_PAGES: usize = 100_000; +const DNS_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +struct PassCursor { + pass: u64, + cursor: Option, + complete: bool, +} + +impl PassCursor { + fn active(pass: u64, cursor: Option) -> Self { + Self { + pass, + cursor, + complete: false, + } + } + + fn complete(pass: u64) -> Self { + Self { + pass, + cursor: None, + complete: true, + } + } +} + +pub(crate) struct RelayFirstProducer { + pub(crate) url: Url, + pub(crate) checker: SignalChecker, + pub(crate) in_flight: InFlight, + pub(crate) tx: mpsc::Sender, + pub(crate) enabled: watch::Receiver, + pub(crate) stats: CrawlerStats, +} + +impl RelayFirstProducer { + pub(crate) async fn run(self) -> Result<()> { + let pass_key = keys::relay_first_pass_key(self.url.as_str()); + let relay = ListReposProducer { + url: self.url.clone(), + checker: self.checker.clone(), + in_flight: self.in_flight.clone(), + tx: self.tx.clone(), + enabled: self.enabled.clone(), + stats: self.stats.clone(), + completion_key: Some(pass_key), + last_completion: None, + }; + let deep = DeepDiscoveryProducer { + relay_url: self.url, + checker: self.checker, + in_flight: self.in_flight, + tx: self.tx, + enabled: self.enabled, + stats: self.stats, + }; + + tokio::select! { + result = relay.run() => result, + result = deep.run() => result, + } + } +} + +struct DeepDiscoveryProducer { + relay_url: Url, + checker: SignalChecker, + in_flight: InFlight, + tx: mpsc::Sender, + enabled: watch::Receiver, + stats: CrawlerStats, +} + +impl DeepDiscoveryProducer { + async fn run(mut self) -> Result<()> { + loop { + self.enabled.wait_enabled("relay-first deep crawler").await; + let pass = match self.wait_for_unhandled_pass().await { + Ok(pass) => pass, + Err(err) => { + error!(err = ?err, "failed to read deep discovery pass state, retrying"); + tokio::time::sleep(RETRY_DELAY).await; + continue; + } + }; + info!(pass, "starting relay-first deep discovery pass"); + if let Err(err) = self.crawl_pass(pass).await { + error!(pass, err = ?err, "deep discovery pass failed, retrying"); + tokio::time::sleep(RETRY_DELAY).await; + continue; + } + info!(pass, "relay-first deep discovery pass complete"); + } + } + + async fn wait_for_unhandled_pass(&mut self) -> Result { + let pass_key = keys::relay_first_pass_key(self.relay_url.as_str()); + let handled_key = keys::relay_first_handled_key(self.relay_url.as_str()); + loop { + self.enabled.wait_enabled("relay-first deep crawler").await; + let state = self.checker.state.clone(); + let pass_key = pass_key.clone(); + let handled_key = handled_key.clone(); + let (pass, handled) = state + .db + .run(move |db| { + Ok(( + read_u64(&db.cursors, &pass_key)?, + read_u64(&db.cursors, &handled_key)?, + )) + }) + .await?; + if let Some(pass) = pass + && handled.is_none_or(|handled| pass > handled) + { + return Ok(pass); + } + + tokio::select! { + _ = tokio::time::sleep(PASS_POLL_INTERVAL) => {} + changed = self.enabled.changed() => { + if changed.is_err() { + miette::bail!("crawler enable channel closed"); + } + } + } + } + } + + async fn crawl_pass(&mut self, pass: u64) -> Result<()> { + let cursor_key = keys::relay_first_hosts_cursor_key(self.relay_url.as_str()); + let mut cursor = self + .load_cursor(&cursor_key, pass) + .await? + .and_then(|state| (!state.complete).then_some(state.cursor).flatten()); + let mut page_count = 0usize; + + loop { + page_count += 1; + if page_count > MAX_LIST_HOSTS_PAGES { + miette::bail!("listHosts exceeded {MAX_LIST_HOSTS_PAGES} pages"); + } + self.enabled.wait_enabled("relay-first deep crawler").await; + let url = pds_discovery::list_hosts_url(&base_url(&self.relay_url)?, cursor.as_deref()); + let response = self + .checker + .http + .get(url.clone()) + .send() + .await + .into_diagnostic() + .wrap_err_with(|| format!("failed to fetch {url}"))? + .error_for_status() + .into_diagnostic() + .wrap_err_with(|| format!("listHosts returned an error for {url}"))?; + let bytes = crate::util::read_limited_bytes(response, MAX_LIST_RESPONSE_BYTES).await?; + let output = serde_json::from_slice::(&bytes) + .into_diagnostic() + .wrap_err("failed to parse listHosts response")? + .into_static(); + let next_cursor = output.cursor.map(|value| SmolStr::new(value.as_ref())); + let hosts: Vec> = output.hosts; + let mut crawls = tokio::task::JoinSet::new(); + for host in hosts { + if crawls.len() >= MAX_CONCURRENT_PDS_CRAWLS + && let Some(result) = crawls.join_next().await + { + log_pds_crawl_result(result); + } + let producer = self.clone_for_host(); + crawls.spawn(async move { + let hostname = host.hostname.to_string(); + (hostname, producer.crawl_host(pass, host).await) + }); + } + while let Some(result) = crawls.join_next().await { + log_pds_crawl_result(result); + } + + if next_cursor.is_some() && next_cursor == cursor { + miette::bail!("listHosts returned the same cursor twice"); + } + + let cursor_updates = if let Some(next) = &next_cursor { + vec![CursorUpdate { + key: cursor_key.clone(), + value: Some(serialize_cursor(&PassCursor::active( + pass, + Some(next.clone()), + ))?), + }] + } else { + vec![ + CursorUpdate { + key: keys::relay_first_handled_key(self.relay_url.as_str()), + value: Some(pass.to_be_bytes().to_vec()), + }, + CursorUpdate { + key: cursor_key.clone(), + value: None, + }, + ] + }; + self.send_cursor_updates(cursor_updates).await?; + + let Some(next) = next_cursor else { + return Ok(()); + }; + cursor = Some(next); + } + } + + fn clone_for_host(&self) -> Self { + Self { + relay_url: self.relay_url.clone(), + checker: self.checker.clone(), + in_flight: self.in_flight.clone(), + tx: self.tx.clone(), + enabled: self.enabled.clone(), + stats: self.stats.clone(), + } + } + + async fn crawl_host(mut self, pass: u64, host: Host<'static>) -> Result<()> { + let hostname = host.hostname.as_ref(); + if matches!( + host.status, + Some(HostStatus::Banned | HostStatus::Offline | HostStatus::Throttled) + ) { + debug!(%hostname, status = ?host.status, "skipping unavailable deep-discovery PDS"); + return Ok(()); + } + let pds = Url::parse(&format!("https://{hostname}/")) + .into_diagnostic() + .wrap_err("invalid PDS hostname from listHosts")?; + let Some(url_host) = pds.host_str() else { + miette::bail!("PDS hostname did not produce a URL host"); + }; + if !url_host.eq_ignore_ascii_case(hostname) + || pds.port().is_some() + || pds.path() != "/" + || pds.query().is_some() + || pds.fragment().is_some() + || !pds.username().is_empty() + || pds.password().is_some() + || !pds_discovery::is_safe_seed_host(url_host) + { + warn!(%hostname, "unsafe/private hostname in listHosts response, skipping deep discovery"); + return Ok(()); + } + let Some(http) = public_pds_client(url_host).await? else { + warn!(%hostname, "unsafe/private DNS result for listHosts hostname, skipping deep discovery"); + return Ok(()); + }; + if self.checker.state.pds_meta.load().is_banned(url_host) { + debug!(%hostname, "locally banned PDS, skipping deep discovery"); + return Ok(()); + } + let account_count = host + .account_count + .and_then(|count| u64::try_from(count).ok()) + .unwrap_or(1) + .max(1); + self.crawl_pds(pass, &pds, account_count, &http).await + } + + async fn crawl_pds( + &mut self, + pass: u64, + pds: &Url, + account_count: u64, + http: &reqwest::Client, + ) -> Result<()> { + let hostname = pds + .host_str() + .ok_or_else(|| miette::miette!("PDS URL has no hostname"))?; + let cursor_key = keys::relay_first_pds_cursor_key(self.relay_url.as_str(), hostname); + let saved = self.load_cursor(&cursor_key, pass).await?; + if saved.as_ref().is_some_and(|cursor| cursor.complete) { + trace!(%hostname, pass, "deep PDS crawl already complete"); + return Ok(()); + } + let mut cursor = saved.and_then(|state| state.cursor); + let mut page_count = 0usize; + + loop { + page_count += 1; + if page_count > MAX_PDS_PAGES { + miette::bail!("PDS listRepos exceeded {MAX_PDS_PAGES} pages"); + } + self.enabled.wait_enabled("relay-first deep crawler").await; + if self.checker.state.pds_meta.load().is_banned(hostname) { + debug!(%hostname, "locally banned PDS, stopping deep discovery"); + return Ok(()); + } + let mut url = pds + .join("/xrpc/com.atproto.sync.listRepos") + .into_diagnostic()?; + url.query_pairs_mut().append_pair("limit", "1000"); + if let Some(value) = &cursor { + url.query_pairs_mut().append_pair("cursor", value); + } + + let Some(bytes) = self + .fetch_pds_page(pds, hostname, account_count, url, http) + .await? + else { + self.send_cursor_updates(vec![CursorUpdate { + key: cursor_key, + value: Some(serialize_cursor(&PassCursor::complete(pass))?), + }]) + .await?; + return Ok(()); + }; + let page = self.parse_deep_page(bytes).await?; + self.stats.record_crawled(page.count); + + let in_flight = self.in_flight.acquire(page.unknown_dids).await; + let filter = self.checker.state.filter.load_full(); + let confirmed = if filter.check_signals() && !in_flight.is_empty() { + let mut retry_batch = self.checker.state.db.inner.batch(); + let confirmed = self + .checker + .check_signals_batch(in_flight, &filter, &mut retry_batch, &HashMap::new()) + .await?; + self.checker + .state + .db + .run(move |_db| retry_batch.commit().into_diagnostic()) + .await?; + confirmed + } else { + in_flight + }; + + let next_cursor = page.cursor; + if next_cursor.is_some() && next_cursor == cursor { + miette::bail!("PDS listRepos returned the same cursor twice"); + } + let persisted = next_cursor.as_ref().map_or_else( + || PassCursor::complete(pass), + |next| PassCursor::active(pass, Some(next.clone())), + ); + self.tx + .send(CrawlerBatch { + guards: confirmed, + listings: Vec::new(), + cursor_updates: vec![CursorUpdate { + key: cursor_key.clone(), + value: Some(serialize_cursor(&persisted)?), + }], + }) + .await + .into_diagnostic() + .wrap_err("crawler worker exited")?; + + let Some(next) = next_cursor else { + return Ok(()); + }; + cursor = Some(next); + } + } + + async fn fetch_pds_page( + &self, + pds: &Url, + hostname: &str, + account_count: u64, + url: Url, + http: &reqwest::Client, + ) -> Result> { + let throttle = self.checker.throttler.get_handle(pds).await; + if throttle.is_throttled() { + miette::bail!("PDS is throttled until {}", throttle.throttled_until()); + } + let _permit = throttle.acquire().await; + let tier = self.checker.state.resolve_pds_tier(hostname); + throttle.wait_for_allow(account_count, &tier).await; + if throttle.is_throttled() { + miette::bail!("PDS became throttled while waiting for pacing"); + } + + let response = match http.get(url).timeout(throttle.timeout()).send().await { + Ok(response) => response, + Err(err) => { + throttle.record_failure_detail("deep_list_repos", err.to_string()); + return Err(err).into_diagnostic(); + } + }; + if response.status() == StatusCode::TOO_MANY_REQUESTS { + throttle.record_ratelimit(parse_retry_after(&response)); + miette::bail!("PDS rate limited deep discovery"); + } + if matches!( + response.status(), + StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED + ) || response.status().is_redirection() + { + debug!(status = %response.status(), "PDS does not support listRepos; skipping"); + throttle.record_success(); + return Ok(None); + } + let response = match response.error_for_status() { + Ok(response) => response, + Err(err) => { + throttle.record_failure_detail("deep_list_repos", err.to_string()); + return Err(err).into_diagnostic(); + } + }; + let bytes = crate::util::read_limited_bytes(response, MAX_LIST_RESPONSE_BYTES).await?; + throttle.record_success(); + Ok(Some(bytes)) + } + + async fn parse_deep_page(&self, bytes: bytes::Bytes) -> Result { + let repos = self.checker.state.db.repos.clone(); + let filter = self.checker.state.db.filter.clone(); + let crawler = self.checker.state.db.crawler.clone(); + tokio::time::timeout( + BLOCKING_TASK_TIMEOUT, + tokio::task::spawn_blocking(move || { + let output = serde_json::from_slice::(&bytes) + .into_diagnostic() + .wrap_err("failed to parse PDS listRepos response")? + .into_static(); + select_unknown_repos(&repos, &filter, &crawler, output) + }), + ) + .await + .map_err(|_| miette::miette!("PDS listRepos parse timed out"))? + .into_diagnostic()? + } + + async fn load_cursor(&self, key: &[u8], pass: u64) -> Result> { + let key = key.to_vec(); + self.checker + .state + .db + .run(move |db| { + db.cursors + .get(key) + .into_diagnostic()? + .map(|value| rmp_serde::from_slice::(&value).into_diagnostic()) + .transpose() + .map(|cursor| cursor.filter(|cursor| cursor.pass == pass)) + }) + .await + } + + async fn send_cursor_updates(&self, cursor_updates: Vec) -> Result<()> { + self.tx + .send(CrawlerBatch { + guards: Vec::new(), + listings: Vec::new(), + cursor_updates, + }) + .await + .into_diagnostic() + .wrap_err("crawler worker exited") + } +} + +fn log_pds_crawl_result(result: std::result::Result<(String, Result<()>), tokio::task::JoinError>) { + match result { + Ok((hostname, Err(err))) => { + warn!(%hostname, err = ?err, "deep PDS crawl failed; retrying on the next relay pass"); + } + Err(err) => error!(err = ?err, "deep PDS crawl task failed"), + Ok((_, Ok(()))) => {} + } +} + +struct DeepPage { + unknown_dids: Vec>, + cursor: Option, + count: usize, +} + +fn select_unknown_repos( + repos: &fjall::Keyspace, + filter: &fjall::Keyspace, + crawler: &fjall::Keyspace, + output: ListReposOutput<'static>, +) -> Result { + let count = output.repos.len(); + let cursor = output.cursor.map(|value| SmolStr::new(value.as_ref())); + let mut unknown_dids = Vec::new(); + for repo in output.repos { + let exclude_key = crate::db::filter::exclude_key(repo.did.as_str())?; + let did_key = keys::repo_key(&repo.did); + let retry_key = keys::crawler_retry_key(&repo.did); + let known = filter.contains_key(exclude_key).into_diagnostic()? + || repos.contains_key(did_key).into_diagnostic()? + || crawler.contains_key(retry_key).into_diagnostic()?; + if !known { + unknown_dids.push(repo.did.into_static()); + } + } + Ok(DeepPage { + unknown_dids, + cursor, + count, + }) +} + +fn serialize_cursor(cursor: &PassCursor) -> Result> { + rmp_serde::to_vec(cursor).into_diagnostic() +} + +fn read_u64(keyspace: &fjall::Keyspace, key: &[u8]) -> Result> { + keyspace + .get(key) + .into_diagnostic()? + .map(|value| { + value + .as_ref() + .try_into() + .into_diagnostic() + .map(u64::from_be_bytes) + }) + .transpose() +} + +async fn public_pds_client(hostname: &str) -> Result> { + let addresses = + match tokio::time::timeout(DNS_LOOKUP_TIMEOUT, tokio::net::lookup_host((hostname, 443))) + .await + { + Ok(Ok(addresses)) => addresses.collect::>(), + Ok(Err(_)) | Err(_) => return Ok(None), + }; + if addresses.is_empty() + || addresses + .iter() + .any(|address| pds_discovery::is_private_ip(address.ip())) + { + return Ok(None); + } + + reqwest::Client::builder() + .user_agent(concat!( + env!("CARGO_PKG_NAME"), + "/", + env!("CARGO_PKG_VERSION") + )) + .gzip(true) + .redirect(Policy::none()) + .resolve_to_addrs(hostname, &addresses) + .build() + .into_diagnostic() + .map(Some) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Config; + use crate::crawler::{CrawlerWorker, InFlight}; + use axum::{Json, Router, extract::Query, routing::get}; + use serde_json::json; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tempfile::tempdir; + + const HEAD: &str = "bafyreidf747c4x3lps3k4n357l3a3r57k3k465743k573k465743k5"; + + fn list_repos_output(value: serde_json::Value) -> Result> { + let bytes = serde_json::to_vec(&value).into_diagnostic()?; + serde_json::from_slice::(&bytes) + .into_diagnostic() + .map(IntoStatic::into_static) + } + + #[test] + fn pass_cursor_round_trips() -> Result<()> { + let cursor = PassCursor::active(7, Some("next".into())); + assert_eq!( + rmp_serde::from_slice::(&serialize_cursor(&cursor)?).into_diagnostic()?, + cursor + ); + assert!(PassCursor::complete(7).complete); + Ok(()) + } + + #[test] + fn deep_pages_select_only_unknown_repos_without_trusting_status() -> Result<()> { + let tmp = tempdir().into_diagnostic()?; + let config = Config { + database_path: tmp.path().to_path_buf(), + ..Default::default() + }; + let state = AppState::new(&config)?; + let known = Did::new_static("did:web:known.example")?; + let excluded = Did::new_static("did:web:excluded.example")?; + let retry = Did::new_static("did:web:retry.example")?; + state + .db + .repos + .insert(keys::repo_key(&known), b"relay") + .into_diagnostic()?; + state + .db + .filter + .insert(crate::db::filter::exclude_key(excluded.as_str())?, b"") + .into_diagnostic()?; + state + .db + .crawler + .insert(keys::crawler_retry_key(&retry), b"") + .into_diagnostic()?; + + let page = select_unknown_repos( + &state.db.repos, + &state.db.filter, + &state.db.crawler, + list_repos_output(json!({ + "cursor": "next", + "repos": [ + {"did": known, "head": HEAD, "rev": "3j6s746574657", "active": false, "status": "takendown"}, + {"did": excluded, "head": HEAD, "rev": "3j6s746574657"}, + {"did": retry, "head": HEAD, "rev": "3j6s746574657"}, + {"did": "did:web:inactive-unknown.example", "head": HEAD, "rev": "3j6s746574657", "active": false, "status": "deactivated"} + ] + }))?, + )?; + + assert_eq!(page.count, 4); + assert_eq!(page.cursor.as_deref(), Some("next")); + assert_eq!(page.unknown_dids.len(), 1); + assert_eq!( + page.unknown_dids[0].as_str(), + "did:web:inactive-unknown.example" + ); + assert_eq!( + state + .db + .repos + .get(keys::repo_key(&known)) + .into_diagnostic()? + .as_deref(), + Some(b"relay".as_slice()) + ); + Ok(()) + } + + #[tokio::test] + async fn pds_pages_resume_and_commit_only_after_terminal_page() -> Result<()> { + let requests = Arc::new(AtomicUsize::new(0)); + let app = Router::new().route( + "/xrpc/com.atproto.sync.listRepos", + get({ + let requests = requests.clone(); + move |Query(query): Query>| { + let requests = requests.clone(); + async move { + requests.fetch_add(1, Ordering::Relaxed); + let body = if query.get("cursor").is_some_and(|value| value == "next") { + json!({ + "repos": [ + {"did": "did:web:second-unknown.example", "head": HEAD, "rev": "3j6s746574657"} + ] + }) + } else { + json!({ + "cursor": "next", + "repos": [ + {"did": "did:web:known.example", "head": HEAD, "rev": "3j6s746574657", "active": false, "status": "takendown"}, + {"did": "did:web:first-unknown.example", "head": HEAD, "rev": "3j6s746574657", "active": false, "status": "deactivated"} + ] + }) + }; + Json(body) + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .into_diagnostic()?; + let address = listener.local_addr().into_diagnostic()?; + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + + let tmp = tempdir().into_diagnostic()?; + let config = Config { + database_path: tmp.path().to_path_buf(), + full_network: true, + enable_crawler: Some(true), + ..Default::default() + }; + let state = Arc::new(AppState::new(&config)?); + let known = Did::new_static("did:web:known.example")?; + state + .db + .repos + .insert(keys::repo_key(&known), b"relay-authority") + .into_diagnostic()?; + let stats = CrawlerStats::new(state.clone(), Vec::new(), state.throttler.clone()); + let (worker, tx) = CrawlerWorker::new(state.clone(), 100, 50, stats.clone()); + let worker = tokio::spawn(worker.run()); + let pds = Url::parse(&format!("http://{address}/")).into_diagnostic()?; + let mut producer = DeepDiscoveryProducer { + relay_url: Url::parse("https://relay.example").into_diagnostic()?, + checker: SignalChecker { + http: reqwest::Client::new(), + state: state.clone(), + throttler: state.throttler.clone(), + }, + in_flight: InFlight::new(), + tx, + enabled: state.crawler_enabled.subscribe(), + stats, + }; + + let http = reqwest::Client::new(); + producer.crawl_pds(7, &pds, 1, &http).await?; + let cursor_key = + keys::relay_first_pds_cursor_key(producer.relay_url.as_str(), pds.host_str().unwrap()); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let complete = state + .db + .cursors + .get(&cursor_key) + .ok() + .flatten() + .and_then(|value| rmp_serde::from_slice::(&value).ok()) + .is_some_and(|cursor| cursor == PassCursor::complete(7)); + if complete { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .into_diagnostic()?; + + assert_eq!(requests.load(Ordering::Relaxed), 2); + assert!( + state + .db + .repos + .contains_key(keys::repo_key(&Did::new_static( + "did:web:first-unknown.example" + )?)) + .into_diagnostic()? + ); + assert!( + state + .db + .repos + .contains_key(keys::repo_key(&Did::new_static( + "did:web:second-unknown.example" + )?)) + .into_diagnostic()? + ); + assert_eq!( + state + .db + .repos + .get(keys::repo_key(&known)) + .into_diagnostic()? + .as_deref(), + Some(b"relay-authority".as_slice()) + ); + + producer.crawl_pds(7, &pds, 1, &http).await?; + assert_eq!(requests.load(Ordering::Relaxed), 2); + + state + .db + .cursors + .insert( + &cursor_key, + serialize_cursor(&PassCursor::active(8, Some("next".into())))?, + ) + .into_diagnostic()?; + producer.crawl_pds(8, &pds, 1, &http).await?; + assert_eq!(requests.load(Ordering::Relaxed), 3); + + state.pds_meta.rcu(|meta| { + let mut next = (**meta).clone(); + next.update_host_entry(pds.host_str().unwrap(), |entry| { + entry.status = crate::pds_meta::HostStatus::Banned; + }); + next + }); + producer.crawl_pds(9, &pds, 1, &http).await?; + assert_eq!(requests.load(Ordering::Relaxed), 3); + + worker.abort(); + server.abort(); + Ok(()) + } + + #[tokio::test] + async fn private_pds_addresses_are_rejected() { + assert!(public_pds_client("127.0.0.1").await.unwrap().is_none()); + assert!(public_pds_client("::1").await.unwrap().is_none()); + } + + #[tokio::test] + async fn deep_discovery_waits_for_a_new_relay_pass_marker() -> Result<()> { + let tmp = tempdir().into_diagnostic()?; + let config = Config { + database_path: tmp.path().to_path_buf(), + full_network: true, + enable_crawler: Some(true), + ..Default::default() + }; + let state = Arc::new(AppState::new(&config)?); + let stats = CrawlerStats::new(state.clone(), Vec::new(), state.throttler.clone()); + let (tx, _rx) = mpsc::channel(1); + let mut producer = DeepDiscoveryProducer { + relay_url: Url::parse("https://relay.example").into_diagnostic()?, + checker: SignalChecker { + http: reqwest::Client::new(), + state: state.clone(), + throttler: state.throttler.clone(), + }, + in_flight: InFlight::new(), + tx, + enabled: state.crawler_enabled.subscribe(), + stats, + }; + + assert!( + tokio::time::timeout( + Duration::from_millis(20), + producer.wait_for_unhandled_pass() + ) + .await + .is_err() + ); + state + .db + .cursors + .insert( + keys::relay_first_pass_key(producer.relay_url.as_str()), + 7u64.to_be_bytes(), + ) + .into_diagnostic()?; + state + .db + .cursors + .insert( + keys::relay_first_handled_key(producer.relay_url.as_str()), + 7u64.to_be_bytes(), + ) + .into_diagnostic()?; + assert!( + tokio::time::timeout( + Duration::from_millis(20), + producer.wait_for_unhandled_pass() + ) + .await + .is_err() + ); + state + .db + .cursors + .insert( + keys::relay_first_pass_key(producer.relay_url.as_str()), + 8u64.to_be_bytes(), + ) + .into_diagnostic()?; + assert_eq!(producer.wait_for_unhandled_pass().await?, 8); + Ok(()) + } +} diff --git a/src/crawler/worker.rs b/src/crawler/worker.rs index 034832e..2311859 100644 --- a/src/crawler/worker.rs +++ b/src/crawler/worker.rs @@ -60,17 +60,18 @@ pub(crate) struct RepoListing { pub(super) rev: DbTid, pub(super) active: bool, pub(super) status: Option>, + pub(super) create_if_missing: bool, } /// a batch of confirmed repos from any crawler source ready to enqueue. /// /// `guards` hold the DIDs (via `Deref`) and keep their in-flight slots occupied -/// until the batch is committed to the database. `cursor_update`, if present, -/// is committed atomically with the repos/pending inserts. +/// until the batch is committed to the database. cursor updates are committed +/// atomically with the repos/pending inserts. pub(crate) struct CrawlerBatch { pub(super) guards: Vec, pub(super) listings: Vec, - pub(super) cursor_update: Option, + pub(super) cursor_updates: Vec, } pub(crate) struct CrawlerWorker { @@ -156,13 +157,13 @@ impl CrawlerWorker { let CrawlerBatch { guards, listings, - cursor_update, + cursor_updates, } = batch; // nothing to insert but still need to commit the cursor if present. if guards.is_empty() && listings.is_empty() { - if let Some(cursor) = cursor_update { - self.commit_cursor(cursor).await?; + if !cursor_updates.is_empty() { + self.commit_cursors(cursor_updates).await?; } return Ok(()); } @@ -212,7 +213,7 @@ impl CrawlerWorker { txn.transition_lifecycle(&guard, crate::types::GaugeState::Pending)?; surviving.push(guard); } - if let Some(cursor) = cursor_update { + for cursor in cursor_updates { stage_cursor(&mut txn.batch, db, cursor); } // todo: repo state overwrites here are acceptable? @@ -261,13 +262,15 @@ impl CrawlerWorker { Ok(()) } - async fn commit_cursor(&self, cursor: CursorUpdate) -> Result<()> { + async fn commit_cursors(&self, cursors: Vec) -> Result<()> { let state = self.state.clone(); tokio::time::timeout( BLOCKING_TASK_TIMEOUT, state.db.run(move |db| { let mut txn = crate::db::Txn::new(db); - stage_cursor(&mut txn.batch, db, cursor); + for cursor in cursors { + stage_cursor(&mut txn.batch, db, cursor); + } txn.commit() }), ) @@ -304,7 +307,28 @@ fn reconcile_listing( let db = txn.db; let did_key = keys::repo_key(&listing.did); let Some(state_bytes) = db.repos.get(&did_key).into_diagnostic()? else { - return Ok(ReconcileOutcome::Unchanged); + if listing.active || !listing.create_if_missing { + return Ok(ReconcileOutcome::Unchanged); + } + let status = listed_repo_status(listing.status.as_ref()); + let mut state = RepoState::backfilling(); + state.active = false; + state.status = status.clone(); + if status != RepoStatus::Deleted { + txn.batch.insert( + &db.indexer.resync, + &did_key, + rmp_serde::to_vec(&ResyncState::Gone { + status: status.clone(), + }) + .into_diagnostic()?, + ); + txn.transition_lifecycle(&listing.did, GaugeState::Resync(None))?; + } + txn.batch + .insert(&db.repos, &did_key, ser_repo_state(&state)?); + txn.counts.add_repos(1); + return Ok(ReconcileOutcome::StateOnly); }; let mut state = crate::db::deser_repo_state(&state_bytes)?.into_static(); @@ -581,6 +605,7 @@ mod tests { rev: rev(1), active: false, status: Some(ListedRepoStatus::Deactivated), + create_if_missing: false, }; assert_eq!(apply(&db, &listing)?, ReconcileOutcome::AccountChanged); @@ -598,6 +623,32 @@ mod tests { Ok(()) } + #[test] + fn relay_first_persists_unknown_inactive_listing_without_backfill() -> Result<()> { + let (_tmp, db) = open_db()?; + let listing = RepoListing { + did: did(), + rev: rev(1), + active: false, + status: Some(ListedRepoStatus::Takendown), + create_if_missing: true, + }; + + assert_eq!(apply(&db, &listing)?, ReconcileOutcome::StateOnly); + let state = read_state(&db)?; + assert!(!state.active); + assert_eq!(state.status, RepoStatus::Takendown); + assert_eq!(db.indexer.pending.iter().count(), 0); + assert!( + db.indexer + .resync + .contains_key(keys::repo_key(&listing.did)) + .into_diagnostic()? + ); + assert_eq!(apply(&db, &listing)?, ReconcileOutcome::Unchanged); + Ok(()) + } + #[test] fn current_active_listing_does_not_reenqueue() -> Result<()> { let (_tmp, db) = open_db()?; @@ -607,6 +658,7 @@ mod tests { rev: rev(2), active: true, status: None, + create_if_missing: false, }; assert_eq!(apply(&db, &listing)?, ReconcileOutcome::Unchanged); @@ -626,6 +678,7 @@ mod tests { rev: rev(1), active: false, status: Some(ListedRepoStatus::Deactivated), + create_if_missing: false, }; assert_eq!(apply(&db, &listing)?, ReconcileOutcome::StateOnly); @@ -642,6 +695,7 @@ mod tests { rev: rev(2), active: true, status: None, + create_if_missing: false, }; assert_eq!(apply(&db, &listing)?, ReconcileOutcome::StateOnly); @@ -671,6 +725,35 @@ mod tests { Ok(()) } + #[test] + fn cursor_batch_can_advance_one_marker_and_clear_another() -> Result<()> { + let (_tmp, db) = open_db()?; + let old_key = b"relay_first_cursor|relay|hosts".to_vec(); + let marker_key = b"relay_first_cursor|relay|handled".to_vec(); + db.cursors.insert(&old_key, b"old").into_diagnostic()?; + let mut txn = crate::db::Txn::new(&db); + for cursor in [ + CursorUpdate { + key: marker_key.clone(), + value: Some(7u64.to_be_bytes().to_vec()), + }, + CursorUpdate { + key: old_key.clone(), + value: None, + }, + ] { + stage_cursor(&mut txn.batch, &db, cursor); + } + txn.commit()?; + + assert_eq!( + db.cursors.get(marker_key).into_diagnostic()?.as_deref(), + Some(7u64.to_be_bytes().as_slice()) + ); + assert!(db.cursors.get(old_key).into_diagnostic()?.is_none()); + Ok(()) + } + #[tokio::test] #[cfg(feature = "indexer_stream")] async fn changed_listing_emits_one_account_event() -> Result<()> { @@ -693,13 +776,14 @@ mod tests { rev: rev(1), active: false, status: Some(ListedRepoStatus::Deactivated), + create_if_missing: false, }; worker .enqueue(CrawlerBatch { guards: Vec::new(), listings: vec![listing.clone()], - cursor_update: None, + cursor_updates: Vec::new(), }) .await?; let crate::types::BroadcastEvent::Ephemeral(event) = events.recv().await.unwrap() else { @@ -713,7 +797,7 @@ mod tests { .enqueue(CrawlerBatch { guards: Vec::new(), listings: vec![listing], - cursor_update: None, + cursor_updates: Vec::new(), }) .await?; assert!(events.try_recv().is_err()); @@ -746,8 +830,9 @@ mod tests { rev: rev(2), active: true, status: None, + create_if_missing: false, }], - cursor_update: None, + cursor_updates: Vec::new(), }) .await?; diff --git a/src/db/keys/indexer.rs b/src/db/keys/indexer.rs index 7caa207..0add66f 100644 --- a/src/db/keys/indexer.rs +++ b/src/db/keys/indexer.rs @@ -132,6 +132,38 @@ pub fn crawler_cursor_key(relay: &str) -> Vec { key } +pub const RELAY_FIRST_CURSOR_PREFIX: &[u8] = b"relay_first_cursor|"; + +pub fn relay_first_cursor_prefix(relay: &str) -> Vec { + let mut prefix = Vec::with_capacity(RELAY_FIRST_CURSOR_PREFIX.len() + relay.len() + 1); + prefix.extend_from_slice(RELAY_FIRST_CURSOR_PREFIX); + prefix.extend_from_slice(relay.as_bytes()); + prefix.push(SEP); + prefix +} + +fn relay_first_cursor_key(relay: &str, suffix: &str) -> Vec { + let mut key = relay_first_cursor_prefix(relay); + key.extend_from_slice(suffix.as_bytes()); + key +} + +pub fn relay_first_pass_key(relay: &str) -> Vec { + relay_first_cursor_key(relay, "pass") +} + +pub fn relay_first_handled_key(relay: &str) -> Vec { + relay_first_cursor_key(relay, "handled") +} + +pub fn relay_first_hosts_cursor_key(relay: &str) -> Vec { + relay_first_cursor_key(relay, "hosts") +} + +pub fn relay_first_pds_cursor_key(relay: &str, host: &str) -> Vec { + relay_first_cursor_key(relay, &format!("pds|{host}")) +} + pub const BY_COLLECTION_CURSOR_PREFIX: &[u8] = b"by_collection_cursor|"; /// prefix for all by-collection cursors belonging to a given index URL. diff --git a/src/lib.rs b/src/lib.rs index 0be22bd..bb262e6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,6 +49,7 @@ pub(crate) mod jetstream; #[cfg(feature = "indexer")] pub(crate) mod ops; pub(crate) mod patch; +pub(crate) mod pds_discovery; pub mod resolver; #[cfg(feature = "indexer")] pub(crate) mod sparse_mst; diff --git a/src/pds_discovery.rs b/src/pds_discovery.rs new file mode 100644 index 0000000..439cea4 --- /dev/null +++ b/src/pds_discovery.rs @@ -0,0 +1,99 @@ +use std::net::IpAddr; + +use url::Url; + +pub(crate) fn list_hosts_url(base: &Url, cursor: Option<&str>) -> Url { + let mut url = base.clone(); + url.set_path("/xrpc/com.atproto.sync.listHosts"); + { + let mut pairs = url.query_pairs_mut(); + pairs.append_pair("limit", "1000"); + if let Some(cursor) = cursor { + pairs.append_pair("cursor", cursor); + } + } + url +} + +pub(crate) fn is_private_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => { + let [a, b, c, _] = ip.octets(); + ip.is_loopback() + || ip.is_private() + || ip.is_link_local() + || ip.is_multicast() + || ip.is_unspecified() + || ip.is_broadcast() + || a == 0 + || (a == 100 && b & 0xc0 == 0x40) + || (a == 192 && b == 0 && c == 0) + || (a == 192 && b == 0 && c == 2) + || (a == 192 && b == 88 && c == 99) + || (a == 198 && b & 0xfe == 18) + || (a == 198 && b == 51 && c == 100) + || (a == 203 && b == 0 && c == 113) + || a >= 240 + } + IpAddr::V6(ip) => { + let octets = ip.octets(); + ip.is_loopback() + || ip.is_multicast() + || ip.is_unspecified() + || ip + .to_ipv4_mapped() + .is_some_and(|ipv4| is_private_ip(IpAddr::V4(ipv4))) + || (octets[0] & 0xfe) == 0xfc + || (octets[0] == 0xfe && octets[1] & 0xc0 == 0x80) + || (octets[0] == 0xfe && octets[1] & 0xc0 == 0xc0) + || (octets[..4] == [0x20, 0x01, 0x0d, 0xb8]) + } + } +} + +pub(crate) fn is_safe_seed_host(host: &str) -> bool { + if host.is_empty() { + return false; + } + if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") { + return false; + } + if let Ok(ip) = host.parse::() { + return !is_private_ip(ip); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_non_public_address_ranges() { + for address in [ + "0.0.0.1", + "10.0.0.1", + "100.64.0.1", + "127.0.0.1", + "169.254.1.1", + "192.0.2.1", + "198.18.0.1", + "198.51.100.1", + "203.0.113.1", + "240.0.0.1", + "::1", + "::ffff:127.0.0.1", + "2001:db8::1", + "fc00::1", + "fe80::1", + "fec0::1", + ] { + assert!( + is_private_ip(address.parse().unwrap()), + "accepted {address}" + ); + } + assert!(!is_private_ip("1.1.1.1".parse().unwrap())); + assert!(!is_private_ip("2606:4700:4700::1111".parse().unwrap())); + } +} diff --git a/tests/api_crawler_sources.nu b/tests/api_crawler_sources.nu index 28a4af9..0dab421 100644 --- a/tests/api_crawler_sources.nu +++ b/tests/api_crawler_sources.nu @@ -25,6 +25,17 @@ def test-crawler-source-management [url: string, pid: int] { fail $"expected mode=list_repos, got ($s.mode)" $pid } + print " POST /crawler/sources accepts relay_first as an explicit mode..." + http post -f -e -t application/json $"($url)/crawler/sources" { + url: "https://bsky.network", + mode: "relay_first" + } | assert-status 201 "POST /crawler/sources relay_first" $pid + + let relay_first = (http get $"($url)/crawler/sources") + if ($relay_first | length) != 1 or ($relay_first | first).mode != "relay_first" { + fail "expected relay_first source to replace list_repos" $pid + } + print " POST /crawler/sources replaces an existing URL..." http post -f -e -t application/json $"($url)/crawler/sources" { url: "https://bsky.network", -- knotmirror 0.0.1