web search done right
cleanup warnings (unused functions and imports)
Mikkel Denker8ac2654f06ad
diff --git a/Cargo.toml b/Cargo.tomlindex 907809ec..603166e0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -17,15 +17,14 @@ bincode = "1.3.3"clap = { version = "3.1.18", features = ["derive"] }encoding_rs = "0.8.31"flate2 = "1.0.23"-futures = "0.3.21"htmlescape = "0.3.1"-indicatif = "0.16.2"+indicatif = { version = "0.16.2", features = ["rayon"] }itertools = "0.10.3"lru = "0.7.6"nom = "7.1.1"rand = "0.8.5"rayon = "1.5.3"-reqwest = "0.11.10"+reqwest = { version = "0.11.10", features = ["blocking"] }rusoto_core = "0.48.0"rusoto_s3 = "0.48.0"scraper = "0.13.0"@@ -34,7 +33,6 @@ sled = { version = "0.34.7", features = ["compression"] }tantivy = "0.18.0"thiserror = "1.0.31"tl = "0.7.5"-tokio = { version = "1.18.2", features = ["full"] }tokio-retry = "0.3.0"toml = "0.5.9"tracing = "0.1.34"diff --git a/src/bin/cuely.rs b/src/bin/cuely.rsindex 0024066b..7e45300e 100644--- a/src/bin/cuely.rs+++ b/src/bin/cuely.rs@@ -25,10 +25,9 @@ struct Args {config_file: String,}-#[tokio::main]-async fn main() {+fn main() {let subscriber = FmtSubscriber::builder()- .with_max_level(Level::INFO)+ .with_max_level(Level::TRACE).finish();tracing::subscriber::set_global_default(subscriber).unwrap();@@ -42,7 +41,6 @@ async fn main() {Config::Indexer(config) => {Indexer::from(config).run()- .await.expect("Failed to index documents");}Config::Webgraph(config) => WebgraphBuilder::from(config)diff --git a/src/directory.rs b/src/directory.rsindex cf5075e2..43802b18 100644--- a/src/directory.rs+++ b/src/directory.rs@@ -77,18 +77,3 @@ pub fn scan_folder(path: String) -> Result<DirEntry> {name: path,})}--pub fn serialize(path: String) -> Result<Vec<u8>> {- let folder = scan_folder(path)?;- Ok(bincode::serialize(&folder)?)-}--pub fn deserialize(bytes: &[u8]) -> Result<String> {- let entry = bincode::deserialize(bytes)?;- recreate_folder(&entry)?;-- match entry {- DirEntry::Folder { name, entries: _ } => Ok(name),- DirEntry::File { name, content: _ } => Ok(name),- }-}diff --git a/src/entrypoint/indexer.rs b/src/entrypoint/indexer.rsindex 838ca17b..78c79998 100644--- a/src/entrypoint/indexer.rs+++ b/src/entrypoint/indexer.rs@@ -13,7 +13,6 @@//// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.-use futures::prelude::*;use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};use std::fs::File;use std::io::{self, BufRead};@@ -41,7 +40,7 @@ impl From<IndexingConfig> for Indexer {}impl Indexer {- pub async fn run(self) -> Result<()> {+ pub fn run(self) -> Result<()> {let pb = ProgressBar::new(self.warc_paths.len() as u64);pb.set_style(ProgressStyle::default_bar()@@ -51,36 +50,28 @@ impl Indexer {.progress_chars("#>-"),);- stream::iter(self.warc_paths.into_iter().progress_with(pb))+ self.warc_paths+ .into_iter()+ .progress_with(pb).map(|warc_path| {let source = self.config.warc_source.clone();- tokio::spawn(async move { WarcFile::download(source, &warc_path).await })+ WarcFile::download(source, &warc_path)})- .buffer_unordered(20).map(|warc| {- tokio::task::spawn_blocking(move || {- if warc.is_err() {- return;- }- let warc = warc.unwrap();+ if warc.is_err() {+ return;+ }+ let warc = warc.unwrap();- if warc.is_err() {- return;- }- let warc = warc.unwrap();-- for record in warc.records().flatten() {- let _webpage = Html::parse(&record.response.body, &record.request.url);- // println!("TEST: {:?}", webpage.title());- // println!();- }- // panic!();- })+ for record in warc.records().flatten() {+ let _webpage = Html::parse(&record.response.body, &record.request.url);+ // println!("TEST: {:?}", webpage.title());+ // println!();+ }+ // panic!();})- .buffer_unordered(20)- .collect::<Vec<_>>()- .await;+ .for_each(drop);Ok(())}diff --git a/src/entrypoint/webgraph.rs b/src/entrypoint/webgraph.rsindex ae2cda44..086a6261 100644--- a/src/entrypoint/webgraph.rs+++ b/src/entrypoint/webgraph.rs@@ -21,7 +21,6 @@ use crate::{HttpConfig, LocalConfig, Result, WarcSource, WebgraphConfig, WebgraphLocalConfig,WebgraphMasterConfig, WebgraphWorkerConfig,};-use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};use serde::{Deserialize, Serialize};use std::{net::SocketAddr, path::Path};use tracing::{debug, info};@@ -61,8 +60,9 @@ impl Map<FrozenWebgraph> for Job {JobConfig::Local(config) => WarcSource::Local(config),};- let file =- futures::executor::block_on(WarcFile::download(source, &self.warc_path)).unwrap();+ debug!("downlooading warc file");+ let file = WarcFile::download(source, &self.warc_path).unwrap();+ debug!("finished downloading");for record in file.records().flatten() {let webpage = Html::parse(&record.response.body, &record.request.url);@@ -127,18 +127,9 @@ impl WebgraphBuilder {WarcSource::Local(config) => JobConfig::Local(config),};- let pb = ProgressBar::new(warc_paths.len() as u64);- pb.set_style(- ProgressStyle::default_bar()- .template(- "{spinner:.green} [{elapsed_precise}] [{wide_bar}] {pos:>7}/{len:7} ({eta})",- )- .progress_chars("#>-"),- );-warc_paths.into_iter()- .take(10)+ .take(15).map(|warc_path| Job {config: job_config.clone(),warc_path,diff --git a/src/index.rs b/src/index.rsindex 84c53d94..449fffe3 100644--- a/src/index.rs+++ b/src/index.rs@@ -17,19 +17,18 @@ use tantivy::collector::{Collector, Count};use tantivy::{DocAddress, Document, LeasedItem};use crate::query::Query;-use crate::schema::{create_schema, Field, ALL_FIELDS};+use crate::schema::{Field, ALL_FIELDS};use crate::searcher::SearchResult;use crate::snippet;-use crate::tokenizer::Tokenizer;use crate::webpage::Webpage;use crate::Result;use std::path::Path;pub struct Index {- tantivy_index: tantivy::Index,- writer: tantivy::IndexWriter,- reader: tantivy::IndexReader,- schema: tantivy::schema::Schema,+ pub(crate) tantivy_index: tantivy::Index,+ pub(crate) writer: tantivy::IndexWriter,+ pub(crate) reader: tantivy::IndexReader,+ pub(crate) schema: tantivy::schema::Schema,}impl Index {@@ -37,22 +36,6 @@ impl Index {todo!();}- pub(crate) fn temporary() -> Result<Self> {- let schema = create_schema();- let tantivy_index = tantivy::Index::create_in_ram(schema);-- tantivy_index- .tokenizers()- .register("tokenizer", Tokenizer::default());-- Ok(Self {- writer: tantivy_index.writer(100_000_000)?,- reader: tantivy_index.reader()?,- schema: create_schema(),- tantivy_index,- })- }-pub fn insert(&mut self, webpage: Webpage) -> Result<()> {self.writer.add_document(webpage.into_tantivy(&self.schema)?)?;@@ -146,13 +129,14 @@ impl From<Document> for RetrievedWebpage {#[cfg(test)]mod tests {+ use crate::tests::temporary_index;use crate::{ranking::Ranker, webpage::Link};use super::*;#[test]fn simple_search() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("website").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -188,7 +172,7 @@ mod tests {#[test]fn document_not_matching() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("this query should not match").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -217,7 +201,7 @@ mod tests {#[test]fn english_stemming() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("runner").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -246,7 +230,7 @@ mod tests {#[test]fn stemmed_query_english() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("runners").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -275,7 +259,7 @@ mod tests {#[test]fn searchable_backlinks() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("great site").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -330,7 +314,7 @@ mod tests {#[test]fn limited_top_docs() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("runner").expect("Failed to parse query");let ranker = Ranker::new(query.clone());@@ -361,7 +345,7 @@ mod tests {#[test]fn host_search() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");let query = Query::parse("dr").expect("Failed to parse query");let ranker = Ranker::new(query.clone());diff --git a/src/lib.rs b/src/lib.rsindex 0ce2fa79..1c4c8131 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -27,14 +27,14 @@ pub mod mapreduce;mod directory;mod query;-mod ranking;+pub mod ranking;mod schema;-mod searcher;+pub mod searcher;mod snippet;mod tokenizer;mod warc;-mod webgraph;-mod webpage;+pub mod webgraph;+pub mod webpage;#[derive(Debug, Deserialize, Clone)]#[serde(tag = "type")]@@ -166,3 +166,25 @@ pub enum Error {}pub(crate) type Result<T> = std::result::Result<T, Error>;++#[cfg(test)]+pub(crate) mod tests {+ use super::*;+ use crate::{index::Index, schema::create_schema, tokenizer::Tokenizer};++ pub fn temporary_index() -> Result<Index> {+ let schema = create_schema();+ let tantivy_index = tantivy::Index::create_in_ram(schema);++ tantivy_index+ .tokenizers()+ .register("tokenizer", Tokenizer::default());++ Ok(Index {+ writer: tantivy_index.writer(100_000_000)?,+ reader: tantivy_index.reader()?,+ schema: create_schema(),+ tantivy_index,+ })+ }+}diff --git a/src/mapreduce/manager.rs b/src/mapreduce/manager.rsindex 8ae2bd75..0cc2c587 100644--- a/src/mapreduce/manager.rs+++ b/src/mapreduce/manager.rs@@ -1,17 +1,16 @@+use super::{Error, Result};+use super::{Map, Reduce};+use crate::mapreduce::Task;+use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};+use rayon::iter::ParallelBridge;+use rayon::prelude::*;use std::io::{Read, Write};+use std::net::ToSocketAddrs;use std::net::{SocketAddr, TcpStream};use std::ops::Deref;use std::sync::atomic::{AtomicU32, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;--use crate::mapreduce::Task;--use super::{Error, Result};-use super::{Map, Reduce};-use rayon::iter::ParallelBridge;-use rayon::prelude::*;-use std::net::ToSocketAddrs;use tokio_retry::strategy::ExponentialBackoff;use tracing::{debug, warn};@@ -258,15 +257,41 @@ impl Manager {{let acc = Arc::new(Mutex::new(None));- jobs.par_bridge()- .map(|job| self.map::<I, O>(job))- .fold(|| None, |acc, elem| Some(Manager::reduce(acc, elem)))- .for_each(|res| {- if let Some(res) = res {- let mut lock = acc.lock().unwrap();- *lock = Some(Manager::reduce(lock.take(), res));- }- });+ let size = jobs.size_hint();++ match size.1 {+ Some(size) => {+ let pb = ProgressBar::new(size as u64);+ pb.set_style(+ ProgressStyle::default_bar()+ .template(+ "{spinner:.green} [{elapsed_precise}] [{wide_bar}] {pos:>7}/{len:7} ({eta})",+ )+ .progress_chars("#>-"),+ );+ jobs.par_bridge()+ .map(|job| self.map::<I, O>(job))+ .progress_with(pb)+ .fold(|| None, |acc, elem| Some(Manager::reduce(acc, elem)))+ .for_each(|res| {+ if let Some(res) = res {+ let mut lock = acc.lock().unwrap();+ *lock = Some(Manager::reduce(lock.take(), res));+ }+ });+ }+ None => {+ jobs.par_bridge()+ .map(|job| self.map::<I, O>(job))+ .fold(|| None, |acc, elem| Some(Manager::reduce(acc, elem)))+ .for_each(|res| {+ if let Some(res) = res {+ let mut lock = acc.lock().unwrap();+ *lock = Some(Manager::reduce(lock.take(), res));+ }+ });+ }+ }let x = acc.lock().unwrap().take();xdiff --git a/src/mapreduce/worker.rs b/src/mapreduce/worker.rsindex 35f1d46e..289c59bd 100644--- a/src/mapreduce/worker.rs+++ b/src/mapreduce/worker.rs@@ -85,13 +85,7 @@ impl Worker {#[cfg(test)]mod tests {- use std::{- pin::Pin,- task::{Context, Poll},- };-use serde::Deserialize;- use tokio::io::ReadBuf;use super::*;@@ -114,9 +108,9 @@ mod tests {impl Read for MockTcpStream {fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result<usize> {if self.num_read == 0 {- buf.write_all(&self.contents[..]);+ buf.write_all(&self.contents[..]).unwrap();} else if self.num_read == 1 {- buf.write_all(&END_OF_MESSAGE);+ buf.write_all(&END_OF_MESSAGE).unwrap();}self.contents = Vec::new();@@ -150,6 +144,7 @@ mod tests {}}+ #[test]fn execute() {let contents = vec![1, 2, 0, 1, 0, 1, 0];let job = bincode::serialize(&Task::Job(MockJob { contents })).unwrap();diff --git a/src/ranking/mod.rs b/src/ranking/mod.rsindex 43934c9f..bf1348fe 100644--- a/src/ranking/mod.rs+++ b/src/ranking/mod.rs@@ -42,15 +42,15 @@ impl Ranker {#[cfg(test)]mod tests {use crate::{- index::Index,searcher::Searcher,+ tests::temporary_index,webpage::{Link, Webpage},};#[test]fn harmonic_ranking() {for _ in 0..10 {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");index.insert(Webpage::new(@@ -97,7 +97,7 @@ mod tests {#[test]fn navigational_search() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");index.insert(Webpage::new(diff --git a/src/snippet.rs b/src/snippet.rsindex c7355802..20c78f99 100644--- a/src/snippet.rs+++ b/src/snippet.rs@@ -297,7 +297,8 @@ pub fn generate(query: &Query, text: &str, searcher: &tantivy::Searcher) -> Resu#[cfg(test)]mod tests {use super::*;- use crate::{index::Index, searcher::Searcher, webpage::Webpage};+ use crate::tests::temporary_index;+ use crate::{searcher::Searcher, webpage::Webpage};use maplit::btreemap;use tantivy::tokenizer::SimpleTokenizer;@@ -315,7 +316,7 @@ Survey in 2016, 2017, and 2018."#;#[test]fn snippet_during_search() {- let mut index = Index::temporary().expect("Unable to open index");+ let mut index = temporary_index().expect("Unable to open index");index.insert(Webpage::new(diff --git a/src/tokenizer.rs b/src/tokenizer.rsindex 12c8d2e8..9cda808c 100644--- a/src/tokenizer.rs+++ b/src/tokenizer.rs@@ -110,7 +110,7 @@ impl tantivy::tokenizer::Tokenizer for Tokenizer {tokens.sort_by(|a, b| {a.offset_from.partial_cmp(&b.offset_from)- .unwrap_or(a.offset_to.cmp(&b.offset_to))+ .unwrap_or_else(|| a.offset_to.cmp(&b.offset_to))});tantivy::tokenizer::BoxTokenStream::from(PreTokenizedStream::from(PreTokenizedString {diff --git a/src/warc.rs b/src/warc.rsindex c4c122cb..74c7013d 100644--- a/src/warc.rs+++ b/src/warc.rs@@ -18,11 +18,9 @@ use std::collections::BTreeMap;use std::fs::File;use std::io::{BufRead, BufReader, Read};use std::path::Path;-use tokio::io::AsyncReadExt;+use std::time::Duration;use flate2::read::MultiGzDecoder;-use rusoto_core::Region;-use rusoto_s3::{GetObjectRequest, S3Client, S3};pub(crate) struct WarcFile {bytes: Vec<u8>,@@ -68,20 +66,15 @@ impl WarcFile {}}- pub(crate) async fn download(source: WarcSource, path: &str) -> Result<Self> {+ pub(crate) fn download(source: WarcSource, path: &str) -> Result<Self> {match source {- WarcSource::S3(config) => {- WarcFile::download_from_s3(- path,- config.name.clone(),- config.endpoint.clone(),- config.bucket.clone(),- )- .await- }- WarcSource::HTTP(config) => {- WarcFile::download_from_http(path, config.base_url.clone()).await- }+ WarcSource::S3(config) => WarcFile::download_from_s3(+ path,+ config.name.clone(),+ config.endpoint.clone(),+ config.bucket,+ ),+ WarcSource::HTTP(config) => WarcFile::download_from_http(path, config.base_url),WarcSource::Local(config) => WarcFile::load_from_folder(path, &config.folder),}}@@ -96,51 +89,59 @@ impl WarcFile {Ok(WarcFile::new(bytes))}- async fn download_from_http(path: &str, base_url: String) -> Result<Self> {+ fn download_from_http(path: &str, base_url: String) -> Result<Self> {let mut url = base_url;if !url.ends_with('/') {url += "/";}url += path;- let client = reqwest::Client::new();- let res = client.get(url).send().await?;+ let client = reqwest::blocking::ClientBuilder::new()+ .tcp_keepalive(Duration::from_secs(120))+ .connect_timeout(Duration::from_secs(20))+ .timeout(Duration::from_secs(300))+ .pool_idle_timeout(Duration::from_secs(0))+ .pool_max_idle_per_host(0)+ .connection_verbose(true)+ .build()?;+ let res = client.get(url).send()?;- let bytes = Vec::from(&res.bytes().await?[..]);+ let bytes = Vec::from(&res.bytes()?[..]);Ok(WarcFile::new(bytes))}- async fn download_from_s3(- path: &str,- region_name: String,- region_endpoint: String,- bucket: String,+ fn download_from_s3(+ _path: &str,+ _region_name: String,+ _region_endpoint: String,+ _bucket: String,) -> Result<Self> {- let path = path.to_string();- let region = Region::Custom {- name: region_name,- endpoint: region_endpoint,- };-- let client = S3Client::new(region);-- let obj = client- .get_object(GetObjectRequest {- bucket,- key: path,- ..Default::default()- })- .await?;-- let mut bytes = Vec::new();- obj.body- .ok_or(Error::S3DownloadError)?- .into_async_read()- .read_to_end(&mut bytes)- .await?;-- Ok(WarcFile::new(bytes))+ todo!();+ // let path = path.to_string();+ // let region = Region::Custom {+ // name: region_name,+ // endpoint: region_endpoint,+ // };++ // let client = S3Client::new(region);++ // let obj = client+ // .get_object(GetObjectRequest {+ // bucket,+ // key: path,+ // ..Default::default()+ // })+ // .await?;++ // let mut bytes = Vec::new();+ // obj.body+ // .ok_or(Error::S3DownloadError)?+ // .into_async_read()+ // .read_to_end(&mut bytes)+ // .await?;++ // Ok(WarcFile::new(bytes))}}diff --git a/src/webpage.rs b/src/webpage.rsindex 4cc3a0b8..3fd4295a 100644--- a/src/webpage.rs+++ b/src/webpage.rs@@ -22,7 +22,7 @@ use tl::Children;use crate::schema::{Field, ALL_FIELDS};-fn strip_protocol<'a>(url: &'a str) -> &'a str {+fn strip_protocol(url: &str) -> &'_ str {let mut start_host = 0;if url.starts_with("http://") || url.starts_with("https://") {start_host = url@@ -34,7 +34,7 @@ fn strip_protocol<'a>(url: &'a str) -> &'a str {&url[start_host..]}-pub(crate) fn host<'a>(url: &'a str) -> &'a str {+pub(crate) fn host(url: &str) -> &'_ str {let url = strip_protocol(url);let mut end_host = url.len();@@ -45,7 +45,7 @@ pub(crate) fn host<'a>(url: &'a str) -> &'a str {&url[..end_host]}-pub(crate) fn is_homepage<'a>(url: &'a str) -> bool {+pub(crate) fn is_homepage(url: &str) -> bool {let url = strip_protocol(url);match url.find('/') {Some(idx) => idx == url.len() - 1,@@ -53,7 +53,7 @@ pub(crate) fn is_homepage<'a>(url: &'a str) -> bool {}}-pub(crate) fn domain<'a>(url: &'a str) -> &'a str {+pub(crate) fn domain(url: &str) -> &'_ str {let host = host(url);let num_punctuations: usize = host.chars().map(|c| if c == '.' { 1 } else { 0 }).sum();if num_punctuations > 1 {