crw-renderer 0.13.4

HTTP and CDP browser rendering engine for the CRW web scraper
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
//! Per-host renderer preference learning.
//!
//! Tracks a sliding window of LightPanda failures per normalized host and
//! promotes the host to a heavier renderer (Chrome) when the failure rate
//! crosses a threshold. The cache is bounded by entry count and entries
//! expire on idle to keep memory predictable.
//!
//! ## Failure semantics
//!
//! Only LightPanda-specific failures count toward promotion (see
//! [`FailoverErrorKind::counts_for_promotion`]). Cloudflare challenges,
//! network errors, and "other" failures are recorded but do not drive
//! promotion — that's the strict-predicate guard from the plan review.
//!
//! ## Concurrency
//!
//! Each host's stats live behind a single `Mutex` to avoid TOCTOU races
//! between `record_failure` and `should_promote`. The cache itself is
//! `moka` async, lock-free for reads.

use crw_core::types::{FailoverErrorKind, RendererKind};
use moka::future::Cache;
use publicsuffix::{List, Psl};
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

/// Maximum number of failures we remember per host (sliding window cap).
const WINDOW_CAP: usize = 32;

/// Sliding window length — failures older than this are discarded.
const WINDOW_DURATION: Duration = Duration::from_secs(15 * 60);

/// Default cache capacity (number of distinct hosts tracked).
pub const DEFAULT_CAPACITY: u64 = 10_000;

/// Default idle TTL: hosts unused for this long are evicted.
pub const DEFAULT_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Failures within the sliding window required before promoting a host.
const PROMOTION_THRESHOLD: usize = 3;

#[derive(Debug)]
struct WindowEntry {
    at: Instant,
    /// Whether this failure counts toward promotion (strict predicate).
    counts: bool,
}

/// Per-host failure state. Single Mutex protects the entire view to avoid
/// races between observation and decision.
#[derive(Debug, Default)]
pub struct RendererStats {
    inner: Mutex<StatsInner>,
}

#[derive(Debug, Default)]
struct StatsInner {
    failures: VecDeque<WindowEntry>,
    /// Whether this host has already been promoted (latched until reset).
    promoted: bool,
}

impl RendererStats {
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a failure observed against this host. Returns `true` if this
    /// call caused a promotion transition (counter crossed the threshold).
    pub fn record_failure(&self, kind: &FailoverErrorKind) -> bool {
        let counts = kind.counts_for_promotion();
        let now = Instant::now();
        let mut inner = self.inner.lock().expect("RendererStats mutex poisoned");

        // Drop expired entries.
        while let Some(front) = inner.failures.front() {
            if now.duration_since(front.at) > WINDOW_DURATION {
                inner.failures.pop_front();
            } else {
                break;
            }
        }
        if inner.failures.len() >= WINDOW_CAP {
            inner.failures.pop_front();
        }
        inner.failures.push_back(WindowEntry { at: now, counts });

        if inner.promoted {
            return false;
        }
        let counting: usize = inner.failures.iter().filter(|e| e.counts).count();
        if counting >= PROMOTION_THRESHOLD {
            inner.promoted = true;
            true
        } else {
            false
        }
    }

    /// Record a successful render — clears the promotion latch and trims
    /// half the window so a recovered host can return to LightPanda.
    pub fn record_success(&self) {
        let mut inner = self.inner.lock().expect("RendererStats mutex poisoned");
        inner.promoted = false;
        let drop_n = inner.failures.len() / 2;
        for _ in 0..drop_n {
            inner.failures.pop_front();
        }
    }

    /// True if this host is currently promoted to a heavier renderer.
    pub fn is_promoted(&self) -> bool {
        self.inner
            .lock()
            .expect("RendererStats mutex poisoned")
            .promoted
    }
}

/// Per-host renderer preference cache. Cheap to clone (`Arc` inside).
#[derive(Clone)]
pub struct HostPreferences {
    cache: Cache<String, Arc<RendererStats>>,
}

impl HostPreferences {
    pub fn new(capacity: u64, ttl: Duration) -> Self {
        let cache = Cache::builder()
            .max_capacity(capacity)
            .time_to_idle(ttl)
            .build();
        Self { cache }
    }

    pub fn with_defaults() -> Self {
        Self::new(DEFAULT_CAPACITY, DEFAULT_TTL)
    }

    async fn stats_for(&self, host: &str) -> Arc<RendererStats> {
        let key = host.to_string();
        self.cache
            .get_with(key, async { Arc::new(RendererStats::new()) })
            .await
    }

    /// Record a failure for `host` (will be normalized). Returns the
    /// promotion target if this call promoted the host, else `None`.
    pub async fn record_failure(
        &self,
        host: &str,
        kind: &FailoverErrorKind,
    ) -> Option<RendererKind> {
        let normalized = normalize_host(host);
        let stats = self.stats_for(&normalized).await;
        if stats.record_failure(kind) {
            Some(RendererKind::Chrome)
        } else {
            None
        }
    }

    /// Record a successful render for `host` (will be normalized).
    pub async fn record_success(&self, host: &str) {
        let normalized = normalize_host(host);
        let stats = self.stats_for(&normalized).await;
        stats.record_success();
    }

    /// Returns the preferred renderer for `host` if a promotion is in
    /// effect, else `None` (caller falls back to default chain).
    pub async fn preferred(&self, host: &str) -> Option<RendererKind> {
        let normalized = normalize_host(host);
        let stats = self.cache.get(&normalized).await?;
        if stats.is_promoted() {
            Some(RendererKind::Chrome)
        } else {
            None
        }
    }

    /// Clear all preference state.
    pub async fn reset_all(&self) {
        self.cache.invalidate_all();
        self.cache.run_pending_tasks().await;
    }

    /// Clear preference state for a specific host (will be normalized).
    pub async fn reset_host(&self, host: &str) {
        let normalized = normalize_host(host);
        self.cache.invalidate(&normalized).await;
    }

    /// Current cache size (approximate).
    pub fn size(&self) -> u64 {
        self.cache.entry_count()
    }
}

impl Default for HostPreferences {
    fn default() -> Self {
        Self::with_defaults()
    }
}

// ── Host normalization ────────────────────────────────────────────────

static PSL: OnceLock<List> = OnceLock::new();

fn psl() -> &'static List {
    PSL.get_or_init(|| {
        // Embedded snapshot ships with publicsuffix.
        include_str!("public_suffix_list.dat")
            .parse()
            .expect("embedded PSL must parse")
    })
}

/// Normalize a host for cache keying:
/// - lowercase, trim
/// - strip a single leading `www.`
/// - strip a trailing `.` (FQDN root) so `example.com.` and `example.com`
///   share a cache entry
/// - if the host parses as an IP literal (v4 or v6), return it raw — PSL
///   does not understand IPs and would otherwise collapse `127.0.0.1`
///   into `0.1`, colliding with every other `*.0.1` host
/// - otherwise collapse to the registrable domain (eTLD+1) using the
///   public suffix list
///
/// Multi-tenant hosts under a public suffix (e.g. `foo.myshopify.com`,
/// `foo.vercel.app`) keep their tenant label because the suffix itself
/// is `myshopify.com` / `vercel.app` — eTLD+1 ends up being the tenant.
pub fn normalize_host(input: &str) -> String {
    let lower = input.trim().trim_end_matches('.').to_ascii_lowercase();
    let trimmed = lower.strip_prefix("www.").unwrap_or(&lower);

    // IP literal? Bypass PSL — its eTLD+1 logic would corrupt the address.
    if trimmed.parse::<std::net::IpAddr>().is_ok() {
        return trimmed.to_string();
    }
    // Bracketed IPv6 (`[::1]`): strip brackets and parse.
    if let Some(stripped) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']'))
        && stripped.parse::<std::net::IpAddr>().is_ok()
    {
        return stripped.to_string();
    }

    let bytes = trimmed.as_bytes();
    match psl().domain(bytes) {
        Some(domain) => std::str::from_utf8(domain.as_bytes())
            .unwrap_or(trimmed)
            .to_string(),
        None => trimmed.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalizes_www_prefix() {
        assert_eq!(normalize_host("www.example.com"), "example.com");
    }

    #[test]
    fn keeps_shopify_tenant() {
        assert_eq!(normalize_host("foo.myshopify.com"), "foo.myshopify.com");
    }

    #[test]
    fn keeps_vercel_tenant() {
        assert_eq!(normalize_host("myapp.vercel.app"), "myapp.vercel.app");
    }

    #[test]
    fn collapses_subdomains_to_registrable() {
        assert_eq!(normalize_host("a.b.example.com"), "example.com");
    }

    #[test]
    fn handles_co_uk_etld() {
        assert_eq!(normalize_host("www.example.co.uk"), "example.co.uk");
    }

    #[test]
    fn case_insensitive() {
        assert_eq!(normalize_host("WWW.Example.COM"), "example.com");
    }

    #[test]
    fn ipv4_returns_raw() {
        assert_eq!(normalize_host("127.0.0.1"), "127.0.0.1");
        assert_eq!(normalize_host("192.168.0.1"), "192.168.0.1");
    }

    #[test]
    fn ipv4_distinct_addresses_distinct_keys() {
        // Pre-fix this collided into "0.1" via the PSL eTLD+1 logic.
        assert_ne!(normalize_host("127.0.0.1"), normalize_host("192.168.0.1"));
    }

    #[test]
    fn ipv6_bracketed_returns_unbracketed() {
        assert_eq!(normalize_host("[::1]"), "::1");
        assert_eq!(normalize_host("::1"), "::1");
    }

    #[test]
    fn trailing_dot_stripped() {
        assert_eq!(normalize_host("example.com."), "example.com");
        assert_eq!(
            normalize_host("example.com."),
            normalize_host("example.com")
        );
    }

    #[test]
    fn renderer_stats_promotes_on_threshold() {
        let stats = RendererStats::new();
        assert!(!stats.record_failure(&FailoverErrorKind::NextJsClientError));
        assert!(!stats.record_failure(&FailoverErrorKind::EmptyNextRoot));
        assert!(stats.record_failure(&FailoverErrorKind::LightpandaTimeout));
        assert!(stats.is_promoted());
    }

    #[test]
    fn renderer_stats_strict_predicate_excludes_cf() {
        let stats = RendererStats::new();
        for _ in 0..5 {
            stats.record_failure(&FailoverErrorKind::CloudflareChallenge);
        }
        assert!(!stats.is_promoted());
    }

    #[test]
    fn renderer_stats_success_clears_promotion() {
        let stats = RendererStats::new();
        for _ in 0..3 {
            stats.record_failure(&FailoverErrorKind::NextJsClientError);
        }
        assert!(stats.is_promoted());
        stats.record_success();
        assert!(!stats.is_promoted());
    }

    #[test]
    fn renderer_stats_window_capped() {
        let stats = RendererStats::new();
        for _ in 0..(WINDOW_CAP + 10) {
            stats.record_failure(&FailoverErrorKind::Other);
        }
        let inner = stats.inner.lock().unwrap();
        assert!(inner.failures.len() <= WINDOW_CAP);
    }

    #[tokio::test]
    async fn host_preferences_promotes_after_threshold() {
        let prefs = HostPreferences::with_defaults();
        for kind in [
            FailoverErrorKind::NextJsClientError,
            FailoverErrorKind::EmptyNextRoot,
        ] {
            assert_eq!(prefs.record_failure("example.com", &kind).await, None);
        }
        assert_eq!(
            prefs
                .record_failure("example.com", &FailoverErrorKind::LightpandaTimeout)
                .await,
            Some(RendererKind::Chrome)
        );
        assert_eq!(
            prefs.preferred("example.com").await,
            Some(RendererKind::Chrome)
        );
    }

    #[tokio::test]
    async fn host_preferences_normalize_collapses_subdomain() {
        let prefs = HostPreferences::with_defaults();
        for _ in 0..3 {
            prefs
                .record_failure("a.b.example.com", &FailoverErrorKind::NextJsClientError)
                .await;
        }
        assert_eq!(
            prefs.preferred("www.example.com").await,
            Some(RendererKind::Chrome)
        );
    }

    #[tokio::test]
    async fn host_preferences_reset_clears_state() {
        let prefs = HostPreferences::with_defaults();
        for _ in 0..3 {
            prefs
                .record_failure("example.com", &FailoverErrorKind::NextJsClientError)
                .await;
        }
        prefs.reset_all().await;
        assert_eq!(prefs.preferred("example.com").await, None);
    }
}