Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(crawler): port filterLinks to Rust (#1801)
Gergő Móricza4f4145f3297
diff --git a/.github/workflows/test-server-self-host.yml b/.github/workflows/test-server-self-host.ymlindex aff1167a7..c8d406bad 100644--- a/.github/workflows/test-server-self-host.yml+++ b/.github/workflows/test-server-self-host.yml@@ -82,6 +82,11 @@ jobs:cargo build --releasechmod +x target/release/libpdf_parser.soworking-directory: ./apps/api/sharedLibs/pdf-parser+ - name: Build crawler+ run: |+ cargo build --release+ chmod +x target/release/libcrawler.so+ working-directory: ./apps/api/sharedLibs/crawler- name: Set up SearXNGif: matrix.search == 'searxng'run: |diff --git a/.github/workflows/test-server.yml b/.github/workflows/test-server.ymlindex c30056257..6bfc91add 100644--- a/.github/workflows/test-server.yml+++ b/.github/workflows/test-server.yml@@ -97,6 +97,11 @@ jobs:cargo build --releasechmod +x target/release/libpdf_parser.soworking-directory: ./apps/api/sharedLibs/pdf-parser+ - name: Build crawler+ run: |+ cargo build --release+ chmod +x target/release/libcrawler.so+ working-directory: ./apps/api/sharedLibs/crawler- name: Start the applicationrun: npm run start:production > api.log 2>&1 &env:diff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex 2080e766e..69cb302ae 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -27,6 +27,7 @@ RUN cd /app/sharedLibs/go-html-to-md && \FROM rust:1-slim AS rust-baseCOPY sharedLibs/html-transformer /app/sharedLibs/html-transformerCOPY sharedLibs/pdf-parser /app/sharedLibs/pdf-parser+COPY sharedLibs/crawler /app/sharedLibs/crawler# Install Rust dependencies and build transformer libRUN cd /app/sharedLibs/html-transformer && \@@ -38,12 +39,18 @@ RUN cd /app/sharedLibs/pdf-parser && \cargo build --release && \chmod +x target/release/libpdf_parser.so+# Install Rust dependencies and build crawler lib+RUN cd /app/sharedLibs/crawler && \+ cargo build --release && \+ chmod +x target/release/libcrawler.so+FROM baseCOPY --from=build /app/dist /app/distCOPY --from=prod-deps /app/node_modules /app/node_modulesCOPY --from=go-base /app/sharedLibs/go-html-to-md/html-to-markdown.so /app/sharedLibs/go-html-to-md/html-to-markdown.soCOPY --from=rust-base /app/sharedLibs/html-transformer/target/release/libhtml_transformer.so /app/sharedLibs/html-transformer/target/release/libhtml_transformer.soCOPY --from=rust-base /app/sharedLibs/pdf-parser/target/release/libpdf_parser.so /app/sharedLibs/pdf-parser/target/release/libpdf_parser.so+COPY --from=rust-base /app/sharedLibs/crawler/target/release/libcrawler.so /app/sharedLibs/crawler/target/release/libcrawler.so# Install gitRUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*diff --git a/apps/api/sharedLibs/crawler/.gitignore b/apps/api/sharedLibs/crawler/.gitignorenew file mode 100644index 000000000..1de565933--- /dev/null+++ b/apps/api/sharedLibs/crawler/.gitignore@@ -0,0 +1 @@+target\ No newline at end of filediff --git a/apps/api/sharedLibs/crawler/Cargo.lock b/apps/api/sharedLibs/crawler/Cargo.locknew file mode 100644index 000000000..9b2af422e--- /dev/null+++ b/apps/api/sharedLibs/crawler/Cargo.lock@@ -0,0 +1,432 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aho-corasick"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"+dependencies = [+ "memchr",+]++[[package]]+name = "crawler"+version = "0.1.0"+dependencies = [+ "libc",+ "regex",+ "robotstxt",+ "serde",+ "serde_json",+ "url",+]++[[package]]+name = "displaydoc"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "form_urlencoded"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "icu_collections"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47"+dependencies = [+ "displaydoc",+ "potential_utf",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3"++[[package]]+name = "icu_properties"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "potential_utf",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632"++[[package]]+name = "icu_provider"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "stable_deref_trait",+ "tinystr",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "itoa"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"++[[package]]+name = "libc"+version = "0.2.174"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"++[[package]]+name = "litemap"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956"++[[package]]+name = "memchr"+version = "2.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"++[[package]]+name = "percent-encoding"+version = "2.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"++[[package]]+name = "potential_utf"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585"+dependencies = [+ "zerovec",+]++[[package]]+name = "proc-macro2"+version = "1.0.95"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.40"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "regex"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"++[[package]]+name = "robotstxt"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc52377db80e3fec3a2c748ca603b8b6cacdd34ff89ff4b742a635361d4b4a7"++[[package]]+name = "ryu"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"++[[package]]+name = "serde"+version = "1.0.219"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.219"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.140"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"+dependencies = [+ "itoa",+ "memchr",+ "ryu",+ "serde",+]++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "stable_deref_trait"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"++[[package]]+name = "syn"+version = "2.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tinystr"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "unicode-ident"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"++[[package]]+name = "url"+version = "2.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "writeable"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb"++[[package]]+name = "yoke"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc"+dependencies = [+ "serde",+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]diff --git a/apps/api/sharedLibs/crawler/Cargo.toml b/apps/api/sharedLibs/crawler/Cargo.tomlnew file mode 100644index 000000000..cbc4cb9f8--- /dev/null+++ b/apps/api/sharedLibs/crawler/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "crawler"+version = "0.1.0"+edition = "2024"++[dependencies]+libc = "0.2.0"+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"+url = "2.5.4"+regex = "1.11.1"+robotstxt = "0.3.0"++[lib]+crate-type = ["cdylib"]\ No newline at end of filediff --git a/apps/api/sharedLibs/crawler/src/lib.rs b/apps/api/sharedLibs/crawler/src/lib.rsnew file mode 100644index 000000000..3b304d95e--- /dev/null+++ b/apps/api/sharedLibs/crawler/src/lib.rs@@ -0,0 +1,173 @@+use std::collections::HashMap;+use serde::{Deserialize, Serialize};+use std::ffi::{CStr, CString};+use url::Url;+use regex::Regex;+use robotstxt::DefaultMatcher;++#[derive(Deserialize)]+struct FilterLinksCall {+ links: Vec<String>,+ limit: u32,+ max_depth: u32,+ base_url: String,+ initial_url: String,+ regex_on_full_url: bool,+ excludes: Vec<String>,+ includes: Vec<String>,+ allow_backward_crawling: bool,+ ignore_robots_txt: bool,+ robots_txt: String,+}++#[derive(Serialize)]+struct FilterLinksResult {+ links: Vec<String>,+ denial_reasons: HashMap<String, String>,+}++fn _is_file(url: &Url) -> bool {+ let file_extensions = vec![+ ".css",+ ".js",+ ".ico",+ ".svg",+ ".tiff",+ ".zip",+ ".exe",+ ".dmg",+ ".mp4",+ ".mp3",+ ".wav",+ ".pptx",+ ".xlsx",+ ".avi",+ ".flv",+ ".woff",+ ".ttf",+ ".woff2",+ ".webp",+ ".inc",+ ];+ let url_without_query = url.path().to_lowercase();+ file_extensions.iter().any(|ext| url_without_query.ends_with(ext))+}++fn _get_url_depth(path: &str) -> u32 {+ path.split('/').filter(|x| *x != "" && *x != "index.php" && *x != "index.html").count() as u32+}++fn _filter_links(data: FilterLinksCall) -> Result<FilterLinksResult, Box<dyn std::error::Error>> {+ let mut denial_reasons = HashMap::new();+ let base_url = Url::parse(&data.base_url)?;+ let initial_url = Url::parse(&data.initial_url)?;++ let excludes_regex = data.excludes.iter().map(|exclude| Regex::new(exclude)).collect::<Vec<Result<Regex, regex::Error>>>();+ let excludes_regex = excludes_regex.into_iter().filter_map(|x| x.ok()).collect::<Vec<Regex>>();++ let includes_regex = data.includes.iter().map(|include| Regex::new(include)).collect::<Vec<Result<Regex, regex::Error>>>();+ let includes_regex = includes_regex.into_iter().filter_map(|x| x.ok()).collect::<Vec<Regex>>();++ let links = data.links.into_iter()+ .filter(|link| {+ let url = match base_url.join(link) {+ Ok(x) => x,+ Err(_) => {+ denial_reasons.insert(link.clone(), "URL_PARSE_ERROR".to_string());+ return false;+ }+ };++ let path = url.path();+ let depth = _get_url_depth(path);+ if depth > data.max_depth {+ denial_reasons.insert(link.clone(), "DEPTH_LIMIT".to_string());+ return false;+ }++ let exinc_path = if data.regex_on_full_url {+ url.as_str()+ } else {+ url.path()+ };++ if !excludes_regex.is_empty() && excludes_regex.iter().any(|regex| regex.is_match(exinc_path)) {+ denial_reasons.insert(link.clone(), "EXCLUDE_PATTERN".to_string());+ return false;+ }++ if !includes_regex.is_empty() && !includes_regex.iter().any(|regex| regex.is_match(exinc_path)) {+ denial_reasons.insert(link.clone(), "INCLUDE_PATTERN".to_string());+ return false;+ }++ if !data.allow_backward_crawling {+ if !url.path().starts_with(initial_url.path()) {+ denial_reasons.insert(link.clone(), "BACKWARD_CRAWLING".to_string());+ return false;+ }+ }++ if !data.ignore_robots_txt {+ let mut matcher = DefaultMatcher::default();+ let allowed = matcher.allowed_by_robots(&data.robots_txt, vec![+ "FireCrawlAgent",+ "FirecrawlAgent",+ ], url.as_str());++ if !allowed {+ denial_reasons.insert(link.clone(), "ROBOTS_TXT".to_string());+ return false;+ }+ }++ if _is_file(&url) {+ denial_reasons.insert(link.clone(), "FILE_TYPE".to_string());+ return false;+ }++ true+ })+ .take(data.limit as usize)+ .collect();++ Ok(FilterLinksResult {+ links,+ denial_reasons,+ })+}++#[unsafe(no_mangle)]+pub unsafe extern "C" fn filter_links(data: *const libc::c_char) -> *mut libc::c_char {+ let data = match serde_json::from_slice(unsafe { CStr::from_ptr(data).to_bytes() }) {+ Ok(x) => x,+ Err(_) => {+ return CString::new("RUSTFC:ERROR:Failed to parse input data as C string").unwrap().into_raw();+ }+ };++ let result = match _filter_links(data) {+ Ok(x) => x,+ Err(e) => {+ return CString::new(format!("RUSTFC:ERROR:{}", e)).unwrap().into_raw();+ }+ };++ let result = match serde_json::to_string(&result) {+ Ok(x) => x,+ Err(e) => {+ return CString::new(format!("RUSTFC:ERROR:Failed to serialize result as JSON {}", e)).unwrap().into_raw();+ }+ };++ CString::new(result).unwrap().into_raw()+}++/// Frees a string allocated in Rust-land.+///+/// # Safety+/// ptr must be a non-freed string pointer returned by Rust code.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn free_string(ptr: *mut libc::c_char) {+ drop(unsafe { CString::from_raw(ptr) })+}diff --git a/apps/api/src/lib/crawler.ts b/apps/api/src/lib/crawler.tsnew file mode 100644index 000000000..a0a93dc42--- /dev/null+++ b/apps/api/src/lib/crawler.ts@@ -0,0 +1,93 @@+import koffi, { KoffiFunction } from "koffi";+import { join } from "path";+import { stat } from "fs/promises";+import { platform } from "os";+import type { DenialReason } from "../scraper/WebScraper/crawler";++// TODO: add a timeout to the Rust transformer+const rustExecutablePath = join(+ process.cwd(),+ "sharedLibs/crawler/target/release/",+ platform() === "darwin" ? "libcrawler.dylib" : "libcrawler.so"+);++export type FilterLinksCall = {+ links: string[],+ limit: number,+ max_depth: number,+ base_url: string,+ initial_url: string,+ regex_on_full_url: boolean,+ excludes: string[],+ includes: string[],+ allow_backward_crawling: boolean,+ ignore_robots_txt: boolean,+ robots_txt: string,+}++export type FilterLinksResult = {+ links: string[],+ denial_reasons: Map<string, keyof typeof DenialReason>,+}++class RustCrawler {+ private static instance: RustCrawler;+ private _freeString: KoffiFunction;+ private _filterLinks: KoffiFunction;++ private constructor() {+ const lib = koffi.load(rustExecutablePath);+ this._freeString = lib.func("free_string", "void", ["string"]);+ const cstn = "CString:" + crypto.randomUUID();+ const freedResultString = koffi.disposable(cstn, "string", this._freeString);+ this._filterLinks = lib.func("filter_links", freedResultString, ["string"]);+ }++ public static async getInstance(): Promise<RustCrawler> {+ if (!RustCrawler.instance) {+ try {+ await stat(rustExecutablePath);+ } catch (_) {+ throw Error("Rust crawler shared library not found");+ }+ RustCrawler.instance = new RustCrawler();+ }+ return RustCrawler.instance;+ }++ public async filterLinks(call: FilterLinksCall): Promise<FilterLinksResult> {+ return new Promise<FilterLinksResult>((resolve, reject) => {+ this._filterLinks.async(JSON.stringify(call), (err: Error, res: string) => {+ if (err) {+ reject(err);+ } else {+ if (res.startsWith("RUSTFC:ERROR:")) {+ return reject(new Error(res.split("RUSTFC:ERROR:")[1]));+ }++ if (res === "RUSTFC:ERROR") {+ return reject(new Error("Something went wrong on the Rust side."));+ }++ try {+ const raw = JSON.parse(res);+ const result: FilterLinksResult = {+ links: raw.links,+ denial_reasons: new Map(Object.entries(raw.denial_reasons)),+ }+ resolve(result);+ } catch (e) {+ reject(e);+ }+ }+ });+ });+ }+}++export async function filterLinks(+ call: FilterLinksCall,+): Promise<FilterLinksResult> {+ const converter = await RustCrawler.getInstance();+ return await converter.filterLinks(call);+}diff --git a/apps/api/src/scraper/WebScraper/__tests__/crawler.test.ts b/apps/api/src/scraper/WebScraper/__tests__/crawler.test.tsindex 7f2598e15..ad5b12c60 100644--- a/apps/api/src/scraper/WebScraper/__tests__/crawler.test.ts+++ b/apps/api/src/scraper/WebScraper/__tests__/crawler.test.ts@@ -59,7 +59,7 @@ describe("WebCrawler", () => {initialUrl + "/page3",]);- const filteredLinks = crawler["filterLinks"](+ const filteredLinks = await crawler["filterLinks"]([initialUrl,initialUrl + "/page1",diff --git a/apps/api/src/scraper/WebScraper/crawler.ts b/apps/api/src/scraper/WebScraper/crawler.tsindex 29450766f..d5b52f8ec 100644--- a/apps/api/src/scraper/WebScraper/crawler.ts+++ b/apps/api/src/scraper/WebScraper/crawler.ts@@ -10,6 +10,7 @@ import https from "https";import { redisEvictConnection } from "../../services/redis";import { extractLinks } from "../../lib/html-transformer";import { TimeoutSignal } from "../../controllers/v1/types";+import { filterLinks } from "../../lib/crawler";export interface FilterResult {allowed: boolean;@@ -45,6 +46,7 @@ export class WebCrawler {private visited: Set<string> = new Set();private crawledUrls: Map<string, string> = new Map();private limit: number;+ private robotsTxt: string;private robotsTxtUrl: string;public robots: Robot;private robotsCrawlDelay: number | null = null;@@ -103,8 +105,9 @@ export class WebCrawler {this.includes = Array.isArray(includes) ? includes : [];this.excludes = Array.isArray(excludes) ? excludes : [];this.limit = limit;+ this.robotsTxt = "";this.robotsTxtUrl = `${this.baseUrl}${this.baseUrl.endsWith("/") ? "" : "/"}robots.txt`;- this.robots = robotsParser(this.robotsTxtUrl, "");+ this.robots = robotsParser(this.robotsTxtUrl, this.robotsTxt);// Deprecated, use limit insteadthis.maxCrawledLinks = maxCrawledLinks ?? limit;this.maxCrawledDepth = maxCrawledDepth ?? 10;@@ -120,12 +123,12 @@ export class WebCrawler {this.currentDiscoveryDepth = currentDiscoveryDepth ?? 0;}- public filterLinks(+ public async filterLinks(sitemapLinks: string[],limit: number,maxDepth: number,fromMap: boolean = false,- ): FilterLinksResult {+ ): Promise<FilterLinksResult> {const denialReasons = new Map<string, string>();if (this.currentDiscoveryDepth === this.maxDiscoveryDepth) {@@ -141,6 +144,37 @@ export class WebCrawler {return { links: sitemapLinks.slice(0, limit), denialReasons };}+ try {+ const res = await filterLinks({+ links: sitemapLinks,+ limit,+ max_depth: maxDepth,+ base_url: this.baseUrl,+ initial_url: this.initialUrl,+ regex_on_full_url: this.regexOnFullURL,+ excludes: this.excludes,+ includes: this.includes,+ allow_backward_crawling: this.allowBackwardCrawling,+ ignore_robots_txt: this.ignoreRobotsTxt,+ robots_txt: this.robotsTxt,+ });++ const fancyDenialReasons = new Map<string, string>();+ res.denial_reasons.forEach((value, key) => {+ fancyDenialReasons.set(key, DenialReason[value]);+ });++ return {+ links: res.links,+ denialReasons: fancyDenialReasons,+ };+ } catch (error) {+ this.logger.error("Error filtering links in Rust, falling back to JS", {+ error,+ method: "filterLinks",+ });+ }+const filteredLinks = sitemapLinks.filter((link) => {let url: URL;@@ -284,7 +318,8 @@ export class WebCrawler {}public importRobotsTxt(txt: string) {- this.robots = robotsParser(this.robotsTxtUrl, txt);+ this.robotsTxt = txt;+ this.robots = robotsParser(this.robotsTxtUrl, this.robotsTxt);const delay = this.robots.getCrawlDelay("FireCrawlAgent") || this.robots.getCrawlDelay("FirecrawlAgent");this.robotsCrawlDelay = delay !== undefined ? delay : null;}@@ -318,7 +353,7 @@ export class WebCrawler {if (fromMap && onlySitemap) {return await urlsHandler(urls);} else {- let filteredLinksResult = this.filterLinks(+ let filteredLinksResult = await this.filterLinks([...new Set(urls)].filter(x => this.filterURL(x, this.initialUrl).allowed),leftOfLimit,this.maxCrawledDepth,diff --git a/apps/api/src/services/queue-worker.ts b/apps/api/src/services/queue-worker.tsindex ce4b09475..8991973c4 100644--- a/apps/api/src/services/queue-worker.ts+++ b/apps/api/src/services/queue-worker.ts@@ -174,7 +174,7 @@ async function finishCrawlIfNeeded(job: Job & { id: string }, sc: StoredCrawl) {job.data.crawlerOptions,);- const univistedUrls = crawler.filterLinks(+ const univistedUrls = await crawler.filterLinks(Array.from(lastUrlsSet).filter((x) => !visitedUrls.has(x)),Infinity,sc.crawlerOptions.maxDepth ?? 10,@@ -861,7 +861,7 @@ async function kickoffGetIndexLinks(sc: StoredCrawl, crawler: WebCrawler, url: ssc.crawlerOptions.limit ?? 10000,);- const validIndexLinksResult = crawler.filterLinks(+ const validIndexLinksResult = await crawler.filterLinks(index.filter(x => crawler.filterURL(x, trimmedURL.href).allowed),sc.crawlerOptions.limit ?? 10000,sc.crawlerOptions.maxDepth ?? 10,@@ -1287,7 +1287,7 @@ async function processJob(job: Job & { id: string }, token: string) {job.data.crawlerOptions,);- const links = crawler.filterLinks(+ const links = await crawler.filterLinks(await crawler.extractLinksFromHTML(rawHtml ?? "",doc.metadata?.url ?? doc.metadata?.sourceURL ?? sc.originUrl!,@@ -1360,7 +1360,7 @@ async function processJob(job: Job & { id: string }, token: string) {// Only run check after adding new jobs for discovery - mogeryif (job.data.isCrawlSourceScrape) {- const filterResult = crawler.filterLinks(+ const filterResult = await crawler.filterLinks([doc.metadata.url ?? doc.metadata.sourceURL!],1,sc.crawlerOptions?.maxDepth ?? 10,