spider 2.51.69

A web crawler and scraper, building blocks for data curation workloads.
Documentation
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! End-to-end integration tests that connect to a real Chrome instance and
//! verify that goto_with_html_once correctly injects HTML without deadlocking.
//!
//! Requires: Chrome running with --remote-debugging-port=9222
//! Run: CHROME_URL=ws://127.0.0.1:9222 cargo test -p spider --test chrome_intercept_e2e --features "chrome chrome_intercept smart"

#[cfg(feature = "chrome")]
mod e2e {
    use spider::tokio;
    use spider::website::Website;
    use std::time::Duration;

    /// Get the full devtools WS URL from a local Chrome instance.
    /// `Browser::connect_with_config` requires the full path (e.g.
    /// ws://host:port/devtools/browser/UUID), not just ws://host:port.
    async fn chrome_url() -> Option<String> {
        if std::net::TcpStream::connect("127.0.0.1:9222").is_err() {
            return None;
        }
        let resp = spider::reqwest::get("http://127.0.0.1:9222/json/version")
            .await
            .ok()?;
        let json: serde_json::Value = resp.json().await.ok()?;
        json["webSocketDebuggerUrl"].as_str().map(String::from)
    }

    /// Basic Chrome crawl without chrome_intercept features — the common path.
    #[tokio::test]
    async fn basic_chrome_crawl() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at port 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_limit(1)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(16);
        let collector = tokio::spawn(async move {
            let mut pages = vec![];
            while let Ok(page) = rx.recv().await {
                pages.push((page.get_url().to_string(), page.get_html().len()));
            }
            pages
        });

        let start = std::time::Instant::now();
        website.crawl().await;
        website.unsubscribe();
        let elapsed = start.elapsed();

        let pages = collector.await.unwrap();
        eprintln!("basic_chrome_crawl: {} pages in {:?}", pages.len(), elapsed);

        assert!(!pages.is_empty(), "Should have crawled at least 1 page");
        assert!(
            pages[0].1 > 100,
            "Page should have content ({} bytes)",
            pages[0].1
        );
        assert!(
            elapsed < Duration::from_secs(45),
            "Should not deadlock ({:?})",
            elapsed
        );
    }

    /// Chrome crawl with chrome_intercept — resource blocking active.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn chrome_intercept_crawl() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at port 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_limit(1)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(16);
        let collector = tokio::spawn(async move {
            let mut pages = vec![];
            while let Ok(page) = rx.recv().await {
                pages.push((page.get_url().to_string(), page.get_html().len()));
            }
            pages
        });

        let start = std::time::Instant::now();
        website.crawl().await;
        website.unsubscribe();
        let elapsed = start.elapsed();

        let pages = collector.await.unwrap();
        eprintln!(
            "chrome_intercept_crawl: {} pages in {:?}",
            pages.len(),
            elapsed
        );

        assert!(!pages.is_empty(), "Should have crawled at least 1 page");
        assert!(
            pages[0].1 > 100,
            "Page should have content ({} bytes)",
            pages[0].1
        );
        assert!(
            elapsed < Duration::from_secs(45),
            "Should not deadlock ({:?})",
            elapsed
        );
    }

    /// Multiple concurrent pages with chrome_intercept — most likely to trigger blocking.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn chrome_intercept_concurrent() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at port 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_depth(1)
            .with_limit(4)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(32);
        let collector = tokio::spawn(async move {
            let mut count = 0usize;
            while let Ok(_page) = rx.recv().await {
                count += 1;
            }
            count
        });

        let start = std::time::Instant::now();
        website.crawl().await;
        website.unsubscribe();
        let elapsed = start.elapsed();

        let count = collector.await.unwrap();
        eprintln!(
            "chrome_intercept_concurrent: {} pages in {:?}",
            count, elapsed
        );

        assert!(count >= 1, "Should have visited at least 1 page");
        assert!(
            elapsed < Duration::from_secs(60),
            "No deadlock ({:?})",
            elapsed
        );
    }

    /// Smart mode — HTTP first, Chrome upgrade for JS content.
    #[cfg(feature = "smart")]
    #[tokio::test]
    async fn smart_mode_crawl() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at port 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_limit(1)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(16);
        let collector = tokio::spawn(async move {
            let mut pages = vec![];
            while let Ok(page) = rx.recv().await {
                pages.push((page.get_url().to_string(), page.get_html().len()));
            }
            pages
        });

        let start = std::time::Instant::now();
        website.crawl_smart().await;
        website.unsubscribe();
        let elapsed = start.elapsed();

        let pages = collector.await.unwrap();
        eprintln!("smart_mode: {} pages in {:?}", pages.len(), elapsed);

        assert!(!pages.is_empty(), "Should have crawled at least 1 page");
        assert!(
            elapsed < Duration::from_secs(60),
            "No deadlock ({:?})",
            elapsed
        );
    }

    /// Verify the seeded content path (goto_with_html_once) doesn't deadlock.
    /// Crawl twice: first populates cache, second uses cached content.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn seeded_content_no_deadlock() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at port 9222");
            return;
        };

        // First crawl — populates pages
        let mut website1 = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.clone().into()))
            .with_limit(1)
            .with_caching(true)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx1 = website1.subscribe(16);
        let c1 = tokio::spawn(async move {
            let mut n = 0usize;
            while let Ok(_) = rx1.recv().await {
                n += 1;
            }
            n
        });

        website1.crawl().await;
        website1.unsubscribe();
        let n1 = c1.await.unwrap();
        eprintln!("seeded_content first crawl: {} pages", n1);

        // Second crawl — should use cached content (goto_with_html_once path)
        let mut website2 = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_limit(1)
            .with_caching(true)
            .with_request_timeout(Some(Duration::from_secs(30)))
            .build()
            .unwrap();

        let mut rx2 = website2.subscribe(16);
        let c2 = tokio::spawn(async move {
            let mut n = 0usize;
            while let Ok(_) = rx2.recv().await {
                n += 1;
            }
            n
        });

        let start = std::time::Instant::now();
        website2.crawl().await;
        website2.unsubscribe();
        let elapsed = start.elapsed();
        let n2 = c2.await.unwrap();

        eprintln!("seeded_content second crawl: {} pages in {:?}", n2, elapsed);
        assert!(
            elapsed < Duration::from_secs(45),
            "Second crawl (cached path) deadlocked: {:?}",
            elapsed
        );
    }

    /// High concurrency — 8 concurrent pages, depth 2.
    /// Tests that semaphore permits are returned, tabs are cleaned up,
    /// and the handler doesn't get overwhelmed.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn high_concurrency_no_deadlock() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_depth(2)
            .with_limit(8)
            .with_request_timeout(Some(Duration::from_secs(15)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(64);
        let collector = tokio::spawn(async move {
            let mut count = 0usize;
            while let Ok(_) = rx.recv().await {
                count += 1;
            }
            count
        });

        let start = std::time::Instant::now();
        website.crawl().await;
        website.unsubscribe();
        let elapsed = start.elapsed();
        let count = collector.await.unwrap();

        eprintln!("high_concurrency: {} pages in {:?}", count, elapsed);
        assert!(count >= 1, "Should crawl at least 1 page");
        assert!(
            elapsed < Duration::from_secs(60),
            "High concurrency crawl should not deadlock ({:?})",
            elapsed
        );
    }

    /// Rapid sequential crawls — reuse the same Chrome instance across
    /// multiple Website instances to test tab cleanup between crawls.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn sequential_crawls_no_accumulation() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at 9222");
            return;
        };

        for i in 0..3 {
            let mut website = Website::new("https://example.com")
                .with_chrome_connection(Some(ws.clone().into()))
                .with_limit(2)
                .with_depth(1)
                .with_request_timeout(Some(Duration::from_secs(15)))
                .build()
                .unwrap();

            let mut rx = website.subscribe(16);
            let collector = tokio::spawn(async move {
                let mut count = 0usize;
                while let Ok(_) = rx.recv().await {
                    count += 1;
                }
                count
            });

            let start = std::time::Instant::now();
            website.crawl().await;
            website.unsubscribe();
            let elapsed = start.elapsed();
            let count = collector.await.unwrap();

            eprintln!(
                "sequential crawl {}: {} pages in {:?}",
                i + 1,
                count,
                elapsed
            );
            assert!(
                elapsed < Duration::from_secs(30),
                "Sequential crawl {} should not degrade ({:?})",
                i + 1,
                elapsed
            );
        }
    }

    /// Budget exhaustion — set a small budget and verify the crawl
    /// completes without hanging when the budget is exceeded.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn budget_exhaustion_completes() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at 9222");
            return;
        };

        let mut budget = spider::hashbrown::HashMap::new();
        budget.insert("*", 1u32); // max 1 page total

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_depth(2)
            .with_limit(4)
            .with_budget(Some(budget))
            .with_request_timeout(Some(Duration::from_secs(15)))
            .build()
            .unwrap();

        let mut rx = website.subscribe(16);
        let collector = tokio::spawn(async move {
            let mut count = 0usize;
            while let Ok(_) = rx.recv().await {
                count += 1;
            }
            count
        });

        let start = std::time::Instant::now();
        website.crawl().await;
        website.unsubscribe();
        let elapsed = start.elapsed();
        let count = collector.await.unwrap();

        eprintln!("budget_exhaustion: {} pages in {:?}", count, elapsed);
        assert!(count <= 2, "Budget should limit pages (got {})", count);
        assert!(
            elapsed < Duration::from_secs(30),
            "Budget exhaustion should not hang ({:?})",
            elapsed
        );
    }

    /// Crawl with timeout — set a very short crawl timeout and verify
    /// it terminates promptly without hanging on cleanup.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn crawl_timeout_terminates() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_depth(3)
            .with_limit(10)
            .with_request_timeout(Some(Duration::from_secs(5)))
            .with_crawl_timeout(Some(Duration::from_secs(5)))
            .build()
            .unwrap();

        let start = std::time::Instant::now();
        website.crawl().await;
        let elapsed = start.elapsed();

        eprintln!("crawl_timeout: completed in {:?}", elapsed);
        assert!(
            elapsed < Duration::from_secs(30),
            "Crawl with 5s timeout should not hang on cleanup ({:?})",
            elapsed
        );
    }

    /// Drop subscriber mid-crawl — verify subscription_guard doesn't hang.
    #[cfg(feature = "chrome_intercept")]
    #[tokio::test]
    async fn dropped_subscriber_no_hang() {
        let Some(ws) = chrome_url().await else {
            eprintln!("SKIP: no Chrome at 9222");
            return;
        };

        let mut website = Website::new("https://example.com")
            .with_chrome_connection(Some(ws.into()))
            .with_limit(1)
            .with_request_timeout(Some(Duration::from_secs(15)))
            .build()
            .unwrap();

        // Subscribe then immediately drop the receiver
        let _rx = website.subscribe(16);
        drop(_rx);

        let start = std::time::Instant::now();
        website.crawl().await;
        let elapsed = start.elapsed();

        eprintln!("dropped_subscriber: completed in {:?}", elapsed);
        assert!(
            elapsed < Duration::from_secs(20),
            "Dropped subscriber should not cause hang ({:?})",
            elapsed
        );
    }
}