web search done right
Download warc files in async batches
Mikkel Denker1bdafe9bd48f
diff --git a/Cargo.lock b/Cargo.lockindex 6a1925ef..4a4fa2f3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -987,7 +987,7 @@ dependencies = ["indexmap","slab","tokio",- "tokio-util",+ "tokio-util 0.7.3","tracing",]@@ -2184,6 +2184,7 @@ dependencies = ["serde_urlencoded","tokio","tokio-native-tls",+ "tokio-util 0.6.10","url","wasm-bindgen","wasm-bindgen-futures",@@ -2757,6 +2758,20 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-util"+version = "0.6.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "log",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tokio-util"version = "0.7.3"@@ -2815,7 +2830,7 @@ dependencies = ["percent-encoding","pin-project-lite","tokio",- "tokio-util",+ "tokio-util 0.7.3","tower","tower-layer","tower-service",diff --git a/Cargo.toml b/Cargo.tomlindex dc16d9b6..5c421309 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -19,7 +19,7 @@ indicatif = { version = "0.16.2", features = ["rayon"] }itertools = "0.10.3"lru = "0.7.6"rayon = "1.5.3"-reqwest = { version = "0.11.10", features = ["blocking"] }+reqwest = { version = "0.11.10", features = ["blocking", "stream"] }serde = "1.0.137"serde_json = "1.0.81"tantivy = "0.18.0"diff --git a/configs/webgraph/local.toml b/configs/webgraph/local.tomlindex d3e2d932..51e0fb33 100644--- a/configs/webgraph/local.toml+++ b/configs/webgraph/local.toml@@ -1,5 +1,6 @@-limit_warc_files = 3+limit_warc_files = 4graph_base_path = "data/webgraph"+batch_size = 2[warc_source]type = "HTTP"diff --git a/src/entrypoint/indexer.rs b/src/entrypoint/indexer.rsindex 7c0691e1..4e0d7436 100644--- a/src/entrypoint/indexer.rs+++ b/src/entrypoint/indexer.rs@@ -16,10 +16,12 @@use std::net::SocketAddr;use std::path::Path;+use itertools::Itertools;use rayon::prelude::*;use serde::{Deserialize, Serialize};use tracing::{debug, info, trace};+use crate::entrypoint::download_all_warc_files;use crate::index::{FrozenIndex, Index};use crate::mapreduce::{Map, MapReduce, Reduce, Worker};use crate::ranking::centrality_store::CentralityStore;@@ -40,7 +42,7 @@ enum JobConfig {#[derive(Debug, Serialize, Deserialize)]struct Job {config: JobConfig,- warc_path: String,+ warc_paths: Vec<String>,base_path: String,}@@ -60,7 +62,7 @@ impl Worker for IndexingWorker {}impl Map<IndexingWorker, FrozenIndex> for Job {fn map(self, worker: &IndexingWorker) -> FrozenIndex {- let name = self.warc_path.split('/').last().unwrap();+ let name = self.warc_paths.first().unwrap().split('/').last().unwrap();info!("processing {}", name);@@ -71,45 +73,51 @@ impl Map<IndexingWorker, FrozenIndex> for Job {JobConfig::Local(config) => WarcSource::Local(config),};- debug!("downlooading warc file");- let file = WarcFile::download(source, &self.warc_path).unwrap();- debug!("finished downloading");-- for record in- file.records()- .flatten()- .filter(|record| match &record.response.payload_type {- Some(payload_type) => !matches!(payload_type.as_str(), "application/pdf"),- None => true,- })- {- let html = Html::parse(&record.response.body, &record.request.url);- let backlinks: Vec<Link> = Vec::new(); // TODO: lookup backlinks in full webgraph- let centrality = worker- .centrality_store- .get(html.url().host_without_specific_subdomains())- .unwrap_or_default();- let fetch_time_ms = record.metadata.fetch_time_ms as u64;-- trace!("inserting webpage: {:?}", html.url());-- trace!("title = {:?}", html.title());- trace!("text = {:?}", html.clean_text());-- let webpage = Webpage {- html,- backlinks,- centrality,- fetch_time_ms,- primary_image_uuid: None,- };- if let Err(err) = index.insert(webpage) {- debug!("{:?}", err);+ let warc_files = download_all_warc_files(&self.warc_paths, &source, &self.base_path);++ for file in warc_files {+ if let Ok(file) = WarcFile::open(&file) {+ for record in+ file.records()+ .flatten()+ .filter(|record| match &record.response.payload_type {+ Some(payload_type) => {+ !matches!(payload_type.as_str(), "application/pdf")+ }+ None => true,+ })+ {+ let html = Html::parse(&record.response.body, &record.request.url);+ let backlinks: Vec<Link> = Vec::new(); // TODO: lookup backlinks in full webgraph+ let centrality = worker+ .centrality_store+ .get(html.url().host_without_specific_subdomains())+ .unwrap_or_default();+ let fetch_time_ms = record.metadata.fetch_time_ms as u64;++ trace!("inserting webpage: {:?}", html.url());++ trace!("title = {:?}", html.title());+ trace!("text = {:?}", html.clean_text());++ let webpage = Webpage {+ html,+ backlinks,+ centrality,+ fetch_time_ms,+ primary_image_uuid: None,+ };+ if let Err(err) = index.insert(webpage) {+ debug!("{:?}", err);+ }+ }+ index.commit().unwrap();+ info!("downloading images");+ index.download_pending_images();}++ std::fs::remove_file(file).ok();}- index.commit().unwrap();- info!("downloading images");- index.download_pending_images();info!("{} done", name);@@ -161,17 +169,22 @@ impl Indexer {WarcSource::Local(config) => JobConfig::Local(config),};- let mut warc_paths: Box<dyn Iterator<Item = Job> + Send> =- Box::new(warc_paths.into_iter().map(|warc_path| {- Job {+ let mut warc_paths: Box<dyn Iterator<Item = Job> + Send> = Box::new(+ warc_paths+ .into_iter()+ .chunks(config.batch_size.unwrap_or(1))+ .into_iter()+ .map(|warc_paths| Job {config: job_config.clone(),- warc_path,+ warc_paths: warc_paths.collect_vec(),base_path: config.index_base_path.clone().unwrap_or_else(|| "data/index".to_string()),- }- }));+ })+ .collect_vec()+ .into_iter(),+ );if let Some(limit) = config.limit_warc_files {warc_paths = Box::new(warc_paths.take(limit));@@ -206,12 +219,15 @@ impl Indexer {warc_paths.into_iter().take(config.limit_warc_files.unwrap_or(usize::MAX))- .map(|path| Job {+ .chunks(config.batch_size.unwrap_or(1))+ .into_iter()+ .map(|warc_paths| Job {config: job_config.clone(),- warc_path: path,+ warc_paths: warc_paths.collect_vec(),base_path: "data/index".to_string(),})- .par_bridge()+ .collect_vec()+ .into_par_iter().panic_fuse().map(|job| job.map(&worker)).map(Index::from)diff --git a/src/entrypoint/mod.rs b/src/entrypoint/mod.rsindex 847c99cf..c4da2518 100644--- a/src/entrypoint/mod.rs+++ b/src/entrypoint/mod.rs@@ -19,7 +19,81 @@ pub mod frontend;mod indexer;mod webgraph;+use std::{fs::File, path::Path};+pub use centrality::Centrality;pub use entity::EntityIndexer;+use futures::StreamExt;pub use indexer::Indexer;+use tracing::debug;pub use webgraph::Webgraph;++use crate::{warc::WarcFile, WarcSource};++async fn async_download_all_warc_files(+ warc_paths: &[String],+ source: &WarcSource,+ download_path: &Path,+) {+ futures::stream::iter(+ warc_paths+ .iter()+ .map(|path| (path.split('/').last().unwrap(), path))+ .map(|(name, path)| {+ let file = File::options()+ .create(true)+ .truncate(true)+ .write(true)+ .open(download_path.join(name))+ .unwrap();+ (file, path)+ })+ .map(|(mut file, warc_path)| async move {+ debug!("downloading warc file {}", &warc_path);+ let res = WarcFile::download_into_buf(source, warc_path, &mut file)+ .await+ .ok();+ debug!("finished downloading");++ res+ }),+ )+ .buffer_unordered(warc_paths.len())+ .collect::<Vec<Option<()>>>()+ .await;+}++fn download_all_warc_files(+ warc_paths: &[String],+ source: &WarcSource,+ base_path: &str,+) -> Vec<String> {+ let download_path = Path::new(base_path).join("warc_files");++ if !download_path.exists() {+ std::fs::create_dir_all(&download_path).unwrap();+ }++ let file_paths = warc_paths+ .iter()+ .map(|warc_path| warc_path.split('/').last().unwrap())+ .map(|name| {+ download_path+ .join(name)+ .as_os_str()+ .to_str()+ .unwrap()+ .to_string()+ })+ .collect();++ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(async {+ async_download_all_warc_files(warc_paths, source, &download_path).await+ });++ file_paths+}diff --git a/src/entrypoint/webgraph.rs b/src/entrypoint/webgraph.rsindex 5564bec9..5aefe252 100644--- a/src/entrypoint/webgraph.rs+++ b/src/entrypoint/webgraph.rs@@ -15,17 +15,18 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.use crate::{directory::DirEntry,+ entrypoint::download_all_warc_files,mapreduce::{Map, MapReduce, Reduce, StatelessWorker, Worker},warc::WarcFile,webgraph::{self, FrozenWebgraph, Node, WebgraphBuilder},webpage::Html,HttpConfig, LocalConfig, Result, WarcSource, WebgraphLocalConfig, WebgraphMasterConfig,};-use rayon::prelude::ParallelBridge;+use itertools::Itertools;use rayon::prelude::*;use serde::{Deserialize, Serialize};use std::{net::SocketAddr, path::Path};-use tracing::{debug, info, trace};+use tracing::{info, trace};#[derive(Debug, Serialize, Deserialize)]struct GraphPath(String);@@ -39,7 +40,7 @@ enum JobConfig {#[derive(Debug, Serialize, Deserialize)]struct Job {config: JobConfig,- warc_path: String,+ warc_paths: Vec<String>,graph_base_path: String,}@@ -51,7 +52,7 @@ fn open_graph<P: AsRef<Path>>(path: P) -> webgraph::Webgraph {}fn process_job(job: &Job) -> webgraph::Webgraph {- let name = job.warc_path.split('/').last().unwrap();+ let name = job.warc_paths.first().unwrap().split('/').last().unwrap();info!("processing {}", name);@@ -62,25 +63,29 @@ fn process_job(job: &Job) -> webgraph::Webgraph {JobConfig::Local(config) => WarcSource::Local(config),};- debug!("downlooading warc file");- let file = WarcFile::download(source, &job.warc_path).unwrap();- debug!("finished downloading");-- for record in file.records().flatten() {- let webpage = Html::parse(&record.response.body, &record.request.url);- for link in webpage- .links()- .into_iter()- .filter(|link| matches!(link.destination.protocol(), "http" | "https"))- .filter(|link| link.source.domain() != link.destination.domain())- {- trace!("inserting link {:?}", link);- graph.insert(- Node::from(link.source),- Node::from(link.destination),- link.text,- );+ let warc_files = download_all_warc_files(&job.warc_paths, &source, &job.graph_base_path);++ for warc_path in &warc_files {+ if let Ok(file) = WarcFile::open(warc_path) {+ for record in file.records().flatten() {+ let webpage = Html::parse(&record.response.body, &record.request.url);+ for link in webpage+ .links()+ .into_iter()+ .filter(|link| matches!(link.destination.protocol(), "http" | "https"))+ .filter(|link| link.source.domain() != link.destination.domain())+ {+ trace!("inserting link {:?}", link);+ graph.insert(+ Node::from(link.source),+ Node::from(link.destination),+ link.text,+ );+ }+ }}++ std::fs::remove_file(warc_path).ok();}graph.flush();@@ -170,17 +175,22 @@ impl Webgraph {WarcSource::Local(config) => JobConfig::Local(config),};- let mut warc_paths: Box<dyn Iterator<Item = Job> + Send> =- Box::new(warc_paths.into_iter().map(|warc_path| {- Job {+ let mut warc_paths: Box<dyn Iterator<Item = Job> + Send> = Box::new(+ warc_paths+ .into_iter()+ .chunks(config.batch_size.unwrap_or(1))+ .into_iter()+ .map(|warc_paths| Job {config: job_config.clone(),- warc_path,+ warc_paths: warc_paths.into_iter().collect(),graph_base_path: config.graph_base_path.clone().unwrap_or_else(|| "data/webgraph".to_string()),- }- }));+ })+ .collect::<Vec<_>>()+ .into_iter(),+ );if let Some(limit) = config.limit_warc_files {warc_paths = Box::new(warc_paths.take(limit));@@ -219,15 +229,18 @@ impl Webgraph {warc_paths.into_iter().take(config.limit_warc_files.unwrap_or(usize::MAX))- .map(|path| Job {+ .chunks(config.batch_size.unwrap_or(1))+ .into_iter()+ .map(|warc_paths| Job {config: job_config.clone(),- warc_path: path,+ warc_paths: warc_paths.collect_vec(),graph_base_path: config.graph_base_path.clone().unwrap_or_else(|| "data/webgraph".to_string()),})- .par_bridge()+ .collect_vec()+ .into_par_iter().map(|job| -> GraphPath { job.map(&worker) }).map(Some).reduce(diff --git a/src/image_downloader.rs b/src/image_downloader.rsindex 65468dea..07135b5a 100644--- a/src/image_downloader.rs+++ b/src/image_downloader.rs@@ -108,7 +108,7 @@ where}}pub fn download(&mut self, store: &mut impl ImageStore<K>) {- tokio::runtime::Builder::new_multi_thread()+ tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()diff --git a/src/lib.rs b/src/lib.rsindex ece3b966..96b0d7b7 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -58,6 +58,7 @@ pub struct IndexingMasterConfig {limit_warc_files: Option<usize>,warc_source: WarcSource,workers: Vec<String>,+ batch_size: Option<usize>,index_base_path: Option<String>,}@@ -65,6 +66,7 @@ pub struct IndexingMasterConfig {pub struct IndexingLocalConfig {limit_warc_files: Option<usize>,warc_source: WarcSource,+ batch_size: Option<usize>,centrality_store_path: String,}@@ -74,6 +76,7 @@ pub struct WebgraphMasterConfig {warc_source: WarcSource,workers: Vec<String>,graph_base_path: Option<String>,+ batch_size: Option<usize>,}#[derive(Debug, Deserialize, Clone)]@@ -81,6 +84,7 @@ pub struct WebgraphLocalConfig {limit_warc_files: Option<usize>,warc_source: WarcSource,graph_base_path: Option<String>,+ batch_size: Option<usize>,}#[derive(Debug, Serialize, Deserialize, Clone)]diff --git a/src/warc.rs b/src/warc.rsindex 396142df..da742d5d 100644--- a/src/warc.rs+++ b/src/warc.rs@@ -17,11 +17,12 @@ use crate::exponential_backoff::ExponentialBackoff;use crate::{Error, Result, WarcSource};use std::collections::BTreeMap;use std::fs::File;-use std::io::{BufRead, BufReader, Read};+use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write};use std::path::Path;-use std::thread::sleep;use flate2::read::MultiGzDecoder;+use futures::StreamExt;+use tokio::time::sleep;use tracing::debug;pub(crate) struct WarcFile {@@ -56,10 +57,20 @@ fn decode(raw: &[u8]) -> String {}impl WarcFile {- pub(crate) fn new(bytes: Vec<u8>) -> Self {+ pub fn new(bytes: Vec<u8>) -> Self {Self { bytes }}+ pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {+ let file = File::open(path)?;+ let mut reader = BufReader::new(file);++ let mut bytes = Vec::new();+ reader.read_to_end(&mut bytes)?;++ Ok(Self::new(bytes))+ }+pub fn records(&self) -> RecordIterator<&[u8]> {RecordIterator {reader: BufReader::new(MultiGzDecoder::new(&self.bytes[..])),@@ -67,53 +78,78 @@ impl WarcFile {}}- pub(crate) fn download(source: WarcSource, path: &str) -> Result<Self> {+ #[allow(unused)]+ pub(crate) async fn download(source: &WarcSource, warc_path: &str) -> Result<Self> {+ let mut cursor = Cursor::new(Vec::new());+ Self::download_into_buf(source, warc_path, &mut cursor).await?;++ let mut buf = Vec::new();+ cursor.read_to_end(&mut buf)?;++ Ok(Self::new(buf))+ }++ pub(crate) async fn download_into_buf<W: Write + Seek>(+ source: &WarcSource,+ warc_path: &str,+ buf: &mut W,+ ) -> Result<()> {for dur in ExponentialBackoff::from_millis(10).take(5) {let res = match source.clone() {- WarcSource::HTTP(config) => WarcFile::download_from_http(path, config.base_url),- WarcSource::Local(config) => WarcFile::load_from_folder(path, &config.folder),+ WarcSource::HTTP(config) => {+ WarcFile::download_from_http(warc_path, config.base_url, buf).await+ }+ WarcSource::Local(config) => {+ WarcFile::load_from_folder(warc_path, &config.folder, buf)+ }};if res.is_ok() {- return res;+ return Ok(());}debug!("warc download failed, retrying in {} ms", dur.as_millis());- sleep(dur);+ sleep(dur).await;}Err(Error::DownloadFailed)}- fn load_from_folder(name: &str, folder: &str) -> Result<Self> {- let mut bytes = Vec::new();+ fn load_from_folder<W: Write + Seek>(name: &str, folder: &str, buf: &mut W) -> Result<()> {let f = File::open(Path::new(folder).join(name))?;-let mut reader = BufReader::new(f);- reader.read_to_end(&mut bytes)?;- Ok(WarcFile::new(bytes))+ buf.seek(SeekFrom::Start(0))?;+ std::io::copy(&mut reader, buf)?;+ Ok(())}- fn download_from_http(path: &str, base_url: String) -> Result<Self> {+ async fn download_from_http<W: Write + Seek>(+ warc_path: &str,+ base_url: String,+ buf: &mut W,+ ) -> Result<()> {let mut url = base_url;if !url.ends_with('/') {url += "/";}- url += path;+ url += warc_path;- let client = reqwest::blocking::ClientBuilder::new()+ let client = reqwest::ClientBuilder::new().tcp_keepalive(None)- .connect_timeout(None)- .timeout(None).pool_idle_timeout(None).build()?;- let res = client.get(url).send()?;+ let res = client.get(url).send().await?;- let bytes = Vec::from(&res.bytes()?[..]);+ let mut stream = res.bytes_stream();++ buf.seek(SeekFrom::Start(0))?;+ while let Some(chunk) = stream.next().await {+ std::io::copy(&mut &chunk?[..], buf)?;+ }- Ok(WarcFile::new(bytes))+ Ok(())}}