crawn 0.3.0

A utility for web crawling and scraping
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! **A utility for web crawling and scraping**
//!
//! ## Usage
//!
//! - Basic Crawling:                                                                                    
//! ```bash                                                                                              
//! crawn https://example.com                                                                            
//! ```                                                                                                  
//!
//! - With Logging:                                                                                      
//! ```bash                                                                                              
//! crawn -l crawler.log https://example.com                                                             
//! ```                                                                                                  
//!
//! - Verbose Mode (Log All Requests):                                                                   
//! ```bash                                                                                              
//! crawn -v https://example.com | bat --language json                                                   
//! ```                                                                                                  
//!
//! - Custom Depth Limit:                                                                                
//! ```bash                                                                                              
//! crawn -m 3 https://example.com | grep 'rust' | cat > output.ndjson                                   
//! ```                                                                                                  
//!
//! - Full HTML:                                                                                         
//! ```bash                                                                                              
//! crawn --include-content https://example.com | jq -s '.'                                              
//! ```                                                                                                  
//!
//! - Extracted text only:                                                                               
//! ```bash                                                                                              
//! crawn --include-text https://example.com | sed -i 's/[^\r]\n/\r\n/g' | jq -s '.' | cat > output.json
//! ```                                                                                                  
//!
//! ---
//!
//! ## Output Format
//!
//! Results are written as NDJSON (newline-delimited JSON):
//! ```json
//! {"URL": "https://example.com", "Title": "Example Domain", "Links": 12}
//! {"URL": "https://example.com/about", "Title": "About Us", "Links": 9}
//! {"URL": "https://example.com/contact", "Title": "Contact", "Links": 48}
//! ```
//!
//! - With `--include-text`:
//! ```json
//! {"URL": "https://example.com", "Title": "Example Domain", "Links": 27, "Text": "Example Domain\nThis domain is..."}
//! ```
//!
//! - With `--include-content`:
//! ```json
//! {"URL": "https://example.com", "Title": "Example Domain", "Links": 30, "Content": "<!DOCTYPE html>\n<html>..."}
//! ```
//!
//! ---
//!
//! ## How It Works
//!
//! 1. BFS Crawling:
//! - Starts at the seed URL (depth 0)
//! - Discovers links on each page
//! - Processes links level-by-level (breadth-first)
//! - Stops at max_depth (default: 3)
//! - Uses `tokio::task::spawn` and `tokio::task::spawn_blocking` for concurrent processing
//!
//! 2. Keyword Filtering:
//! - Extracts "keywords" from URL paths (sanitized, lowercased)
//! - Splits by /, -, _ (e.g., /rust-tutorials/async → ["rust", "tutorials", "async"])
//! - Filters stop words, numbers, short words (<3 chars)
//! - Matches candidate URLs against base keywords
//! - Result: Only crawls relevant pages, skips off-topic content
//!
//! 3. Rate Limiting:
//! - Random range between 300 - 600ms
//! - Prevents server overload and IP bans
//! - Configurable via code (not exposed as CLI flag yet)
//!
//! 4. Error Handling:
//! - Network errors: Logged as warnings, crawling continues
//! - HTTP 404/500: Skipped, logged as warnings
//! - Parse failures: Logged, returns empty JSON
//! - Fatal errors: Printed to stdout with full context chain
//!
//! ---
//!
//! ## Logging
//!
//! #### Log Levels:
//!
//! - **INFO** (verbose mode only): Request logs
//! - **WARN** (always): Recoverable errors (404, network timeouts)
//! - **FATAL** (always): Unrecoverable errors (invalid URL, disk full)
//!
//! #### Log Format:
//!
//! ```text
//! 2026-01-24 02:37:40.351 [INFO]: Sent request to URL: https://example.com
//!
//! 2026-01-24 02:37:41.123 [WARN]: Failed to fetch URL: https://example.com/broken-link
//! Cause: HTTP 404 Not Found
//! ```
//!
//! ---
//!
//! ## Examples
//!
//! - Crawl Documentation Site:
//! ```bash
//! crawn https://doc.rust-lang.org/book/ | cat output.ndjson
//! ```
//!
//! - Crawl with Logging to custom file:
//! ```bash
//! crawn -l crawler.log -v https://example.com | jq -s '.'
//! ```
//!
//! - Limit to 2 Levels Deep:
//! ```bash
//! crawn -m 2 https://example.com | cat > shallow.ndjson
//! ```
//!
//! ---
//!
//! ## Limitations
//!
//! - Same-domain only (no external links, by design)
//! - No JavaScript rendering (static HTML only)
//! - No authentication (public pages only)
//!
//! ---
//!
//! ## License
//!
//! crawn is licensed under the **MIT** license.

use std::sync::atomic::{AtomicU8, AtomicUsize};
use std::sync::{Arc, LazyLock};
use std::time::Duration;

use clap::Parser;
use owo_colors::OwoColorize;
use resext::ctx;
use tokio::io::{AsyncReadExt, stdin};
use tokio::sync::Mutex;

mod cli;
mod crawler;
mod error;
mod fetch;
mod output;
mod repo;

use crate::fetch::*;
use crawler::*;
pub use repo::*;
use scraper::{Html, Selector};
use url::Url;

use crate::error::{LOG_TIMESTAMP_FORMAT, Log, Res, ResErr, ResExt, flush_logger};
use crate::output::{flush_writer, write_output};

pub static ARGS: LazyLock<cli::Args> = LazyLock::new(cli::Args::parse);
static CRAWLED: LazyLock<Arc<AtomicUsize>> = LazyLock::new(|| Arc::new(AtomicUsize::new(0)));
static SUCCESSES: LazyLock<Arc<AtomicUsize>> = LazyLock::new(|| Arc::new(AtomicUsize::new(0)));

async fn run() -> Res<()> {
    let args = &*ARGS;
    let repo = Arc::new(Mutex::new(InMemoryRepo::default()));
    let client = Arc::new(CrawnClient::new()?);
    let curr_depth = Arc::new(AtomicU8::new(0));
    let pending = Arc::new(AtomicUsize::new(0));
    let crawled = Arc::clone(&*CRAWLED);
    let successes = Arc::clone(&*SUCCESSES);

    let mut url = String::new();
    if args.url.is_some() {
        url = unsafe { args.url.as_ref().unwrap_unchecked() }.to_string();
    } else {
        let bytes_read = stdin()
            .read_to_string(&mut url)
            .await
            .context("Failed to read base URL from Stdin")?;

        if bytes_read < 10 {
            return Err(ResErr::from_args(
                ctx!("Invalid input from Stdin: {}", &url),
                std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid Stdin data"),
            ));
        }

        while url.ends_with([' ', '\r', '\n', '\t']) {
            url.pop();
        }
    }

    let base = Url::parse(&url).context("Failed to parse base URL")?;

    let base_keywords = Arc::new(get_keywords(&base));

    let base_domain = Arc::new(base.domain().unwrap_or_default().to_owned());

    let selectors = Arc::new(Selectors {
        anchor: Selector::parse("a[href]").context(ctx!(
            "Failed to parse selector for HTML 'anchor' (link) tag: {}",
            "`<a href=\"URL\">`".yellow()
        ))?,

        title: Selector::parse("title").context(ctx!(
            "Failed to parse selector for HTML 'title' tag: {}",
            "`<title>`".yellow()
        ))?,

        body: if args.include_text {
            Some(Selector::parse("body").context(ctx!(
                "Failed to parse selector for HTML 'body' tag: {}",
                "`<body>`".yellow()
            ))?)
        } else {
            None
        },
    });

    crawled.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let content = fetch_url(&url, Arc::clone(&client))
        .await
        .context("Failed to fetch base URL")?;

    successes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

    if args.verbose {
        String::from("Fetched content from base URL").log().await?;
    }

    let doc = Html::parse_document(&content);

    let links = extract_links(&doc, Arc::new(base), &selectors.anchor);
    let mut link_count = 0usize;
    {
        let mut rp = repo.lock().await;
        rp.mark(url.clone())
            .await
            .context("Failed to mark base URL as visited")?;

        for link in links {
            let link = match_option!(link.log().await?);
            let link = match_option!(normalize_url(link).log().await?);

            match_option!(rp.add(link).await.log().await?);

            link_count += 1;
        }
        rp.add(String::from("M")).await?;
    }
    curr_depth.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

    let text = selectors
        .body
        .as_ref()
        .map(|body_selector| extract_text(&doc, body_selector));
    let title = extract_title(&doc, &selectors.title);

    let content = if args.include_content {
        Some(content)
    } else {
        None
    };

    write_output(url.clone(), title, link_count, text, content)
        .await
        .log()
        .await?;

    let task_count = if args.include_content || args.include_text {
        6
    } else {
        9
    };

    let mut tasks = Vec::new();
    for _ in 0..task_count {
        let repo = Arc::clone(&repo);
        let base_keywords = Arc::clone(&base_keywords);
        let base_domain = Arc::clone(&base_domain);
        let selectors = Arc::clone(&selectors);
        let client = Arc::clone(&client);
        let curr_depth = Arc::clone(&curr_depth);
        let pending = Arc::clone(&pending);
        let crawled = Arc::clone(&crawled);
        let successes = Arc::clone(&successes);

        let task: tokio::task::JoinHandle<Res<()>> = tokio::task::spawn(async move {
            loop {
                if curr_depth.load(std::sync::atomic::Ordering::SeqCst)
                    > args.max_depth.unwrap_or(4)
                {
                    break;
                }

                let work_item = {
                    let mut repo_guard = repo.lock().await;
                    repo_guard.pop().await.log().await?.unwrap_or(None)
                };

                match work_item {
                    None => {
                        if pending.load(std::sync::atomic::Ordering::SeqCst) > 0 {
                            tokio::time::sleep(Duration::from_millis(100)).await;
                        } else {
                            break;
                        }
                    }

                    Some(url) => {
                        if &url == "M" {
                            if pending.load(std::sync::atomic::Ordering::SeqCst) > 0 {
                                #[allow(clippy::unit_arg)]
                                repo.lock().await.kick(url).await.log().await?.unwrap_or({
                                    tokio::time::sleep(Duration::from_millis(100)).await;
                                });

                                tokio::time::sleep(Duration::from_millis(100)).await;
                            } else {
                                repo.lock()
                                    .await
                                    .add(url)
                                    .await
                                    .log()
                                    .await?
                                    .unwrap_or_default();

                                curr_depth.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            }
                        } else {
                            pending.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

                            let can_extract = curr_depth.load(std::sync::atomic::Ordering::SeqCst)
                                < args.max_depth.unwrap_or(4);

                            let other =
                                Url::parse(&url).context(ctx!("Failed to parse URL: {}", &url))?;

                            if should_crawl(
                                Arc::clone(&base_domain),
                                Arc::clone(&base_keywords),
                                &other,
                            ) {
                                crawled.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

                                let is_success = worker(
                                    Arc::clone(&repo),
                                    Arc::clone(&selectors),
                                    Arc::clone(&client),
                                    url,
                                    can_extract,
                                )
                                .await
                                .log()
                                .await?
                                .is_some();

                                if is_success {
                                    successes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                                }
                            }

                            pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                }
            }

            Ok(())
        });

        tasks.push(task);
    }

    for task in tasks {
        task.await.context("Failed to spawn concurrent worker")??;
    }

    flush_writer().await?;
    flush_logger().await
}

#[tokio::main]
async fn main() -> std::process::ExitCode {
    match run().await {
        Ok(_) => {
            eprintln!(
                "\n{} Crawled {} URLs with {} successes and {} failures",
                "Finished!".bright_green().bold(),
                CRAWLED
                    .load(std::sync::atomic::Ordering::Relaxed)
                    .bright_green()
                    .bold(),
                SUCCESSES
                    .load(std::sync::atomic::Ordering::Relaxed)
                    .bright_green()
                    .bold(),
                {
                    CRAWLED.fetch_sub(
                        SUCCESSES.load(std::sync::atomic::Ordering::Relaxed),
                        std::sync::atomic::Ordering::Relaxed,
                    );
                    let temp = CRAWLED
                        .load(std::sync::atomic::Ordering::Relaxed)
                        .to_string();
                    if &temp == "0" {
                        temp.bright_green().bold().to_string()
                    } else {
                        temp.red().bold().to_string()
                    }
                }
            );
            std::process::ExitCode::SUCCESS
        }
        Err(e) => {
            let timestamp: String = time::OffsetDateTime::now_utc()
                .to_offset(time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC))
                .format(&LOG_TIMESTAMP_FORMAT)
                .map_err(|_| String::from("Format Failure"))
                .context("Failed to format timestamp for log")
                .unwrap_or_else(|e| {
                    eprintln!("{}", e);
                    String::from("")
                });

            eprintln!("{} {}:\n{}", timestamp.yellow(), "[FATAL]".red().bold(), e);
            std::process::ExitCode::FAILURE
        }
    }
}