Skip to main content

html2pdf_api/service/
pdf.rs

1//! Core PDF generation service (framework-agnostic).
2//!
3//! This module contains the core PDF generation logic that is shared across
4//! all web framework integrations. The functions here are **synchronous/blocking**
5//! and should be called from within a blocking context (e.g., `tokio::task::spawn_blocking`,
6//! `actix_web::web::block`, etc.).
7//!
8//! # Architecture
9//!
10//! ```text
11//! ┌─────────────────────────────────────────────────────────────────┐
12//! │                    Framework Integration                        │
13//! │              (Actix-web / Rocket / Axum)                        │
14//! └─────────────────────────┬───────────────────────────────────────┘
15//!                           │ async context
16//!                           ▼
17//! ┌─────────────────────────────────────────────────────────────────┐
18//! │              spawn_blocking / web::block                        │
19//! └─────────────────────────┬───────────────────────────────────────┘
20//!                           │ blocking context
21//!                           ▼
22//! ┌─────────────────────────────────────────────────────────────────┐
23//! │                  This Module (pdf.rs)                           │
24//! │  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  │
25//! │  │generate_pdf_    │  │generate_pdf_    │  │get_pool_stats   │  │
26//! │  │from_url         │  │from_html        │  │                 │  │
27//! │  └────────┬────────┘  └────────┬────────┘  └─────────────────┘  │
28//! │           │                    │                                │
29//! │           └──────────┬─────────┘                                │
30//! │                      ▼                                          │
31//! │           ┌─────────────────────┐                               │
32//! │           │generate_pdf_internal│                               │
33//! │           └──────────┬──────────┘                               │
34//! └──────────────────────┼──────────────────────────────────────────┘
35//!                        │
36//!                        ▼
37//! ┌─────────────────────────────────────────────────────────────────┐
38//! │                    BrowserPool                                  │
39//! │                 (headless_chrome)                               │
40//! └─────────────────────────────────────────────────────────────────┘
41//! ```
42//!
43//! # Thread Safety
44//!
45//! All functions in this module are designed to be called from multiple threads
46//! concurrently. The browser pool is protected by a `Mutex`, and each PDF
47//! generation operation acquires a browser, uses it, and returns it to the pool
48//! automatically via RAII.
49//!
50//! # Blocking Behavior
51//!
52//! **Important:** These functions block the calling thread. In an async context,
53//! always wrap calls in a blocking task:
54//!
55//! ```rust,ignore
56//! // ✅ Correct: Using spawn_blocking
57//! let result = tokio::task::spawn_blocking(move || {
58//!     generate_pdf_from_url(&pool, &request)
59//! }).await?;
60//!
61//! // ❌ Wrong: Calling directly in async context
62//! // This will block the async runtime!
63//! let result = generate_pdf_from_url(&pool, &request);
64//! ```
65//!
66//! # Usage Examples
67//!
68//! ## Basic URL to PDF Conversion
69//!
70//! ```rust,ignore
71//! use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};
72//!
73//! // Assuming `pool` is a BrowserPool
74//! let request = PdfFromUrlRequest {
75//!     url: "https://example.com".to_string(),
76//!     ..Default::default()
77//! };
78//!
79//! // In a blocking context:
80//! let response = generate_pdf_from_url(&pool, &request)?;
81//! println!("Generated PDF: {} bytes", response.data.len());
82//! ```
83//!
84//! ## HTML to PDF Conversion
85//!
86//! ```rust,ignore
87//! use html2pdf_api::service::{generate_pdf_from_html, PdfFromHtmlRequest};
88//!
89//! let request = PdfFromHtmlRequest {
90//!     html: "<html><body><h1>Hello World</h1></body></html>".to_string(),
91//!     filename: Some("hello.pdf".to_string()),
92//!     ..Default::default()
93//! };
94//!
95//! let response = generate_pdf_from_html(&pool, &request)?;
96//! std::fs::write("hello.pdf", &response.data)?;
97//! ```
98//!
99//! ## With Async Web Framework
100//!
101//! ```rust,ignore
102//! use actix_web::{web, HttpResponse};
103//! use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};
104//!
105//! async fn handler(
106//!     pool: web::Data<SharedPool>,
107//!     query: web::Query<PdfFromUrlRequest>,
108//! ) -> HttpResponse {
109//!     let pool = pool.into_inner();
110//!     let request = query.into_inner();
111//!
112//!     let result = web::block(move || {
113//!         generate_pdf_from_url(&pool, &request)
114//!     }).await;
115//!
116//!     match result {
117//!         Ok(Ok(pdf)) => HttpResponse::Ok()
118//!             .content_type("application/pdf")
119//!             .body(pdf.data),
120//!         Ok(Err(e)) => HttpResponse::BadRequest().body(e.to_string()),
121//!         Err(e) => HttpResponse::InternalServerError().body(e.to_string()),
122//!     }
123//! }
124//! ```
125//!
126//! # Performance Considerations
127//!
128//! | Operation | Typical Duration | Notes |
129//! |-----------|------------------|-------|
130//! | Pool lock acquisition | < 1ms | Fast, non-blocking |
131//! | Browser checkout | < 1ms | If browser available |
132//! | Browser creation | 500ms - 2s | If pool needs to create new browser |
133//! | Page navigation | 100ms - 10s | Depends on target page |
134//! | JavaScript wait | 0 - 15s | Configurable via `waitsecs` |
135//! | PDF generation | 100ms - 5s | Depends on page complexity |
136//! | Tab cleanup | < 100ms | Best effort, non-blocking |
137//!
138//! # Error Handling
139//!
140//! All functions return `Result<T, PdfServiceError>`. Errors are categorized
141//! and include appropriate HTTP status codes. See [`PdfServiceError`] for
142//! the complete error taxonomy.
143//!
144//! [`PdfServiceError`]: crate::service::PdfServiceError
145
146use headless_chrome::types::PrintToPdfOptions;
147use std::time::{Duration, Instant};
148
149use crate::handle::BrowserHandle;
150use crate::pool::BrowserPool;
151use crate::service::types::*;
152
153// ============================================================================
154// Constants
155// ============================================================================
156
157/// Default timeout for the entire PDF generation operation in seconds.
158///
159/// This timeout encompasses the complete operation including:
160/// - Browser acquisition from pool
161/// - Page navigation
162/// - JavaScript execution wait
163/// - PDF rendering
164/// - Tab cleanup
165///
166/// If the operation exceeds this duration, a [`PdfServiceError::Timeout`]
167/// error is returned.
168///
169/// # Default Value
170///
171/// `60` seconds - sufficient for most web pages, including those with
172/// heavy JavaScript and external resources.
173///
174/// # Customization
175///
176/// This constant is used by framework integrations for their timeout wrappers.
177/// To customize, create your own timeout wrapper around the service functions.
178///
179/// ```rust,ignore
180/// use std::time::Duration;
181/// use tokio::time::timeout;
182///
183/// let custom_timeout = Duration::from_secs(120); // 2 minutes
184///
185/// let result = timeout(custom_timeout, async {
186///     tokio::task::spawn_blocking(move || {
187///         generate_pdf_from_url(&pool, &request)
188///     }).await
189/// }).await;
190/// ```
191pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
192
193/// Default wait time for JavaScript execution in seconds.
194///
195/// After page navigation completes, the service waits for JavaScript to finish
196/// rendering dynamic content. This constant defines the default wait time when
197/// not specified in the request.
198///
199/// # Behavior
200///
201/// During the wait period, the service polls every 200ms for `window.isPageDone === true`.
202/// If the page sets this flag, PDF generation proceeds immediately. Otherwise,
203/// the full wait duration elapses before generating the PDF.
204///
205/// # Default Value
206///
207/// `5` seconds - balances between allowing time for JavaScript execution
208/// and not waiting unnecessarily for simple pages.
209///
210/// # Recommendations
211///
212/// | Page Type | Recommended Wait |
213/// |-----------|------------------|
214/// | Static HTML | 1-2 seconds |
215/// | Light JavaScript (vanilla JS, jQuery) | 3-5 seconds |
216/// | Heavy SPA (React, Vue, Angular) | 5-10 seconds |
217/// | Complex visualizations (D3, charts) | 10-15 seconds |
218/// | Real-time data loading | 10-20 seconds |
219pub const DEFAULT_WAIT_SECS: u64 = 5;
220
221/// Polling interval for JavaScript completion check in milliseconds.
222///
223/// When waiting for JavaScript to complete, the service checks for
224/// `window.isPageDone === true` at this interval.
225///
226/// # Trade-offs
227///
228/// - **Shorter interval**: More responsive but higher CPU usage
229/// - **Longer interval**: Lower CPU usage but may overshoot ready state
230///
231/// # Default Value
232///
233/// `200` milliseconds - provides good responsiveness without excessive polling.
234const JS_POLL_INTERVAL_MS: u64 = 200;
235
236// ============================================================================
237// Public API - Core PDF Generation Functions
238// ============================================================================
239
240/// Generate a PDF from a URL.
241///
242/// Navigates to the specified URL using a browser from the pool, waits for
243/// JavaScript execution, and generates a PDF of the rendered page.
244///
245/// # Thread Safety
246///
247/// This function is thread-safe and can be called concurrently from multiple
248/// threads. The browser pool mutex ensures safe access to shared resources.
249///
250/// # Blocking Behavior
251///
252/// **This function blocks the calling thread.** In async contexts, wrap it
253/// in `tokio::task::spawn_blocking`, `actix_web::web::block`, or similar.
254///
255/// # Arguments
256///
257/// * `pool` - Reference to the browser pool. The pool uses fine-grained internal locks;\n///   browser checkout is fast (~1ms) and concurrent.
258/// * `request` - PDF generation parameters. See [`PdfFromUrlRequest`] for details.
259///
260/// # Returns
261///
262/// * `Ok(PdfResponse)` - Successfully generated PDF with binary data and metadata
263/// * `Err(PdfServiceError)` - Error with details about what went wrong
264///
265/// # Errors
266///
267/// | Error | Cause | Resolution |
268/// |-------|-------|------------|
269/// | [`InvalidUrl`] | URL is empty or malformed | Provide valid HTTP/HTTPS URL |
270/// | [`BrowserUnavailable`] | Pool exhausted | Retry or increase pool size |
271/// | [`TabCreationFailed`] | Browser issue | Automatic recovery |
272/// | [`NavigationFailed`] | URL unreachable | Check URL accessibility |
273/// | [`NavigationTimeout`] | Page too slow | Increase timeout or optimize page |
274/// | [`PdfGenerationFailed`] | Rendering issue | Simplify page or check content |
275///
276/// [`InvalidUrl`]: PdfServiceError::InvalidUrl
277/// [`BrowserUnavailable`]: PdfServiceError::BrowserUnavailable
278/// [`TabCreationFailed`]: PdfServiceError::TabCreationFailed
279/// [`NavigationFailed`]: PdfServiceError::NavigationFailed
280/// [`NavigationTimeout`]: PdfServiceError::NavigationTimeout
281/// [`PdfGenerationFailed`]: PdfServiceError::PdfGenerationFailed
282///
283/// # Examples
284///
285/// ## Basic Usage
286///
287/// ```rust,ignore
288/// use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};
289///
290/// let request = PdfFromUrlRequest {
291///     url: "https://example.com".to_string(),
292///     ..Default::default()
293/// };
294///
295/// let response = generate_pdf_from_url(&pool, &request)?;
296/// assert!(response.data.starts_with(b"%PDF-")); // Valid PDF header
297/// ```
298///
299/// ## With Custom Options
300///
301/// ```rust,ignore
302/// let request = PdfFromUrlRequest {
303///     url: "https://example.com/report".to_string(),
304///     filename: Some("quarterly-report.pdf".to_string()),
305///     landscape: Some(true),      // Wide tables
306///     waitsecs: Some(10),         // Complex charts
307///     download: Some(true),       // Force download
308///     print_background: Some(true),
309/// };
310///
311/// let response = generate_pdf_from_url(&pool, &request)?;
312/// println!("Generated {} with {} bytes", response.filename, response.size());
313/// ```
314///
315/// ## Error Handling
316///
317/// ```rust,ignore
318/// match generate_pdf_from_url(&pool, &request) {
319///     Ok(pdf) => {
320///         // Success - use pdf.data
321///     }
322///     Err(PdfServiceError::InvalidUrl(msg)) => {
323///         // Client error - return 400
324///         eprintln!("Bad URL: {}", msg);
325///     }
326///     Err(PdfServiceError::BrowserUnavailable(_)) => {
327///         // Transient error - retry
328///         std::thread::sleep(Duration::from_secs(1));
329///     }
330///     Err(e) => {
331///         // Other error
332///         eprintln!("PDF generation failed: {}", e);
333///     }
334/// }
335/// ```
336///
337/// # Performance
338///
339/// Typical execution time breakdown for a moderately complex page:
340///
341/// ```text
342/// ┌────────────────────────────────────────────────────────────────┐
343/// │ Browser checkout                                       ~1ms    │
344/// │ ├─────────────────────────────────────────────────────────────┤
345/// │ Tab creation                                          ~50ms   │
346/// │ ├─────────────────────────────────────────────────────────────┤
347/// │ Navigation + page load                                ~500ms  │
348/// │ ├─────────────────────────────────────────────────────────────┤
349/// │ JavaScript wait (configurable)                        ~5000ms │
350/// │ ├─────────────────────────────────────────────────────────────┤
351/// │ PDF rendering                                         ~200ms  │
352/// │ ├─────────────────────────────────────────────────────────────┤
353/// │ Tab cleanup                                           ~50ms   │
354/// └────────────────────────────────────────────────────────────────┘
355/// Total: ~5.8 seconds (dominated by JS wait)
356/// ```
357pub fn generate_pdf_from_url(
358    pool: &BrowserPool,
359    request: &PdfFromUrlRequest,
360) -> Result<PdfResponse, PdfServiceError> {
361    // Validate URL before acquiring browser
362    let url = validate_url(&request.url)?;
363
364    log::debug!(
365        "Generating PDF from URL: {} (landscape={}, wait={}s)",
366        url,
367        request.is_landscape(),
368        request.wait_duration().as_secs()
369    );
370
371    // Acquire browser from pool (lock held briefly)
372    let browser = acquire_browser(pool)?;
373
374    // Generate PDF (lock released, browser returned via RAII on completion/error)
375    let pdf_data = generate_pdf_internal(
376        &browser,
377        &url,
378        request.wait_duration(),
379        request.is_landscape(),
380        request.print_background(),
381    )?;
382
383    log::info!(
384        "✅ PDF generated successfully from URL: {} ({} bytes)",
385        url,
386        pdf_data.len()
387    );
388
389    Ok(PdfResponse::new(
390        pdf_data,
391        request.filename_or_default(),
392        request.is_download(),
393    ))
394}
395
396/// Generate a PDF from HTML content.
397///
398/// Loads the provided HTML content into a browser tab using a data URL,
399/// waits for any JavaScript execution, and generates a PDF.
400///
401/// # Thread Safety
402///
403/// This function is thread-safe and can be called concurrently from multiple
404/// threads. See [`generate_pdf_from_url`] for details.
405///
406/// # Blocking Behavior
407///
408/// **This function blocks the calling thread.** See [`generate_pdf_from_url`]
409/// for guidance on async usage.
410///
411/// # How It Works
412///
413/// The HTML content is converted to a data URL:
414///
415/// ```text
416/// data:text/html;charset=utf-8,<encoded-html-content>
417/// ```
418///
419/// This allows loading HTML directly without a web server. The browser
420/// renders the HTML as if it were loaded from a regular URL.
421///
422/// # Arguments
423///
424/// * `pool` - Reference to the mutex-wrapped browser pool
425/// * `request` - HTML content and generation parameters. See [`PdfFromHtmlRequest`].
426///
427/// # Returns
428///
429/// * `Ok(PdfResponse)` - Successfully generated PDF
430/// * `Err(PdfServiceError)` - Error details
431///
432/// # Errors
433///
434/// | Error | Cause | Resolution |
435/// |-------|-------|------------|
436/// | [`EmptyHtml`] | HTML content is empty/whitespace | Provide HTML content |
437/// | [`BrowserUnavailable`] | Pool exhausted | Retry or increase pool size |
438/// | [`NavigationFailed`] | HTML parsing issue | Check HTML validity |
439/// | [`PdfGenerationFailed`] | Rendering issue | Simplify HTML |
440///
441/// [`EmptyHtml`]: PdfServiceError::EmptyHtml
442/// [`BrowserUnavailable`]: PdfServiceError::BrowserUnavailable
443/// [`NavigationFailed`]: PdfServiceError::NavigationFailed
444/// [`PdfGenerationFailed`]: PdfServiceError::PdfGenerationFailed
445///
446/// # Limitations
447///
448/// ## External Resources
449///
450/// Since HTML is loaded via data URL, relative URLs don't work:
451///
452/// ```html
453/// <!-- ❌ Won't work - relative URL -->
454/// <img src="/images/logo.png">
455///
456/// <!-- ✅ Works - absolute URL -->
457/// <img src="https://example.com/images/logo.png">
458///
459/// <!-- ✅ Works - inline base64 -->
460/// <img src="data:image/png;base64,iVBORw0KGgo...">
461/// ```
462///
463/// ## Size Limits
464///
465/// Data URLs have browser-specific size limits. For very large HTML documents
466/// (> 1MB), consider:
467/// - Hosting the HTML on a temporary server
468/// - Using [`generate_pdf_from_url`] instead
469/// - Splitting into multiple PDFs
470///
471/// # Examples
472///
473/// ## Simple HTML
474///
475/// ```rust,ignore
476/// use html2pdf_api::service::{generate_pdf_from_html, PdfFromHtmlRequest};
477///
478/// let request = PdfFromHtmlRequest {
479///     html: "<h1>Hello World</h1><p>This is a test.</p>".to_string(),
480///     ..Default::default()
481/// };
482///
483/// let response = generate_pdf_from_html(&pool, &request)?;
484/// std::fs::write("output.pdf", &response.data)?;
485/// ```
486///
487/// ## Complete Document with Styling
488///
489/// ```rust,ignore
490/// let html = r#"
491/// <!DOCTYPE html>
492/// <html>
493/// <head>
494///     <meta charset="UTF-8">
495///     <style>
496///         body {
497///             font-family: 'Arial', sans-serif;
498///             margin: 40px;
499///             color: #333;
500///         }
501///         h1 {
502///             color: #0066cc;
503///             border-bottom: 2px solid #0066cc;
504///             padding-bottom: 10px;
505///         }
506///         table {
507///             width: 100%;
508///             border-collapse: collapse;
509///             margin-top: 20px;
510///         }
511///         th, td {
512///             border: 1px solid #ddd;
513///             padding: 12px;
514///             text-align: left;
515///         }
516///         th {
517///             background-color: #f5f5f5;
518///         }
519///     </style>
520/// </head>
521/// <body>
522///     <h1>Monthly Report</h1>
523///     <p>Generated on: 2024-01-15</p>
524///     <table>
525///         <tr><th>Metric</th><th>Value</th></tr>
526///         <tr><td>Revenue</td><td>$50,000</td></tr>
527///         <tr><td>Users</td><td>1,234</td></tr>
528///     </table>
529/// </body>
530/// </html>
531/// "#;
532///
533/// let request = PdfFromHtmlRequest {
534///     html: html.to_string(),
535///     filename: Some("monthly-report.pdf".to_string()),
536///     print_background: Some(true), // Include styled backgrounds
537///     ..Default::default()
538/// };
539///
540/// let response = generate_pdf_from_html(&pool, &request)?;
541/// ```
542///
543/// ## With Embedded Images
544///
545/// ```rust,ignore
546/// // Base64 encode an image
547/// let image_base64 = base64::encode(std::fs::read("logo.png")?);
548///
549/// let html = format!(r#"
550/// <!DOCTYPE html>
551/// <html>
552/// <body>
553///     <img src="data:image/png;base64,{}" alt="Logo">
554///     <h1>Company Report</h1>
555/// </body>
556/// </html>
557/// "#, image_base64);
558///
559/// let request = PdfFromHtmlRequest {
560///     html,
561///     ..Default::default()
562/// };
563///
564/// let response = generate_pdf_from_html(&pool, &request)?;
565/// ```
566pub fn generate_pdf_from_html(
567    pool: &BrowserPool,
568    request: &PdfFromHtmlRequest,
569) -> Result<PdfResponse, PdfServiceError> {
570    // Validate HTML content
571    if request.html.trim().is_empty() {
572        log::warn!("Empty HTML content provided");
573        return Err(PdfServiceError::EmptyHtml);
574    }
575
576    log::debug!(
577        "Generating PDF from HTML ({} bytes, landscape={}, wait={}s)",
578        request.html.len(),
579        request.is_landscape(),
580        request.wait_duration().as_secs()
581    );
582
583    // Acquire browser from pool
584    let browser = acquire_browser(pool)?;
585
586    // Convert HTML to data URL
587    // Using percent-encoding to handle special characters
588    let data_url = format!(
589        "data:text/html;charset=utf-8,{}",
590        urlencoding::encode(&request.html)
591    );
592
593    log::trace!("Data URL length: {} bytes", data_url.len());
594
595    // Generate PDF
596    let pdf_data = generate_pdf_internal(
597        &browser,
598        &data_url,
599        request.wait_duration(),
600        request.is_landscape(),
601        request.print_background(),
602    )?;
603
604    log::info!(
605        "✅ PDF generated successfully from HTML ({} bytes input → {} bytes output)",
606        request.html.len(),
607        pdf_data.len()
608    );
609
610    Ok(PdfResponse::new(
611        pdf_data,
612        request.filename_or_default(),
613        request.is_download(),
614    ))
615}
616
617/// Get current browser pool statistics.
618///
619/// Returns real-time metrics about the browser pool state including
620/// available browsers, active browsers, and total count.
621///
622/// # Thread Safety
623///
624/// This function briefly acquires the pool lock to read statistics.
625/// It's safe to call frequently for monitoring purposes.
626///
627/// # Blocking Behavior
628///
629/// This function is fast (< 1ms) as it reads from the pool's internal
630/// state. Safe to call frequently from health check endpoints.
631///
632/// # Arguments
633///
634/// * `pool` - Reference to the browser pool
635///
636/// # Returns
637///
638/// * `Ok(PoolStatsResponse)` - Current pool statistics
639///
640/// # Examples
641///
642/// ## Basic Usage
643///
644/// ```rust,ignore
645/// use html2pdf_api::service::get_pool_stats;
646///
647/// let stats = get_pool_stats(&pool)?;
648/// println!("Available: {}", stats.available);
649/// println!("Active: {}", stats.active);
650/// println!("Total: {}", stats.total);
651/// ```
652///
653/// ## Monitoring Integration
654///
655/// ```rust,ignore
656/// use prometheus::{Gauge, register_gauge};
657///
658/// lazy_static! {
659///     static ref POOL_AVAILABLE: Gauge = register_gauge!(
660///         "browser_pool_available",
661///         "Number of available browsers in pool"
662///     ).unwrap();
663///     static ref POOL_ACTIVE: Gauge = register_gauge!(
664///         "browser_pool_active",
665///         "Number of active browsers in pool"
666///     ).unwrap();
667/// }
668///
669/// fn update_metrics(pool: &Mutex<BrowserPool>) {
670///     if let Ok(stats) = get_pool_stats(pool) {
671///         POOL_AVAILABLE.set(stats.available as f64);
672///         POOL_ACTIVE.set(stats.active as f64);
673///     }
674/// }
675/// ```
676///
677/// ## Capacity Check
678///
679/// ```rust,ignore
680/// let stats = get_pool_stats(&pool)?;
681///
682/// if stats.available == 0 {
683///     log::warn!("No browsers available, requests may be delayed");
684/// }
685///
686/// let utilization = stats.active as f64 / stats.total.max(1) as f64;
687/// if utilization > 0.8 {
688///     log::warn!("Pool utilization at {:.0}%, consider scaling", utilization * 100.0);
689/// }
690/// ```
691pub fn get_pool_stats(pool: &BrowserPool) -> Result<PoolStatsResponse, PdfServiceError> {
692    let stats = pool.stats();
693
694    Ok(PoolStatsResponse {
695        available: stats.available,
696        active: stats.active,
697        total: stats.total,
698    })
699}
700
701/// Check if the browser pool is ready to handle requests.
702///
703/// Returns `true` if the pool has available browsers or capacity to create
704/// new ones. This is useful for readiness probes in container orchestration.
705///
706/// # Readiness Criteria
707///
708/// The pool is considered "ready" if either:
709/// - There are idle browsers available (`available > 0`), OR
710/// - There is capacity to create new browsers (`active < max_pool_size`)
711///
712/// The pool is "not ready" only when:
713/// - All browsers are in use AND the pool is at maximum capacity
714///
715/// # Arguments
716///
717/// * `pool` - Reference to the browser pool
718///
719/// # Returns
720///
721/// * `Ok(true)` - Pool can accept new requests
722/// * `Ok(false)` - Pool is at capacity, requests will queue
723///
724/// # Use Cases
725///
726/// ## Kubernetes Readiness Probe
727///
728/// ```yaml
729/// readinessProbe:
730///   httpGet:
731///     path: /ready
732///     port: 8080
733///   initialDelaySeconds: 5
734///   periodSeconds: 10
735/// ```
736///
737/// ## Load Balancer Health Check
738///
739/// When `is_pool_ready` returns `false`, the endpoint should return
740/// HTTP 503 Service Unavailable to remove the instance from rotation.
741///
742/// # Examples
743///
744/// ## Basic Check
745///
746/// ```rust,ignore
747/// use html2pdf_api::service::is_pool_ready;
748///
749/// if is_pool_ready(&pool)? {
750///     println!("Pool is ready to accept requests");
751/// } else {
752///     println!("Pool is at capacity");
753/// }
754/// ```
755///
756/// ## Request Gating
757///
758/// ```rust,ignore
759/// async fn handle_request(pool: &Mutex<BrowserPool>, request: PdfFromUrlRequest) -> Result<PdfResponse, Error> {
760///     // Quick capacity check before expensive operation
761///     if !is_pool_ready(pool)? {
762///         return Err(Error::ServiceUnavailable("Pool at capacity, try again later"));
763///     }
764///     
765///     // Proceed with PDF generation
766///     generate_pdf_from_url(pool, &request)
767/// }
768/// ```
769pub fn is_pool_ready(pool: &BrowserPool) -> Result<bool, PdfServiceError> {
770    let stats = pool.stats();
771    let config = pool.config();
772
773    // Ready if we have available browsers OR we can create more
774    let is_ready = stats.available > 0 || stats.active < config.max_pool_size;
775
776    log::trace!(
777        "Pool readiness check: available={}, active={}, max={}, ready={}",
778        stats.available,
779        stats.active,
780        config.max_pool_size,
781        is_ready
782    );
783
784    Ok(is_ready)
785}
786
787// ============================================================================
788// Internal Helper Functions
789// ============================================================================
790
791/// Validate and normalize a URL string.
792///
793/// Parses the URL using the `url` crate and returns the normalized form.
794/// This catches malformed URLs early, before acquiring a browser.
795///
796/// # Validation Rules
797///
798/// - URL must not be empty
799/// - URL must be parseable by the `url` crate
800/// - Scheme must be present (http/https/file/data)
801///
802/// # Arguments
803///
804/// * `url` - The URL string to validate
805///
806/// # Returns
807///
808/// * `Ok(String)` - The normalized URL
809/// * `Err(PdfServiceError::InvalidUrl)` - If validation fails
810///
811/// # Examples
812///
813/// ```rust,ignore
814/// assert!(validate_url("https://example.com").is_ok());
815/// assert!(validate_url("").is_err());
816/// assert!(validate_url("not-a-url").is_err());
817/// ```
818fn validate_url(url: &str) -> Result<String, PdfServiceError> {
819    // Check for empty URL first (better error message)
820    if url.trim().is_empty() {
821        log::debug!("URL validation failed: empty URL");
822        return Err(PdfServiceError::InvalidUrl("URL is required".to_string()));
823    }
824
825    // Parse and normalize the URL
826    match url::Url::parse(url) {
827        Ok(parsed) => {
828            log::trace!("URL validated successfully: {}", parsed);
829            Ok(parsed.to_string())
830        }
831        Err(e) => {
832            log::debug!("URL validation failed for '{}': {}", url, e);
833            Err(PdfServiceError::InvalidUrl(e.to_string()))
834        }
835    }
836}
837
838/// Acquire a browser from the pool.
839///
840/// Locks the pool mutex, retrieves a browser, and returns it. The lock is
841/// released immediately after checkout, not held during PDF generation.
842///
843/// # Browser Lifecycle
844///
845/// The returned `BrowserHandle` uses RAII to automatically return the
846/// browser to the pool when dropped:
847///
848/// ```text
849/// ┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
850/// │  acquire_browser │ ──▶ │  BrowserHandle  │ ──▶ │  PDF Generation │
851/// │  (lock, get)     │     │  (RAII guard)   │     │  (uses browser) │
852/// └─────────────────┘     └─────────────────┘     └────────┬────────┘
853///                                                          │
854///                                                          ▼
855///                         ┌─────────────────┐     ┌─────────────────┐
856///                         │  Back to Pool   │ ◀── │  Drop Handle    │
857///                         │  (automatic)    │     │  (RAII cleanup) │
858///                         └─────────────────┘     └─────────────────┘
859/// ```
860///
861/// # Arguments
862///
863/// * `pool` - Reference to the mutex-wrapped browser pool
864///
865/// # Returns
866///
867/// * `Ok(BrowserHandle)` - A browser ready for use
868/// * `Err(PdfServiceError)` - If pool lock or browser acquisition fails
869fn acquire_browser(pool: &BrowserPool) -> Result<BrowserHandle, PdfServiceError> {
870    // Get a browser from the pool (no outer lock needed — pool uses internal locks)
871    let browser = pool.get().map_err(|e| {
872        log::error!("❌ Failed to get browser from pool: {}", e);
873        PdfServiceError::BrowserUnavailable(e.to_string())
874    })?;
875
876    log::debug!("Acquired browser {} from pool", browser.id());
877
878    Ok(browser)
879}
880
881/// Core PDF generation logic.
882///
883/// This function performs the actual work of:
884/// 1. Creating a new browser tab
885/// 2. Navigating to the URL
886/// 3. Waiting for JavaScript completion
887/// 4. Generating the PDF
888/// 5. Cleaning up the tab
889///
890/// # Arguments
891///
892/// * `browser` - Browser handle from the pool
893/// * `url` - URL to navigate to (can be http/https or data: URL)
894/// * `wait_duration` - How long to wait for JavaScript
895/// * `landscape` - Whether to use landscape orientation
896/// * `print_background` - Whether to include background graphics
897///
898/// # Returns
899///
900/// * `Ok(Vec<u8>)` - The raw PDF binary data
901/// * `Err(PdfServiceError)` - If any step fails
902///
903/// # Tab Lifecycle
904///
905/// A new tab is created for each PDF generation and closed afterward.
906/// This ensures clean state and prevents memory leaks from accumulating
907/// page resources.
908///
909/// ```text
910/// Browser Instance
911/// ├── Tab 1 (new) ◀── Created for this request
912/// │   ├── Navigate to URL
913/// │   ├── Wait for JS
914/// │   ├── Generate PDF
915/// │   └── Close tab ◀── Cleanup
916/// └── (available for next request)
917/// ```
918fn generate_pdf_internal(
919    browser: &BrowserHandle,
920    url: &str,
921    wait_duration: Duration,
922    landscape: bool,
923    print_background: bool,
924) -> Result<Vec<u8>, PdfServiceError> {
925    let start_time = Instant::now();
926
927    // Create new tab
928    log::trace!("Creating new browser tab");
929    let tab = browser.new_tab().map_err(|e| {
930        log::error!("❌ Failed to create tab: {}", e);
931        PdfServiceError::TabCreationFailed(e.to_string())
932    })?;
933
934    // Configure PDF options
935    let print_options = build_print_options(landscape, print_background);
936
937    // Navigate to URL
938    log::trace!("Navigating to URL: {}", truncate_url(url, 100));
939    let nav_start = Instant::now();
940
941    let page = tab
942        .navigate_to(url)
943        .map_err(|e| {
944            log::error!("❌ Failed to navigate to URL: {}", e);
945            PdfServiceError::NavigationFailed(e.to_string())
946        })?
947        .wait_until_navigated()
948        .map_err(|e| {
949            log::error!("❌ Navigation timeout: {}", e);
950            PdfServiceError::NavigationTimeout(e.to_string())
951        })?;
952
953    log::debug!("Navigation completed in {:?}", nav_start.elapsed());
954
955    // Wait for JavaScript execution
956    wait_for_page_ready(&tab, wait_duration);
957
958    // Generate PDF
959    log::trace!("Generating PDF");
960    let pdf_start = Instant::now();
961
962    let pdf_data = page.print_to_pdf(print_options).map_err(|e| {
963        log::error!("❌ Failed to generate PDF: {}", e);
964        PdfServiceError::PdfGenerationFailed(e.to_string())
965    })?;
966
967    log::debug!(
968        "PDF generated in {:?} ({} bytes)",
969        pdf_start.elapsed(),
970        pdf_data.len()
971    );
972
973    // Close tab (best effort - don't fail if this doesn't work)
974    close_tab_safely(&tab);
975
976    log::debug!("Total PDF generation time: {:?}", start_time.elapsed());
977
978    Ok(pdf_data)
979}
980
981/// Build PDF print options.
982///
983/// Creates the `PrintToPdfOptions` struct with the specified settings
984/// and sensible defaults for margins and other options.
985///
986/// # Default Settings
987///
988/// - **Margins**: All set to 0 (full page)
989/// - **Header/Footer**: Disabled
990/// - **Background**: Configurable (default: true)
991/// - **Scale**: 1.0 (100%)
992fn build_print_options(landscape: bool, print_background: bool) -> Option<PrintToPdfOptions> {
993    Some(PrintToPdfOptions {
994        landscape: Some(landscape),
995        display_header_footer: Some(false),
996        print_background: Some(print_background),
997        // Zero margins for full-page output
998        margin_top: Some(0.0),
999        margin_bottom: Some(0.0),
1000        margin_left: Some(0.0),
1001        margin_right: Some(0.0),
1002        // Use defaults for everything else
1003        ..Default::default()
1004    })
1005}
1006
1007/// Wait for the page to signal it's ready for PDF generation.
1008///
1009/// This function implements a polling loop that checks for `window.isPageDone === true`.
1010/// This allows JavaScript-heavy pages to signal when they've finished rendering,
1011/// enabling early PDF generation without waiting the full timeout.
1012///
1013/// # Behavior Summary
1014///
1015/// | Page State | Result |
1016/// |------------|--------|
1017/// | `window.isPageDone = true` | Returns **immediately** (early exit) |
1018/// | `window.isPageDone = false` | Waits **full duration** |
1019/// | `window.isPageDone` not defined | Waits **full duration** |
1020/// | JavaScript error during check | Waits **full duration** |
1021///
1022/// # Default Behavior (No Flag Set)
1023///
1024/// **Important:** If the page does not set `window.isPageDone = true`, this function
1025/// waits the **full `max_wait` duration** before returning. This is intentional -
1026/// it gives JavaScript-heavy pages time to render even without explicit signaling.
1027///
1028/// For example, with the default `waitsecs = 5`:
1029/// - A page **with** the flag set immediately: ~0ms wait
1030/// - A page **without** the flag: full 5000ms wait
1031///
1032/// # How It Works
1033///
1034/// ```text
1035/// ┌─────────────────────────────────────────────────────────────────┐
1036/// │                    wait_for_page_ready                          │
1037/// │                                                                 │
1038/// │   ┌─────────┐     ┌──────────────┐     ┌─────────────────────┐  │
1039/// │   │  Start  │────▶│ Check flag   │────▶│ window.isPageDone?  │  │
1040/// │   └─────────┘     └──────────────┘     └──────────┬──────────┘  │
1041/// │                                                   │             │
1042/// │                          ┌────────────────────────┼─────────┐   │
1043/// │                          │                        │         │   │
1044/// │                          ▼                        ▼         │   │
1045/// │                   ┌────────────┐           ┌───────────┐    │   │
1046/// │                   │   true     │           │  false /  │    │   │
1047/// │                   │ (ready!)   │           │ undefined │    │   │
1048/// │                   └─────┬──────┘           └─────┬─────┘    │   │
1049/// │                         │                        │          │   │
1050/// │                         ▼                        ▼          │   │
1051/// │                   ┌───────────┐           ┌───────────┐     │   │
1052/// │                   │  Return   │           │ Sleep     │     │   │
1053/// │                   │  early    │           │ 200ms     │─────┘   │
1054/// │                   └───────────┘           └───────────┘         │
1055/// │                                                  │              │
1056/// │                                                  ▼              │
1057/// │                                           ┌───────────┐         │
1058/// │                                           │ Timeout?  │         │
1059/// │                                           └─────┬─────┘         │
1060/// │                                                 │               │
1061/// │                                    ┌────────────┴────────────┐  │
1062/// │                                    ▼                         ▼  │
1063/// │                             ┌───────────┐              ┌──────┐ │
1064/// │                             │   Yes     │              │  No  │ │
1065/// │                             │ (proceed) │              │(loop)│ │
1066/// │                             └───────────┘              └──────┘ │
1067/// └─────────────────────────────────────────────────────────────────┘
1068/// ```
1069///
1070/// # Polling Timeline
1071///
1072/// The function polls every 200ms (see `JS_POLL_INTERVAL_MS`):
1073///
1074/// ```text
1075/// Time:   0ms    200ms   400ms   600ms   800ms  ...  5000ms
1076///          │       │       │       │       │           │
1077///          ▼       ▼       ▼       ▼       ▼           ▼
1078///        Poll    Poll    Poll    Poll    Poll  ...   Timeout
1079///          │       │       │       │       │           │
1080///          └───────┴───────┴───────┴───────┴───────────┤
1081///                                                      ▼
1082///                                              Proceed to PDF
1083///
1084/// If window.isPageDone = true at any poll → Exit immediately
1085/// ```
1086///
1087/// Each poll executes this JavaScript:
1088///
1089/// ```javascript
1090/// window.isPageDone === true  // Returns true, false, or undefined
1091/// ```
1092///
1093/// - `true` → Function returns immediately
1094/// - `false` / `undefined` / error → Continue polling until timeout
1095///
1096/// # Page-Side Implementation (Optional)
1097///
1098/// To enable early completion and avoid unnecessary waiting, add this to your
1099/// page's JavaScript **after** all content is rendered:
1100///
1101/// ```javascript
1102/// // Signal that the page is ready for PDF generation
1103/// window.isPageDone = true;
1104/// ```
1105///
1106/// ## Framework Examples
1107///
1108/// **React:**
1109/// ```javascript
1110/// useEffect(() => {
1111///     fetchData().then((result) => {
1112///         setData(result);
1113///         // Signal ready after state update and re-render
1114///         setTimeout(() => { window.isPageDone = true; }, 0);
1115///     });
1116/// }, []);
1117/// ```
1118///
1119/// **Vue:**
1120/// ```javascript
1121/// mounted() {
1122///     this.loadData().then(() => {
1123///         this.$nextTick(() => {
1124///             window.isPageDone = true;
1125///         });
1126///     });
1127/// }
1128/// ```
1129///
1130/// **Vanilla JavaScript:**
1131/// ```javascript
1132/// document.addEventListener('DOMContentLoaded', async () => {
1133///     await loadDynamicContent();
1134///     await renderCharts();
1135///     window.isPageDone = true;  // All done!
1136/// });
1137/// ```
1138///
1139/// # When to Increase `waitsecs`
1140///
1141/// If you cannot modify the target page to set `window.isPageDone`, increase
1142/// `waitsecs` based on the page complexity:
1143///
1144/// | Page Type | Recommended `waitsecs` |
1145/// |-----------|------------------------|
1146/// | Static HTML (no JS) | 1 |
1147/// | Light JS (form validation, simple DOM) | 2-3 |
1148/// | Moderate JS (API calls, dynamic content) | 5 (default) |
1149/// | Heavy SPA (React, Vue, Angular) | 5-10 |
1150/// | Complex visualizations (D3, charts, maps) | 10-15 |
1151/// | Pages loading external resources | 10-20 |
1152///
1153/// # Performance Optimization
1154///
1155/// For high-throughput scenarios, implementing `window.isPageDone` on your
1156/// pages can significantly improve performance:
1157///
1158/// ```text
1159/// Without flag (5s default wait):
1160///     Request 1: ████████████████████ 5.2s
1161///     Request 2: ████████████████████ 5.1s
1162///     Request 3: ████████████████████ 5.3s
1163///     Average: 5.2s per PDF
1164///
1165/// With flag (page ready in 800ms):
1166///     Request 1: ████ 0.9s
1167///     Request 2: ████ 0.8s
1168///     Request 3: ████ 0.9s
1169///     Average: 0.87s per PDF (6x faster!)
1170/// ```
1171///
1172/// # Arguments
1173///
1174/// * `tab` - The browser tab to check. Must have completed navigation.
1175/// * `max_wait` - Maximum time to wait before proceeding with PDF generation.
1176///   This is the upper bound; the function may return earlier if the page
1177///   signals readiness.
1178///
1179/// # Returns
1180///
1181/// This function returns `()` (unit). It either:
1182/// - Returns early when `window.isPageDone === true` is detected
1183/// - Returns after `max_wait` duration has elapsed (timeout)
1184///
1185/// In both cases, PDF generation proceeds afterward. This function never fails -
1186/// timeout is a normal completion path, not an error.
1187///
1188/// # Thread Blocking
1189///
1190/// This function blocks the calling thread with `std::thread::sleep()`.
1191/// Always call from within a blocking context (e.g., `spawn_blocking`).
1192///
1193/// # Example
1194///
1195/// ```rust,ignore
1196/// // Navigate to page first
1197/// let page = tab.navigate_to(url)?.wait_until_navigated()?;
1198///
1199/// // Wait up to 10 seconds for JavaScript
1200/// wait_for_page_ready(&tab, Duration::from_secs(10));
1201///
1202/// // Now generate PDF - page is either ready or we've waited long enough
1203/// let pdf_data = page.print_to_pdf(options)?;
1204/// ```
1205fn wait_for_page_ready(tab: &headless_chrome::Tab, max_wait: Duration) {
1206    let start = Instant::now();
1207    let poll_interval = Duration::from_millis(JS_POLL_INTERVAL_MS);
1208
1209    log::trace!(
1210        "Waiting up to {:?} for page to be ready (polling every {:?})",
1211        max_wait,
1212        poll_interval
1213    );
1214
1215    while start.elapsed() < max_wait {
1216        // Check if page signals completion
1217        let is_done = tab
1218            .evaluate("window.isPageDone === true", false)
1219            .map(|result| result.value.and_then(|v| v.as_bool()).unwrap_or(false))
1220            .unwrap_or(false);
1221
1222        if is_done {
1223            log::debug!("Page signaled ready after {:?}", start.elapsed());
1224            return;
1225        }
1226
1227        // Sleep before next poll
1228        std::thread::sleep(poll_interval);
1229    }
1230
1231    log::debug!(
1232        "Page wait completed after {:?} (timeout, proceeding anyway)",
1233        start.elapsed()
1234    );
1235}
1236
1237/// Safely close a browser tab, ignoring errors.
1238///
1239/// Tab cleanup is best-effort. If it fails, we log a warning but don't
1240/// propagate the error since the PDF generation already succeeded.
1241///
1242/// # Why Best-Effort?
1243///
1244/// - The PDF data is already captured
1245/// - Tab resources will be cleaned up when the browser is recycled
1246/// - Failing here would discard a valid PDF
1247/// - Some errors (e.g., browser already closed) are expected
1248///
1249/// # Arguments
1250///
1251/// * `tab` - The browser tab to close
1252fn close_tab_safely(tab: &headless_chrome::Tab) {
1253    log::trace!("Closing browser tab");
1254
1255    if let Err(e) = tab.close(true) {
1256        // Log but don't fail - PDF generation already succeeded
1257        log::warn!(
1258            "Failed to close tab (continuing anyway, resources will be cleaned up): {}",
1259            e
1260        );
1261    } else {
1262        log::trace!("Tab closed successfully");
1263    }
1264}
1265
1266/// Truncate a URL for logging purposes.
1267///
1268/// Data URLs can be extremely long (containing entire HTML documents).
1269/// This function truncates them for readable log output.
1270///
1271/// # Arguments
1272///
1273/// * `url` - The URL to truncate
1274/// * `max_len` - Maximum length before truncation
1275///
1276/// # Returns
1277///
1278/// The URL, truncated with "..." if longer than `max_len`.
1279fn truncate_url(url: &str, max_len: usize) -> String {
1280    if url.len() <= max_len {
1281        url.to_string()
1282    } else {
1283        format!("{}...", &url[..max_len])
1284    }
1285}
1286
1287// ============================================================================
1288// Unit Tests
1289// ============================================================================
1290
1291#[cfg(test)]
1292mod tests {
1293    use super::*;
1294
1295    // -------------------------------------------------------------------------
1296    // URL Validation Tests
1297    // -------------------------------------------------------------------------
1298
1299    #[test]
1300    fn test_validate_url_valid_https() {
1301        let result = validate_url("https://example.com");
1302        assert!(result.is_ok());
1303        assert_eq!(result.unwrap(), "https://example.com/");
1304    }
1305
1306    #[test]
1307    fn test_validate_url_valid_http() {
1308        let result = validate_url("http://example.com/path?query=value");
1309        assert!(result.is_ok());
1310    }
1311
1312    #[test]
1313    fn test_validate_url_valid_with_port() {
1314        let result = validate_url("http://localhost:3000/api");
1315        assert!(result.is_ok());
1316    }
1317
1318    #[test]
1319    fn test_validate_url_empty() {
1320        let result = validate_url("");
1321        assert!(matches!(result, Err(PdfServiceError::InvalidUrl(_))));
1322    }
1323
1324    #[test]
1325    fn test_validate_url_whitespace_only() {
1326        let result = validate_url("   ");
1327        assert!(matches!(result, Err(PdfServiceError::InvalidUrl(_))));
1328    }
1329
1330    #[test]
1331    fn test_validate_url_no_scheme() {
1332        let result = validate_url("example.com");
1333        assert!(matches!(result, Err(PdfServiceError::InvalidUrl(_))));
1334    }
1335
1336    #[test]
1337    fn test_validate_url_relative() {
1338        let result = validate_url("/path/to/page");
1339        assert!(matches!(result, Err(PdfServiceError::InvalidUrl(_))));
1340    }
1341
1342    #[test]
1343    fn test_validate_url_data_url() {
1344        let result = validate_url("data:text/html,<h1>Hello</h1>");
1345        assert!(result.is_ok());
1346    }
1347
1348    // -------------------------------------------------------------------------
1349    // Helper Function Tests
1350    // -------------------------------------------------------------------------
1351
1352    #[test]
1353    fn test_truncate_url_short() {
1354        let url = "https://example.com";
1355        assert_eq!(truncate_url(url, 50), url);
1356    }
1357
1358    #[test]
1359    fn test_truncate_url_long() {
1360        let url = "https://example.com/very/long/path/that/exceeds/the/maximum/length";
1361        let truncated = truncate_url(url, 30);
1362        assert_eq!(truncated.len(), 33); // 30 + "..."
1363        assert!(truncated.ends_with("..."));
1364    }
1365
1366    #[test]
1367    fn test_truncate_url_exact_length() {
1368        let url = "https://example.com";
1369        assert_eq!(truncate_url(url, url.len()), url);
1370    }
1371
1372    #[test]
1373    fn test_build_print_options_landscape() {
1374        let options = build_print_options(true, true).unwrap();
1375        assert_eq!(options.landscape, Some(true));
1376        assert_eq!(options.print_background, Some(true));
1377    }
1378
1379    #[test]
1380    fn test_build_print_options_portrait() {
1381        let options = build_print_options(false, false).unwrap();
1382        assert_eq!(options.landscape, Some(false));
1383        assert_eq!(options.print_background, Some(false));
1384    }
1385
1386    #[test]
1387    fn test_build_print_options_zero_margins() {
1388        let options = build_print_options(false, true).unwrap();
1389        assert_eq!(options.margin_top, Some(0.0));
1390        assert_eq!(options.margin_bottom, Some(0.0));
1391        assert_eq!(options.margin_left, Some(0.0));
1392        assert_eq!(options.margin_right, Some(0.0));
1393    }
1394
1395    #[test]
1396    fn test_build_print_options_no_header_footer() {
1397        let options = build_print_options(false, true).unwrap();
1398        assert_eq!(options.display_header_footer, Some(false));
1399    }
1400
1401    // -------------------------------------------------------------------------
1402    // Constants Tests
1403    // -------------------------------------------------------------------------
1404
1405    // -------------------------------------------------------------------------
1406
1407    #[test]
1408    #[allow(clippy::assertions_on_constants)]
1409    fn test_default_timeout_reasonable() {
1410        // Timeout should be at least 30 seconds for complex pages
1411        assert!(DEFAULT_TIMEOUT_SECS >= 30);
1412        // But not more than 5 minutes (would be too long)
1413        assert!(DEFAULT_TIMEOUT_SECS <= 300);
1414    }
1415
1416    #[test]
1417    #[allow(clippy::assertions_on_constants)]
1418    fn test_default_wait_reasonable() {
1419        // Wait should be at least 1 second for any JS
1420        assert!(DEFAULT_WAIT_SECS >= 1);
1421        // But not more than 30 seconds by default
1422        assert!(DEFAULT_WAIT_SECS <= 30);
1423    }
1424
1425    #[test]
1426    #[allow(clippy::assertions_on_constants)]
1427    fn test_poll_interval_reasonable() {
1428        // Poll interval should be at least 100ms (not too aggressive)
1429        assert!(JS_POLL_INTERVAL_MS >= 100);
1430        // But not more than 1 second (responsive enough)
1431        assert!(JS_POLL_INTERVAL_MS <= 1000);
1432    }
1433}