LINE1 10 20 30 40 50 60 70 80 90 100123456789101112131415161718192021222324use actix_web::{HttpResponse, http::StatusCode, web};2526use crate::pdf::{Extraction, Options, PdfError};272829pub async fn convert(options: web::Data<Options>, body: web::Bytes) -> HttpResponse {30 convert_with(options.get_ref().clone(), body).await31}32333435363738pub async fn convert_with(options: Options, body: web::Bytes) -> HttpResponse {39 40 if body.len() > options.max_bytes {41 return respond(Err(PdfError::TooLarge {42 size: body.len(),43 max: options.max_bytes,44 }));45 }46 let result = web::block(move || crate::pdf::extract_markdown(&body, &options)).await;47 match result {48 Ok(inner) => respond(inner),49 Err(error) => {50 log::error!("pdf extraction task failed: {error}");51 HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR).json(ErrorResponse {52 error: "pdf extraction failed".to_owned(),53 })54 }55 }56}575859#[derive(Debug, serde::Serialize)]60pub struct ExtractionResponse {61 pub markdown: String,62 pub page_count: u32,63 pub title: Option<String>,64 pub incomplete: bool,65 pub warnings: Vec<String>,66}6768impl From<Extraction> for ExtractionResponse {69 fn from(extraction: Extraction) -> Self {70 Self {71 markdown: extraction.markdown,72 page_count: extraction.page_count,73 title: extraction.title,74 incomplete: extraction.incomplete,75 warnings: extraction.warnings,76 }77 }78}7980#[derive(Debug, serde::Serialize)]81struct ErrorResponse {82 error: String,83}8485fn respond(result: Result<Extraction, PdfError>) -> HttpResponse {86 match result {87 Ok(extraction) => HttpResponse::Ok().json(ExtractionResponse::from(extraction)),88 Err(error) => {89 log::warn!("pdf rejected: {error}");90 let status = StatusCode::from_u16(error.status())91 .expect("PdfError::status is always a valid HTTP status");92 HttpResponse::build(status).json(ErrorResponse {93 error: error.to_string(),94 })95 }96 }97}9899100pub fn route(path: &'static str, config: &mut web::ServiceConfig) {101 route_with(path, &Options::default(), config);102}103104105106pub fn route_with(path: &'static str, options: &Options, config: &mut web::ServiceConfig) {107 config108 .app_data(web::Data::new(options.clone()))109 .app_data(web::PayloadConfig::new(options.max_bytes))110 .route(path, web::post().to(convert));111}112113#[cfg(test)]114mod tests {115 use super::*;116 use actix_web::{App, test};117118 #[tokio::test]119 async fn endpoint_converts_an_uploaded_pdf() {120 let app = test::init_service(App::new().configure(|config| {121 route_with("/v1/pdf_to_markdown", &Options::default(), config);122 }))123 .await;124 let request = test::TestRequest::post()125 .uri("/v1/pdf_to_markdown")126 .insert_header(("Content-Type", "application/pdf"))127 .set_payload(crate::pdf::tests::tiny_pdf(&["Hello decision engine"]))128 .to_request();129 let response = test::call_service(&app, request).await;130 assert_eq!(response.status(), StatusCode::OK);131 let body: serde_json::Value = test::read_body_json(response).await;132 assert_eq!(body["page_count"], 1);133 assert!(134 body["markdown"]135 .as_str()136 .is_some_and(|m| m.contains("Hello decision engine"))137 );138 }139140 #[tokio::test]141 async fn endpoint_rejects_garbage_with_a_bad_request() {142 let app = test::init_service(App::new().configure(|config| {143 route_with("/v1/pdf_to_markdown", &Options::default(), config);144 }))145 .await;146 let request = test::TestRequest::post()147 .uri("/v1/pdf_to_markdown")148 .set_payload(b"not a pdf".to_vec())149 .to_request();150 let response = test::call_service(&app, request).await;151 assert_eq!(response.status(), StatusCode::BAD_REQUEST);152 let body: serde_json::Value = test::read_body_json(response).await;153 assert!(body["error"].as_str().is_some());154 }155156 #[tokio::test]157 async fn endpoint_rejects_an_oversized_upload_with_413() {158 let options = Options {159 max_bytes: 64,160 ..Options::default()161 };162 let app = test::init_service(163 App::new().configure(|config| route_with("/v1/pdf_to_markdown", &options, config)),164 )165 .await;166 let request = test::TestRequest::post()167 .uri("/v1/pdf_to_markdown")168 .set_payload(crate::pdf::tests::tiny_pdf(&["Hello decision engine"]))169 .to_request();170 let response = test::call_service(&app, request).await;171 assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);172 }173}