Module rocket

Module rocket 

Source
Expand description

Rocket framework integration.

This module provides helpers and pre-built handlers for using BrowserPool with Rocket. You can choose between using the pre-built handlers for quick setup, or writing custom handlers for full control.

§Quick Start

§Option 1: Pre-built Routes (Fastest Setup)

Use configure_routes to add all PDF endpoints with a single line:

use rocket::launch;
use html2pdf_api::prelude::*;

#[launch]
async fn rocket() -> _ {
    let pool = init_browser_pool().await
        .expect("Failed to initialize browser pool");

    rocket::build()
        .manage(pool)
        .configure(html2pdf_api::integrations::rocket::configure_routes)
}

This gives you the following endpoints:

MethodPathDescription
GET/pdf?url=...Convert URL to PDF
POST/pdf/htmlConvert HTML to PDF
GET/pool/statsPool statistics
GET/healthHealth check
GET/readyReadiness check

§Option 2: Mix Pre-built and Custom Handlers

Use individual pre-built handlers alongside your own:

use rocket::{get, launch, routes};
use html2pdf_api::prelude::*;
use html2pdf_api::integrations::rocket::{pdf_from_url, health_check};

#[get("/custom")]
fn my_custom_handler() -> &'static str {
    "Custom response"
}

#[launch]
async fn rocket() -> _ {
    let pool = init_browser_pool().await
        .expect("Failed to initialize browser pool");

    rocket::build()
        .manage(pool)
        .mount("/", routes![
            pdf_from_url,
            health_check,
            my_custom_handler
        ])
}

§Option 3: Custom Handlers with Service Functions

For full control, use the service functions directly:

use rocket::{get, http::Status, serde::json::Json, State};
use html2pdf_api::prelude::*;
use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};

#[get("/my-pdf?<url>")]
async fn my_pdf_handler(
    pool: &State<SharedBrowserPool>,
    url: String,
) -> Result<Vec<u8>, Status> {
    // Custom pre-processing: auth, rate limiting, logging, etc.
    log::info!("Custom handler: {}", url);

    let pool = pool.inner().clone();
    let request = PdfFromUrlRequest {
        url,
        filename: Some("custom.pdf".to_string()),
        ..Default::default()
    };

    // Call service in blocking context
    let result = tokio::task::spawn_blocking(move || {
        generate_pdf_from_url(&pool, &request)
    }).await;

    match result {
        Ok(Ok(pdf)) => {
            // Custom post-processing
            Ok(pdf.data)
        }
        Ok(Err(_)) => Err(Status::BadRequest),
        Err(_) => Err(Status::InternalServerError),
    }
}

§Option 4: Full Manual Control (Original Approach)

For complete control over browser operations:

use rocket::{get, http::Status, State};
use html2pdf_api::prelude::*;

#[get("/manual-pdf")]
fn manual_pdf_handler(
    pool: &State<SharedBrowserPool>,
) -> Result<Vec<u8>, Status> {
    let pool_guard = pool.lock()
        .map_err(|_| Status::InternalServerError)?;

    let browser = pool_guard.get()
        .map_err(|_| Status::ServiceUnavailable)?;

    let tab = browser.new_tab()
        .map_err(|_| Status::InternalServerError)?;
    tab.navigate_to("https://example.com")
        .map_err(|_| Status::BadGateway)?;
    tab.wait_until_navigated()
        .map_err(|_| Status::BadGateway)?;

    let pdf_data = tab.print_to_pdf(None)
        .map_err(|_| Status::InternalServerError)?;

    Ok(pdf_data)
}

§Setup

Add to your Cargo.toml:

[dependencies]
html2pdf-api = { version = "0.2", features = ["rocket-integration"] }
rocket = { version = "0.5", features = ["json"] }

§Graceful Shutdown

For proper cleanup, use Rocket’s shutdown fairing:

use rocket::{fairing::{Fairing, Info, Kind}, launch, Orbit, Rocket};
use html2pdf_api::prelude::*;
use std::sync::Arc;

struct ShutdownFairing {
    pool: SharedBrowserPool,
}

#[rocket::async_trait]
impl Fairing for ShutdownFairing {
    fn info(&self) -> Info {
        Info {
            name: "Browser Pool Shutdown",
            kind: Kind::Shutdown,
        }
    }

    async fn on_shutdown(&self, _rocket: &Rocket<Orbit>) {
        if let Ok(mut pool) = self.pool.lock() {
            pool.shutdown();
        }
    }
}

#[launch]
async fn rocket() -> _ {
    let pool = init_browser_pool().await
        .expect("Failed to initialize browser pool");

    let shutdown_pool = pool.clone();

    rocket::build()
        .manage(pool)
        .attach(ShutdownFairing { pool: shutdown_pool })
        .configure(html2pdf_api::integrations::rocket::configure_routes)
}

§API Reference

§Pre-built Handlers

HandlerMethodDefault PathDescription
pdf_from_urlGET/pdfConvert URL to PDF
pdf_from_htmlPOST/pdf/htmlConvert HTML to PDF
pool_statsGET/pool/statsPool statistics
health_checkGET/healthHealth check (always 200)
readiness_checkGET/readyReadiness check (checks pool)

§Type Aliases

TypeDescription
SharedPoolArc<Mutex<BrowserPool>> - for service functions
BrowserPoolState&State<SharedBrowserPool> - for handler parameters

§Helper Functions

FunctionDescription
configure_routesConfigure all pre-built routes
routes()Get all routes for manual mounting
create_pool_dataWrap SharedBrowserPool for Rocket managed state
create_pool_data_from_arcWrap Arc<Mutex<BrowserPool>> for managed state

§Extension Traits

TraitDescription
BrowserPoolRocketExtAdds into_rocket_data() to BrowserPool

Structs§

ErrorResponder
Error response wrapper for Rocket.
PdfFromUrlQuery
Query parameters for PDF from URL endpoint.
PdfResponder
PDF response wrapper for Rocket.

Traits§

BrowserPoolRocketExt
Extension trait for BrowserPool with Rocket helpers.

Functions§

configure_routes
Configure all PDF routes.
create_pool_data
Create Rocket managed state from an existing shared pool.
create_pool_data_from_arc
Create Rocket managed state from an Arc reference.
health_check
Health check endpoint.
pdf_from_html
Generate PDF from HTML content.
pdf_from_url
Generate PDF from a URL.
pool_stats
Get browser pool statistics.
readiness_check
Readiness check endpoint.
routes
Get all routes for manual mounting.

Type Aliases§

BrowserPoolState
Type alias for Rocket State wrapper around the shared pool.
HandlerResult
Result type for Rocket handlers.
SharedPool
Type alias for shared browser pool.