mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
refactor: rebuild desktop app with Tauri
This commit is contained in:
1 parent
a3ec2a0dfc
commit
4053a7fb20
808 files changed
+87359
-181491
No files matched your search
@@ -0,0 +1,230 @@
|
||||
use super::{HtmlEngine, JsonEngine, SearchEngine};
|
||||
|
||||
macro_rules! html {
|
||||
($id:literal, $url:literal, $item:literal, $title:literal, $link:literal, $snippet:literal) => {
|
||||
SearchEngine::from(HtmlEngine::new(
|
||||
$id,
|
||||
$url.into(),
|
||||
$item,
|
||||
$title,
|
||||
$link,
|
||||
$snippet,
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! json {
|
||||
($id:literal, $url:literal, $items:literal, $title:literal, $link:literal, $snippet:literal) => {
|
||||
SearchEngine::from(JsonEngine::new(
|
||||
$id,
|
||||
$url.into(),
|
||||
$items,
|
||||
$title,
|
||||
$link,
|
||||
$snippet,
|
||||
None,
|
||||
))
|
||||
};
|
||||
($id:literal, $url:literal, $items:literal, $title:literal, $link:literal, $snippet:literal, $template:literal) => {
|
||||
SearchEngine::from(JsonEngine::new(
|
||||
$id,
|
||||
$url.into(),
|
||||
$items,
|
||||
$title,
|
||||
$link,
|
||||
$snippet,
|
||||
Some($template),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn engines() -> Vec<SearchEngine> {
|
||||
vec![
|
||||
html!(
|
||||
"google",
|
||||
"https://www.google.com/search?q={query}&num=10",
|
||||
"div.MjjYud",
|
||||
"h3",
|
||||
"a",
|
||||
"div.VwiC3b"
|
||||
),
|
||||
html!(
|
||||
"bing",
|
||||
"https://www.bing.com/search?q={query}&count=10",
|
||||
"li.b_algo",
|
||||
"h2",
|
||||
"h2 a",
|
||||
".b_caption p"
|
||||
),
|
||||
html!(
|
||||
"brave",
|
||||
"https://search.brave.com/search?q={query}&source=web",
|
||||
".snippet",
|
||||
".title",
|
||||
"a",
|
||||
".snippet-description"
|
||||
),
|
||||
html!(
|
||||
"duckduckgo",
|
||||
"https://html.duckduckgo.com/html/?q={query}",
|
||||
".result",
|
||||
".result__a",
|
||||
".result__a",
|
||||
".result__snippet"
|
||||
),
|
||||
html!(
|
||||
"startpage",
|
||||
"https://www.startpage.com/sp/search?query={query}",
|
||||
".w-gl__result",
|
||||
".w-gl__result-title",
|
||||
"a.w-gl__result-title",
|
||||
".w-gl__description"
|
||||
),
|
||||
html!(
|
||||
"yahoo",
|
||||
"https://search.yahoo.com/search?p={query}",
|
||||
"div.dd.algo",
|
||||
"h3.title",
|
||||
"h3.title a",
|
||||
".compText"
|
||||
),
|
||||
html!(
|
||||
"mojeek",
|
||||
"https://www.mojeek.com/search?q={query}",
|
||||
"ul.results-standard > li",
|
||||
"h2",
|
||||
"h2 a",
|
||||
".s"
|
||||
),
|
||||
html!(
|
||||
"qwant",
|
||||
"https://www.qwant.com/?q={query}&t=web",
|
||||
"article",
|
||||
"h2",
|
||||
"a",
|
||||
"p"
|
||||
),
|
||||
html!(
|
||||
"ecosia",
|
||||
"https://www.ecosia.org/search?q={query}",
|
||||
"article",
|
||||
"h2",
|
||||
"a",
|
||||
"p"
|
||||
),
|
||||
html!(
|
||||
"yandex",
|
||||
"https://yandex.com/search/?text={query}",
|
||||
".serp-item",
|
||||
"h2",
|
||||
"h2 a",
|
||||
".OrganicTextContentSpan"
|
||||
),
|
||||
html!(
|
||||
"baidu",
|
||||
"https://www.baidu.com/s?wd={query}",
|
||||
"div.result",
|
||||
"h3",
|
||||
"h3 a",
|
||||
".c-abstract"
|
||||
),
|
||||
html!(
|
||||
"sogou",
|
||||
"https://www.sogou.com/web?query={query}",
|
||||
".vrwrap",
|
||||
"h3",
|
||||
"h3 a",
|
||||
".str_info"
|
||||
),
|
||||
html!(
|
||||
"so360",
|
||||
"https://www.so.com/s?q={query}",
|
||||
".res-list",
|
||||
"h3",
|
||||
"h3 a",
|
||||
".res-desc"
|
||||
),
|
||||
html!(
|
||||
"naver",
|
||||
"https://search.naver.com/search.naver?query={query}",
|
||||
".total_wrap",
|
||||
".total_tit",
|
||||
"a.total_tit",
|
||||
".dsc_txt"
|
||||
),
|
||||
html!(
|
||||
"seznam",
|
||||
"https://search.seznam.cz/?q={query}",
|
||||
".Result",
|
||||
".Result-title",
|
||||
"a.Result-title",
|
||||
".Result-description"
|
||||
),
|
||||
json!(
|
||||
"wikipedia",
|
||||
"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={query}&srlimit=10&format=json",
|
||||
"/query/search",
|
||||
"/title",
|
||||
"/pageid",
|
||||
"/snippet",
|
||||
"https://en.wikipedia.org/?curid={value}"
|
||||
),
|
||||
html!(
|
||||
"github",
|
||||
"https://github.com/search?q={query}&type=repositories",
|
||||
"[data-testid='results-list'] > div",
|
||||
"h3",
|
||||
"h3 a",
|
||||
"p"
|
||||
),
|
||||
json!(
|
||||
"stackoverflow",
|
||||
"https://api.stackexchange.com/2.3/search/advanced?site=stackoverflow&q={query}&pagesize=10&filter=withbody",
|
||||
"/items",
|
||||
"/title",
|
||||
"/link",
|
||||
"/body"
|
||||
),
|
||||
json!(
|
||||
"crates_io",
|
||||
"https://crates.io/api/v1/crates?q={query}&per_page=10",
|
||||
"/crates",
|
||||
"/name",
|
||||
"/id",
|
||||
"/description",
|
||||
"https://crates.io/crates/{value}"
|
||||
),
|
||||
json!(
|
||||
"npm",
|
||||
"https://registry.npmjs.org/-/v1/search?text={query}&size=10",
|
||||
"/objects",
|
||||
"/package/name",
|
||||
"/package/links/npm",
|
||||
"/package/description"
|
||||
),
|
||||
html!(
|
||||
"pypi",
|
||||
"https://pypi.org/search/?q={query}",
|
||||
".package-snippet",
|
||||
".package-snippet__name",
|
||||
"a.package-snippet",
|
||||
".package-snippet__description"
|
||||
),
|
||||
html!(
|
||||
"arxiv",
|
||||
"https://arxiv.org/search/?query={query}&searchtype=all",
|
||||
"li.arxiv-result",
|
||||
"p.title",
|
||||
"p.list-title a",
|
||||
"span.abstract-full"
|
||||
),
|
||||
json!(
|
||||
"crossref",
|
||||
"https://api.crossref.org/works?query={query}&rows=10",
|
||||
"/message/items",
|
||||
"/title/0",
|
||||
"/URL",
|
||||
"/abstract"
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use scraper::{ElementRef, Html, Selector};
|
||||
use serde_json::Value;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HtmlEngine {
|
||||
pub(crate) id: &'static str,
|
||||
url: String,
|
||||
result: String,
|
||||
title: String,
|
||||
link: String,
|
||||
snippet: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct JsonEngine {
|
||||
id: &'static str,
|
||||
url: String,
|
||||
items: &'static str,
|
||||
title: &'static str,
|
||||
link: &'static str,
|
||||
snippet: &'static str,
|
||||
link_template: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SearchEngine {
|
||||
Html(HtmlEngine),
|
||||
Json(JsonEngine),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SearchHit {
|
||||
pub title: String,
|
||||
pub url: String,
|
||||
pub chunk: String,
|
||||
pub engines: Vec<&'static str>,
|
||||
pub(crate) score: f64,
|
||||
}
|
||||
|
||||
impl SearchHit {
|
||||
pub fn new(
|
||||
title: impl Into<String>,
|
||||
url: impl Into<String>,
|
||||
chunk: impl Into<String>,
|
||||
engines: Vec<&'static str>,
|
||||
) -> Self {
|
||||
Self {
|
||||
title: title.into(),
|
||||
url: url.into(),
|
||||
chunk: chunk.into(),
|
||||
engines,
|
||||
score: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HtmlEngine {
|
||||
pub fn new(
|
||||
id: &'static str,
|
||||
url: String,
|
||||
result: impl Into<String>,
|
||||
title: impl Into<String>,
|
||||
link: impl Into<String>,
|
||||
snippet: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
url,
|
||||
result: result.into(),
|
||||
title: title.into(),
|
||||
link: link.into(),
|
||||
snippet: snippet.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn search(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
query: &str,
|
||||
) -> Result<Vec<SearchHit>, String> {
|
||||
let url = search_url(&self.url, query);
|
||||
let response = client
|
||||
.get(&url)
|
||||
.header(reqwest::header::USER_AGENT, user_agent())
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"text/html,application/xhtml+xml;q=0.9,*/*;q=0.1",
|
||||
)
|
||||
.timeout(Duration::from_secs(12))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("request failed: {error}"))?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("HTTP {}", response.status()));
|
||||
}
|
||||
let response_url = response.url().clone();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|error| format!("response failed: {error}"))?;
|
||||
self.parse(&body, &response_url)
|
||||
}
|
||||
|
||||
fn parse(&self, body: &str, response_url: &Url) -> Result<Vec<SearchHit>, String> {
|
||||
let result = selector(&self.result)?;
|
||||
let title = selector(&self.title)?;
|
||||
let link = selector(&self.link)?;
|
||||
let snippet = selector(&self.snippet)?;
|
||||
let document = Html::parse_document(body);
|
||||
Ok(document
|
||||
.select(&result)
|
||||
.filter_map(|item| self.parse_item(item, &title, &link, &snippet, response_url))
|
||||
.take(10)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn parse_item(
|
||||
&self,
|
||||
item: ElementRef<'_>,
|
||||
title: &Selector,
|
||||
link: &Selector,
|
||||
snippet: &Selector,
|
||||
response_url: &Url,
|
||||
) -> Option<SearchHit> {
|
||||
let title = text(item.select(title).next()?);
|
||||
let href = item
|
||||
.select(link)
|
||||
.next()
|
||||
.and_then(|element| element.value().attr("href"))
|
||||
.or_else(|| item.value().attr("href"))?;
|
||||
let url = result_url(response_url, href)?;
|
||||
let chunk = item.select(snippet).next().map(text).unwrap_or_default();
|
||||
(!title.is_empty()).then_some(SearchHit::new(title, url, chunk, vec![self.id]))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonEngine {
|
||||
pub fn new(
|
||||
id: &'static str,
|
||||
url: String,
|
||||
items: &'static str,
|
||||
title: &'static str,
|
||||
link: &'static str,
|
||||
snippet: &'static str,
|
||||
link_template: Option<&'static str>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
url,
|
||||
items,
|
||||
title,
|
||||
link,
|
||||
snippet,
|
||||
link_template,
|
||||
}
|
||||
}
|
||||
|
||||
async fn search(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
query: &str,
|
||||
) -> Result<Vec<SearchHit>, String> {
|
||||
let response = client
|
||||
.get(search_url(&self.url, query))
|
||||
.header(reqwest::header::USER_AGENT, user_agent())
|
||||
.header(reqwest::header::ACCEPT, "application/json")
|
||||
.timeout(Duration::from_secs(12))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("request failed: {error}"))?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("HTTP {}", response.status()));
|
||||
}
|
||||
let body = response
|
||||
.json::<Value>()
|
||||
.await
|
||||
.map_err(|error| format!("response failed: {error}"))?;
|
||||
let items = body
|
||||
.pointer(self.items)
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| format!("missing result array: {}", self.items))?;
|
||||
Ok(items
|
||||
.iter()
|
||||
.filter_map(|item| self.parse_item(item))
|
||||
.take(10)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn parse_item(&self, item: &Value) -> Option<SearchHit> {
|
||||
let title = plain_text(&json_text(item.pointer(self.title)?));
|
||||
let link = json_text(item.pointer(self.link)?);
|
||||
let link = match self.link_template {
|
||||
Some(template) => template.replace(
|
||||
"{value}",
|
||||
&url::form_urlencoded::byte_serialize(link.as_bytes()).collect::<String>(),
|
||||
),
|
||||
None => link,
|
||||
};
|
||||
let url = canonical_url(&link)?;
|
||||
let chunk = item
|
||||
.pointer(self.snippet)
|
||||
.map(json_text)
|
||||
.map(|value| plain_text(&value))
|
||||
.unwrap_or_default();
|
||||
(!title.is_empty()).then_some(SearchHit::new(title, url, chunk, vec![self.id]))
|
||||
}
|
||||
}
|
||||
|
||||
impl SearchEngine {
|
||||
pub(crate) fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Html(engine) => engine.id,
|
||||
Self::Json(engine) => engine.id,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn search(
|
||||
&self,
|
||||
client: &reqwest::Client,
|
||||
query: &str,
|
||||
) -> Result<Vec<SearchHit>, String> {
|
||||
match self {
|
||||
Self::Html(engine) => engine.search(client, query).await,
|
||||
Self::Json(engine) => engine.search(client, query).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HtmlEngine> for SearchEngine {
|
||||
fn from(value: HtmlEngine) -> Self {
|
||||
Self::Html(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonEngine> for SearchEngine {
|
||||
fn from(value: JsonEngine) -> Self {
|
||||
Self::Json(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn selector(value: &str) -> Result<Selector, String> {
|
||||
Selector::parse(value).map_err(|_| format!("invalid selector: {value}"))
|
||||
}
|
||||
|
||||
fn text(element: ElementRef<'_>) -> String {
|
||||
element
|
||||
.text()
|
||||
.flat_map(str::split_whitespace)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn search_url(template: &str, query: &str) -> String {
|
||||
template.replace(
|
||||
"{query}",
|
||||
&url::form_urlencoded::byte_serialize(query.as_bytes()).collect::<String>(),
|
||||
)
|
||||
}
|
||||
|
||||
fn user_agent() -> &'static str {
|
||||
"Mozilla/5.0 (compatible; CursorBYOK/0.1; +https://github.com)"
|
||||
}
|
||||
|
||||
fn json_text(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(value) => value.clone(),
|
||||
Value::Number(value) => value.to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain_text(value: &str) -> String {
|
||||
let fragment = Html::parse_fragment(value);
|
||||
fragment
|
||||
.root_element()
|
||||
.text()
|
||||
.flat_map(str::split_whitespace)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn canonical_url(value: &str) -> Option<String> {
|
||||
canonicalize(Url::parse(value).ok()?)
|
||||
}
|
||||
|
||||
fn result_url(base: &Url, href: &str) -> Option<String> {
|
||||
canonicalize(base.join(href).ok()?)
|
||||
}
|
||||
|
||||
fn canonicalize(mut url: Url) -> Option<String> {
|
||||
if let Some(target) = redirected_target(&url) {
|
||||
url = target;
|
||||
}
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return None;
|
||||
}
|
||||
url.set_fragment(None);
|
||||
let retained = url
|
||||
.query_pairs()
|
||||
.filter(|(key, _)| {
|
||||
!key.starts_with("utm_")
|
||||
&& !matches!(key.as_ref(), "gclid" | "fbclid" | "mc_cid" | "mc_eid")
|
||||
})
|
||||
.map(|(key, value)| (key.into_owned(), value.into_owned()))
|
||||
.collect::<Vec<_>>();
|
||||
url.set_query(None);
|
||||
if !retained.is_empty() {
|
||||
url.query_pairs_mut().extend_pairs(retained);
|
||||
}
|
||||
Some(url.to_string().trim_end_matches('/').to_string())
|
||||
}
|
||||
|
||||
fn redirected_target(url: &Url) -> Option<Url> {
|
||||
let host = url.host_str()?;
|
||||
if host.contains("bing.com") && url.path() == "/ck/a" {
|
||||
return url
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == "u")
|
||||
.and_then(|(_, value)| value.strip_prefix("a1").map(str::to_string))
|
||||
.and_then(|value| URL_SAFE_NO_PAD.decode(value).ok())
|
||||
.and_then(|value| String::from_utf8(value).ok())
|
||||
.and_then(|value| Url::parse(&value).ok());
|
||||
}
|
||||
let key = if host.contains("duckduckgo.com") {
|
||||
"uddg"
|
||||
} else if host.contains("google.") && url.path() == "/url" {
|
||||
"q"
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
url.query_pairs()
|
||||
.find(|(name, _)| name == key)
|
||||
.and_then(|(_, value)| Url::parse(&value).ok())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use url::Url;
|
||||
|
||||
use super::result_url;
|
||||
|
||||
#[test]
|
||||
fn unwraps_bing_encoded_result_url() {
|
||||
let base = Url::parse("https://www.bing.com/search?q=rust").unwrap();
|
||||
let result = result_url(&base, "/ck/a?u=a1aHR0cHM6Ly9ydXN0LWxhbmcub3Jn&ntb=1").unwrap();
|
||||
|
||||
assert_eq!(result, "https://rust-lang.org");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use std::{cmp::Ordering, collections::HashMap};
|
||||
|
||||
use futures_util::future::join_all;
|
||||
|
||||
use super::{catalog, SearchEngine, SearchHit};
|
||||
|
||||
const RRF_K: f64 = 60.0;
|
||||
const MAX_RESULTS: usize = 10;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WebSearch {
|
||||
client: reqwest::Client,
|
||||
engines: Vec<SearchEngine>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("web search failed: {0}")]
|
||||
pub struct SearchError(String);
|
||||
|
||||
impl WebSearch {
|
||||
pub fn built_in() -> Self {
|
||||
Self::with_engines(catalog::engines())
|
||||
}
|
||||
|
||||
pub fn with_engines<I, E>(engines: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = E>,
|
||||
E: Into<SearchEngine>,
|
||||
{
|
||||
Self {
|
||||
client: reqwest::Client::new(),
|
||||
engines: engines.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn engine_ids(&self) -> Vec<&'static str> {
|
||||
self.engines.iter().map(SearchEngine::id).collect()
|
||||
}
|
||||
|
||||
pub async fn search(&self, query: &str) -> Result<Vec<SearchHit>, SearchError> {
|
||||
let query = query.trim();
|
||||
if query.is_empty() {
|
||||
return Err(SearchError("query is empty".into()));
|
||||
}
|
||||
let responses = join_all(
|
||||
self.engines
|
||||
.iter()
|
||||
.map(|engine| engine.search(&self.client, query)),
|
||||
)
|
||||
.await;
|
||||
let mut merged = HashMap::<String, SearchHit>::new();
|
||||
let mut failures = Vec::new();
|
||||
for (engine, response) in self.engines.iter().zip(responses) {
|
||||
match response {
|
||||
Ok(results) if !results.is_empty() => {
|
||||
tracing::debug!(
|
||||
engine = engine.id(),
|
||||
results = results.len(),
|
||||
"search engine completed"
|
||||
);
|
||||
merge(&mut merged, engine.id(), results)
|
||||
}
|
||||
Ok(_) => {
|
||||
tracing::debug!(engine = engine.id(), "search engine returned no results");
|
||||
failures.push(engine.id().to_string());
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(engine = engine.id(), %error, "search engine failed");
|
||||
failures.push(engine.id().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if merged.is_empty() {
|
||||
return Err(SearchError(format!(
|
||||
"no results from engines: {}",
|
||||
failures.join(", ")
|
||||
)));
|
||||
}
|
||||
let mut results = merged.into_values().collect::<Vec<_>>();
|
||||
results.sort_by(|left, right| {
|
||||
right
|
||||
.score
|
||||
.partial_cmp(&left.score)
|
||||
.unwrap_or(Ordering::Equal)
|
||||
.then_with(|| left.url.cmp(&right.url))
|
||||
});
|
||||
results.truncate(MAX_RESULTS);
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WebSearch {
|
||||
fn default() -> Self {
|
||||
Self::built_in()
|
||||
}
|
||||
}
|
||||
|
||||
fn merge(merged: &mut HashMap<String, SearchHit>, engine: &'static str, results: Vec<SearchHit>) {
|
||||
for (rank, mut result) in results.into_iter().enumerate() {
|
||||
let score = 1.0 / (RRF_K + rank as f64 + 1.0);
|
||||
match merged.get_mut(&result.url) {
|
||||
Some(existing) => {
|
||||
existing.score += score;
|
||||
if !existing.engines.contains(&engine) {
|
||||
existing.engines.push(engine);
|
||||
}
|
||||
if result.chunk.len() > existing.chunk.len() {
|
||||
existing.chunk = result.chunk;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
result.score = score;
|
||||
merged.insert(result.url.clone(), result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use dom_smoothie::{Config, Readability, TextMode};
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::{
|
||||
header::{ACCEPT, ACCEPT_LANGUAGE, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT},
|
||||
redirect::Policy,
|
||||
Response,
|
||||
};
|
||||
use tokio::{net::lookup_host, time::timeout};
|
||||
use url::{Host, Url};
|
||||
|
||||
const MAX_RESPONSE_SIZE: usize = 5 * 1024 * 1024;
|
||||
const MAX_REDIRECTS: usize = 5;
|
||||
const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FetchedPage {
|
||||
pub url: String,
|
||||
pub markdown: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("web fetch failed: {0}")]
|
||||
pub struct FetchError(String);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum NetworkPolicy {
|
||||
PublicOnly,
|
||||
#[cfg(test)]
|
||||
Any,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WebFetch {
|
||||
network: NetworkPolicy,
|
||||
}
|
||||
|
||||
impl WebFetch {
|
||||
pub fn built_in() -> Self {
|
||||
Self {
|
||||
network: NetworkPolicy::PublicOnly,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_test() -> Self {
|
||||
Self {
|
||||
network: NetworkPolicy::Any,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn fetch(&self, value: &str) -> Result<FetchedPage, FetchError> {
|
||||
timeout(FETCH_TIMEOUT, self.fetch_inner(value))
|
||||
.await
|
||||
.map_err(|_| failure("request timed out"))?
|
||||
}
|
||||
|
||||
async fn fetch_inner(&self, value: &str) -> Result<FetchedPage, FetchError> {
|
||||
let mut url = parse_url(value)?;
|
||||
for redirect in 0..=MAX_REDIRECTS {
|
||||
let response = self.request(&url).await?;
|
||||
if response.status().is_redirection() {
|
||||
if redirect == MAX_REDIRECTS {
|
||||
return Err(failure("too many redirects"));
|
||||
}
|
||||
let location = response
|
||||
.headers()
|
||||
.get(LOCATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or_else(|| failure("redirect is missing Location"))?;
|
||||
url = parse_url(
|
||||
url.join(location)
|
||||
.map_err(|error| failure(format!("invalid redirect: {error}")))?
|
||||
.as_str(),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
return Err(failure(format!("HTTP {}", response.status())));
|
||||
}
|
||||
return page(response).await;
|
||||
}
|
||||
unreachable!("redirect loop always returns")
|
||||
}
|
||||
|
||||
async fn request(&self, url: &Url) -> Result<Response, FetchError> {
|
||||
let host = url
|
||||
.host_str()
|
||||
.ok_or_else(|| failure("URL is missing a host"))?;
|
||||
let port = url
|
||||
.port_or_known_default()
|
||||
.ok_or_else(|| failure("URL has no usable port"))?;
|
||||
let addresses = lookup_host((host, port))
|
||||
.await
|
||||
.map_err(|error| failure(format!("DNS lookup failed: {error}")))?
|
||||
.collect::<Vec<_>>();
|
||||
if addresses.is_empty() {
|
||||
return Err(failure("DNS lookup returned no addresses"));
|
||||
}
|
||||
let domain = matches!(url.host(), Some(Host::Domain(_)));
|
||||
if matches!(self.network, NetworkPolicy::PublicOnly)
|
||||
&& addresses
|
||||
.iter()
|
||||
.any(|address| !safe_resolution(address.ip(), domain))
|
||||
{
|
||||
return Err(failure("URL resolves to a non-public address"));
|
||||
}
|
||||
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.redirect(Policy::none())
|
||||
.connect_timeout(Duration::from_secs(10));
|
||||
if domain {
|
||||
builder = builder.resolve_to_addrs(host, &addresses);
|
||||
}
|
||||
let client = builder
|
||||
.build()
|
||||
.map_err(|error| failure(format!("HTTP client failed: {error}")))?;
|
||||
client
|
||||
.get(url.clone())
|
||||
.header(
|
||||
USER_AGENT,
|
||||
"Mozilla/5.0 (compatible; CursorBYOK/0.1; +https://github.com)",
|
||||
)
|
||||
.header(
|
||||
ACCEPT,
|
||||
"text/markdown, text/plain;q=0.9, text/html;q=0.8, application/xhtml+xml;q=0.8, application/json;q=0.7, */*;q=0.1",
|
||||
)
|
||||
.header(ACCEPT_LANGUAGE, "en-US,en;q=0.9")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| failure(format!("request failed: {error}")))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WebFetch {
|
||||
fn default() -> Self {
|
||||
Self::built_in()
|
||||
}
|
||||
}
|
||||
|
||||
async fn page(response: Response) -> Result<FetchedPage, FetchError> {
|
||||
let url = response.url().to_string();
|
||||
let content_type = response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("application/octet-stream")
|
||||
.to_string();
|
||||
if response
|
||||
.headers()
|
||||
.get(CONTENT_LENGTH)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.is_some_and(|length| length > MAX_RESPONSE_SIZE)
|
||||
{
|
||||
return Err(failure("response exceeds 5 MiB"));
|
||||
}
|
||||
let body = limited_body(response).await?;
|
||||
let text = decode(&body, &content_type)?;
|
||||
let media_type = content_type
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
let markdown = match media_type.as_str() {
|
||||
"text/html" | "application/xhtml+xml" => {
|
||||
let source_url = url.clone();
|
||||
tokio::task::spawn_blocking(move || readable_markdown(&text, &source_url))
|
||||
.await
|
||||
.map_err(|error| failure(format!("content task failed: {error}")))??
|
||||
}
|
||||
"text/markdown" | "text/x-markdown" | "text/plain" => text,
|
||||
"application/json" => format!("```json\n{text}\n```"),
|
||||
"application/xml" | "text/xml" => format!("```xml\n{text}\n```"),
|
||||
value if value.starts_with("text/") => text,
|
||||
_ => return Err(failure(format!("unsupported content type: {media_type}"))),
|
||||
};
|
||||
if markdown.trim().is_empty() {
|
||||
return Err(failure("response contains no readable content"));
|
||||
}
|
||||
Ok(FetchedPage { url, markdown })
|
||||
}
|
||||
|
||||
async fn limited_body(response: Response) -> Result<BytesMut, FetchError> {
|
||||
let mut body = BytesMut::new();
|
||||
let mut stream = response.bytes_stream();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|error| failure(format!("response failed: {error}")))?;
|
||||
if body.len() + chunk.len() > MAX_RESPONSE_SIZE {
|
||||
return Err(failure("response exceeds 5 MiB"));
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn readable_markdown(html: &str, url: &str) -> Result<String, FetchError> {
|
||||
let mut readability = Readability::new(
|
||||
html,
|
||||
Some(url),
|
||||
Some(Config {
|
||||
max_elements_to_parse: 50_000,
|
||||
text_mode: TextMode::Markdown,
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.map_err(|error| failure(format!("HTML parse failed: {error}")))?;
|
||||
let article = readability
|
||||
.parse()
|
||||
.map_err(|error| failure(format!("article extraction failed: {error}")))?;
|
||||
let body = article.text_content.trim().to_string();
|
||||
let title = article.title.trim();
|
||||
let heading = format!("# {title}");
|
||||
Ok(if title.is_empty() || body.starts_with(&heading) {
|
||||
body
|
||||
} else {
|
||||
format!("# {title}\n\n{body}")
|
||||
})
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8], content_type: &str) -> Result<String, FetchError> {
|
||||
let charset = content_type.split(';').skip(1).find_map(|parameter| {
|
||||
let (name, value) = parameter.trim().split_once('=')?;
|
||||
name.trim()
|
||||
.eq_ignore_ascii_case("charset")
|
||||
.then(|| value.trim().trim_matches(['\'', '"']))
|
||||
});
|
||||
let encoding = match charset {
|
||||
Some(label) => encoding_rs::Encoding::for_label(label.as_bytes())
|
||||
.ok_or_else(|| failure(format!("unsupported charset: {label}")))?,
|
||||
None => encoding_rs::UTF_8,
|
||||
};
|
||||
let (text, _, malformed) = encoding.decode(bytes);
|
||||
if malformed {
|
||||
return Err(failure("response contains malformed text"));
|
||||
}
|
||||
Ok(text.into_owned())
|
||||
}
|
||||
|
||||
fn parse_url(value: &str) -> Result<Url, FetchError> {
|
||||
let url = Url::parse(value).map_err(|error| failure(format!("invalid URL: {error}")))?;
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return Err(failure("URL must use http or https"));
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err(failure("URL credentials are not allowed"));
|
||||
}
|
||||
if url.host_str().is_none() {
|
||||
return Err(failure("URL is missing a host"));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn is_public(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(ip) => public_v4(ip),
|
||||
IpAddr::V6(ip) => public_v6(ip),
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_resolution(ip: IpAddr, domain: bool) -> bool {
|
||||
is_public(ip) || (domain && is_benchmark_proxy_range(ip))
|
||||
}
|
||||
|
||||
fn is_benchmark_proxy_range(ip: IpAddr) -> bool {
|
||||
let IpAddr::V4(ip) = ip else {
|
||||
return false;
|
||||
};
|
||||
u32::from(ip) >> 17 == u32::from(Ipv4Addr::new(198, 18, 0, 0)) >> 17
|
||||
}
|
||||
|
||||
fn public_v4(ip: Ipv4Addr) -> bool {
|
||||
let value = u32::from(ip);
|
||||
![
|
||||
(0x0000_0000, 8),
|
||||
(0x0a00_0000, 8),
|
||||
(0x6440_0000, 10),
|
||||
(0x7f00_0000, 8),
|
||||
(0xa9fe_0000, 16),
|
||||
(0xac10_0000, 12),
|
||||
(0xc000_0000, 24),
|
||||
(0xc000_0200, 24),
|
||||
(0xc0a8_0000, 16),
|
||||
(0xc612_0000, 15),
|
||||
(0xc633_6400, 24),
|
||||
(0xcb00_7100, 24),
|
||||
(0xe000_0000, 3),
|
||||
]
|
||||
.into_iter()
|
||||
.any(|(network, prefix)| value >> (32 - prefix) == network >> (32 - prefix))
|
||||
}
|
||||
|
||||
fn public_v6(ip: Ipv6Addr) -> bool {
|
||||
let segments = ip.segments();
|
||||
segments[0] & 0xe000 == 0x2000 && !(segments[0] == 0x2001 && segments[1] == 0x0db8)
|
||||
}
|
||||
|
||||
fn failure(message: impl Into<String>) -> FetchError {
|
||||
FetchError(message.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
use axum::{
|
||||
http::{header, StatusCode},
|
||||
response::IntoResponse,
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
use super::{decode, is_public, safe_resolution, WebFetch, MAX_RESPONSE_SIZE};
|
||||
|
||||
#[tokio::test]
|
||||
async fn fetches_redirect_and_extracts_only_readable_markdown() {
|
||||
let base = fixture().await;
|
||||
let page = WebFetch::for_test()
|
||||
.fetch(&format!("{base}/redirect"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(page.url.ends_with("/article"));
|
||||
assert!(page.markdown.contains("# Useful article"));
|
||||
assert!(page.markdown.contains("Readable paragraph"));
|
||||
assert!(!page.markdown.contains("Site navigation"));
|
||||
assert!(!page.markdown.contains("window.secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_plain_text() {
|
||||
let base = fixture().await;
|
||||
let page = WebFetch::for_test()
|
||||
.fetch(&format!("{base}/plain"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(page.markdown, "plain response");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_oversized_and_binary_responses() {
|
||||
let base = fixture().await;
|
||||
let oversized = WebFetch::for_test()
|
||||
.fetch(&format!("{base}/oversized"))
|
||||
.await
|
||||
.unwrap_err();
|
||||
let binary = WebFetch::for_test()
|
||||
.fetch(&format!("{base}/binary"))
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(oversized.to_string().contains("5 MiB"));
|
||||
assert!(binary.to_string().contains("unsupported content type"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live public fetch smoke test"]
|
||||
async fn fetches_live_public_article() {
|
||||
let page = WebFetch::built_in()
|
||||
.fetch("https://www.rust-lang.org/learn")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
Url::parse(&page.url).unwrap().host_str(),
|
||||
Some("rust-lang.org")
|
||||
);
|
||||
assert!(page.markdown.contains("Learn Rust"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_globally_routable_addresses_are_public() {
|
||||
assert!(is_public(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1))));
|
||||
assert!(!is_public(IpAddr::V4(Ipv4Addr::LOCALHOST)));
|
||||
assert!(!is_public(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
|
||||
assert!(is_public(IpAddr::V6(
|
||||
"2606:4700:4700::1111".parse::<Ipv6Addr>().unwrap()
|
||||
)));
|
||||
assert!(!is_public(IpAddr::V6(Ipv6Addr::LOCALHOST)));
|
||||
assert!(!is_public(IpAddr::V6(
|
||||
"2001:db8::1".parse::<Ipv6Addr>().unwrap()
|
||||
)));
|
||||
let proxy_ip = IpAddr::V4(Ipv4Addr::new(198, 18, 1, 1));
|
||||
assert!(safe_resolution(proxy_ip, true));
|
||||
assert!(!safe_resolution(proxy_ip, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_case_insensitive_declared_charset() {
|
||||
assert_eq!(
|
||||
decode(&[0xe9], "text/plain; Charset=windows-1252").unwrap(),
|
||||
"é"
|
||||
);
|
||||
}
|
||||
|
||||
async fn fixture() -> String {
|
||||
async fn redirect() -> impl IntoResponse {
|
||||
(StatusCode::FOUND, [(header::LOCATION, "/article")])
|
||||
}
|
||||
async fn article() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
r#"<!doctype html><html><head><title>Useful article</title></head><body>
|
||||
<nav>Site navigation</nav><article><h1>Useful article</h1>
|
||||
<p>Readable paragraph with enough useful words to be selected as the main article content for this deterministic test fixture.</p>
|
||||
<p>A second meaningful paragraph makes article extraction stable and representative of a real web page.</p>
|
||||
</article><script>window.secret = true</script></body></html>"#,
|
||||
)
|
||||
}
|
||||
async fn oversized() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "text/plain")],
|
||||
"x".repeat(MAX_RESPONSE_SIZE + 1),
|
||||
)
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/redirect", get(redirect))
|
||||
.route("/article", get(article))
|
||||
.route("/plain", get(|| async { "plain response" }))
|
||||
.route("/oversized", get(oversized))
|
||||
.route(
|
||||
"/binary",
|
||||
get(|| async { ([(header::CONTENT_TYPE, "image/png")], [0_u8; 4]) }),
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{address}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
mod catalog;
|
||||
mod engine;
|
||||
mod federation;
|
||||
mod fetch;
|
||||
|
||||
pub use engine::{HtmlEngine, JsonEngine, SearchEngine, SearchHit};
|
||||
pub use federation::{SearchError, WebSearch};
|
||||
pub use fetch::{FetchError, FetchedPage, WebFetch};
|
||||
Reference in new issue
Block a user