| 1 | //! Shared PDF-to-text adapter. |
| 2 | //! |
| 3 | //! PDF parsing is intentionally delegated to the optional `pdftotext` |
| 4 | //! executable. Keeping the adapter here gives file and web tools one error |
| 5 | //! contract without carrying a second parser and font stack in Codewhale. |
| 6 | |
| 7 | use std::ffi::{OsStr, OsString}; |
| 8 | use std::fmt; |
| 9 | use std::io::Write; |
| 10 | #[cfg(test)] |
| 11 | use std::path::Path; |
| 12 | use std::path::PathBuf; |
| 13 | use std::process::Stdio; |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | use serde_json::json; |
| 17 | use tokio::io::{AsyncRead, AsyncReadExt}; |
| 18 | use tokio_util::sync::CancellationToken; |
| 19 | |
| 20 | use super::spec::ToolError; |
| 21 | |
| 22 | const PDF_TEXT_TIMEOUT: Duration = Duration::from_secs(30); |
| 23 | const PDF_PIPE_DRAIN_TIMEOUT: Duration = Duration::from_secs(1); |
| 24 | const MAX_PDF_STDOUT_BYTES: usize = 16 * 1024 * 1024; |
| 25 | const MAX_PDF_STDERR_BYTES: usize = 32 * 1024; |
| 26 | |
| 27 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 28 | pub enum PdfTextError { |
| 29 | BinaryUnavailable, |
| 30 | Cancelled, |
| 31 | TimedOut, |
| 32 | Execution(String), |
| 33 | } |
| 34 | |
| 35 | impl fmt::Display for PdfTextError { |
| 36 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 37 | match self { |
| 38 | Self::BinaryUnavailable => formatter.write_str( |
| 39 | "PDF text extraction requires the optional `pdftotext` executable (Poppler)", |
| 40 | ), |
| 41 | Self::Cancelled => formatter.write_str("PDF text extraction was cancelled"), |
| 42 | Self::TimedOut => write!( |
| 43 | formatter, |
| 44 | "PDF text extraction timed out after {} seconds", |
| 45 | PDF_TEXT_TIMEOUT.as_secs() |
| 46 | ), |
| 47 | Self::Execution(message) => formatter.write_str(message), |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// One typed mapping shared by local-file and fetched-PDF consumers. |
| 53 | /// |
| 54 | /// The missing-binary message is deliberately a small JSON object. The |
| 55 | /// `NotAvailable` variant gives the runtime a failed terminal status while |
| 56 | /// callers that inspect the variant retain machine-readable recovery data. |
| 57 | pub(super) fn into_tool_error(error: PdfTextError) -> ToolError { |
| 58 | match error { |
| 59 | PdfTextError::BinaryUnavailable => ToolError::not_available( |
| 60 | json!({ |
| 61 | "type": "binary_unavailable", |
| 62 | "kind": "pdf", |
| 63 | "binary": "pdftotext", |
| 64 | "reason": "optional pdftotext executable is not installed", |
| 65 | "hint": "install Poppler and ensure pdftotext is on PATH" |
| 66 | }) |
| 67 | .to_string(), |
| 68 | ), |
| 69 | PdfTextError::Cancelled => ToolError::cancelled("PDF text extraction was cancelled"), |
| 70 | PdfTextError::TimedOut => ToolError::Timeout { |
| 71 | seconds: PDF_TEXT_TIMEOUT.as_secs(), |
| 72 | }, |
| 73 | PdfTextError::Execution(message) => ToolError::execution_failed(message), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | #[derive(Clone, Copy)] |
| 78 | pub struct PdfTextCommand<'a> { |
| 79 | binary: &'a OsStr, |
| 80 | timeout: Duration, |
| 81 | cancel: Option<&'a CancellationToken>, |
| 82 | context: Option<&'a super::spec::ToolContext>, |
| 83 | } |
| 84 | |
| 85 | impl<'a> PdfTextCommand<'a> { |
| 86 | pub(super) fn context(self) -> Option<&'a super::spec::ToolContext> { |
| 87 | self.context |
| 88 | } |
| 89 | pub(super) fn system(context: Option<&'a super::spec::ToolContext>) -> Self { |
| 90 | Self { |
| 91 | binary: OsStr::new("pdftotext"), |
| 92 | timeout: PDF_TEXT_TIMEOUT, |
| 93 | cancel: context.and_then(|context| context.cancel_token.as_ref()), |
| 94 | context, |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[cfg(test)] |
| 99 | pub(super) fn test( |
| 100 | binary: &'a OsStr, |
| 101 | timeout: Duration, |
| 102 | cancel: Option<&'a CancellationToken>, |
| 103 | ) -> Self { |
| 104 | Self { |
| 105 | binary, |
| 106 | timeout, |
| 107 | cancel, |
| 108 | context: None, |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[cfg(all(test, unix))] |
| 113 | pub(super) fn with_context(mut self, context: &'a super::spec::ToolContext) -> Self { |
| 114 | self.context = Some(context); |
| 115 | if self.cancel.is_none() { |
| 116 | self.cancel = context.cancel_token.as_ref(); |
| 117 | } |
| 118 | self |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[cfg(test)] |
| 123 | pub(super) async fn extract_path( |
| 124 | path: &Path, |
| 125 | page_range: Option<(u32, u32)>, |
| 126 | command: PdfTextCommand<'_>, |
| 127 | ) -> Result<String, PdfTextError> { |
| 128 | extract_captured( |
| 129 | CapturedPdf { |
| 130 | binary: command.binary.to_os_string(), |
| 131 | path: path.to_path_buf(), |
| 132 | page_range, |
| 133 | timeout: command.timeout, |
| 134 | _staged: None, |
| 135 | }, |
| 136 | command, |
| 137 | ) |
| 138 | .await |
| 139 | } |
| 140 | |
| 141 | pub(super) async fn extract_bytes( |
| 142 | bytes: &[u8], |
| 143 | page_range: Option<(u32, u32)>, |
| 144 | command: PdfTextCommand<'_>, |
| 145 | ) -> Result<String, PdfTextError> { |
| 146 | let owned = bytes.to_vec(); |
| 147 | let staged = tokio::task::spawn_blocking(move || { |
| 148 | let mut input = tempfile::NamedTempFile::new().map_err(|error| { |
| 149 | PdfTextError::Execution(format!("failed to stage fetched PDF: {error}")) |
| 150 | })?; |
| 151 | input.write_all(&owned).map_err(|error| { |
| 152 | PdfTextError::Execution(format!("failed to stage fetched PDF: {error}")) |
| 153 | })?; |
| 154 | input.flush().map_err(|error| { |
| 155 | PdfTextError::Execution(format!("failed to stage fetched PDF: {error}")) |
| 156 | })?; |
| 157 | Ok::<tempfile::TempPath, PdfTextError>(input.into_temp_path()) |
| 158 | }) |
| 159 | .await |
| 160 | .map_err(|error| PdfTextError::Execution(format!("failed to stage fetched PDF: {error}")))??; |
| 161 | let path = staged.to_path_buf(); |
| 162 | extract_captured( |
| 163 | CapturedPdf { |
| 164 | binary: command.binary.to_os_string(), |
| 165 | path, |
| 166 | page_range, |
| 167 | timeout: command.timeout, |
| 168 | _staged: Some(staged), |
| 169 | }, |
| 170 | command, |
| 171 | ) |
| 172 | .await |
| 173 | } |
| 174 | |
| 175 | /// Private admitted parser request. No command, path or staged PDF crosses IPC. |
| 176 | pub struct CapturedPdf { |
| 177 | pub binary: OsString, |
| 178 | pub path: PathBuf, |
| 179 | pub page_range: Option<(u32, u32)>, |
| 180 | pub timeout: Duration, |
| 181 | _staged: Option<tempfile::TempPath>, |
| 182 | } |
| 183 | impl CapturedPdf { |
| 184 | pub fn digest(&self) -> String { |
| 185 | let mut bytes = self.binary.as_encoded_bytes().to_vec(); |
| 186 | bytes.push(0); |
| 187 | bytes.extend_from_slice(self.path.as_os_str().as_encoded_bytes()); |
| 188 | bytes.push(0); |
| 189 | if let Some((start, end)) = self.page_range { |
| 190 | bytes.extend_from_slice(&start.to_le_bytes()); |
| 191 | bytes.extend_from_slice(&end.to_le_bytes()); |
| 192 | } |
| 193 | codewhale_runtime::hashing::sha256_hex(&bytes) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /// The existing bounded process result stays private in one Execution job. |
| 198 | pub struct PdfProcessOutcome { |
| 199 | output: Result<(BoundedOutput, BoundedOutput, std::process::ExitStatus), PdfTextError>, |
| 200 | } |
| 201 | impl PdfProcessOutcome { |
| 202 | pub fn projection(&self) -> serde_json::Value { |
| 203 | match &self.output { |
| 204 | Ok((stdout, stderr, status)) => json!({"kind":"pdf_process","state":"complete", |
| 205 | "success":status.success(),"exit_code":status.code(), |
| 206 | "stdout_truncated":stdout.truncated,"stderr":sanitized_text(&stderr.bytes), |
| 207 | "stderr_truncated":stderr.truncated}), |
| 208 | Err(error) => json!({"kind":"pdf_process","state":match error { |
| 209 | PdfTextError::BinaryUnavailable=>"binary_unavailable", PdfTextError::Cancelled=>"cancelled", |
| 210 | PdfTextError::TimedOut=>"timed_out", PdfTextError::Execution(_)=>"execution", |
| 211 | },"message":error.to_string()}), |
| 212 | } |
| 213 | } |
| 214 | fn into_rust_text(self) -> Result<String, PdfTextError> { |
| 215 | let (stdout, stderr, status) = self.output?; |
| 216 | if stdout.truncated { |
| 217 | return Err(PdfTextError::Execution(format!( |
| 218 | "pdftotext output exceeded the {} byte safety limit", |
| 219 | MAX_PDF_STDOUT_BYTES |
| 220 | ))); |
| 221 | } |
| 222 | if !status.success() { |
| 223 | let suffix = if stderr.truncated { " [truncated]" } else { "" }; |
| 224 | let stderr = sanitized_text(&stderr.bytes); |
| 225 | let stderr = if stderr.is_empty() { |
| 226 | "no diagnostic output".to_string() |
| 227 | } else { |
| 228 | stderr |
| 229 | }; |
| 230 | return Err(PdfTextError::Execution(format!( |
| 231 | "pdftotext failed (exit {:?}): {stderr}{suffix}", |
| 232 | status.code() |
| 233 | ))); |
| 234 | } |
| 235 | Ok(String::from_utf8_lossy(&stdout.bytes).into_owned()) |
| 236 | } |
| 237 | fn into_host_text(self, result: super::spec::ToolResult) -> Result<String, PdfTextError> { |
| 238 | #[derive(serde::Deserialize)] |
| 239 | #[serde(deny_unknown_fields)] |
| 240 | struct Decision { |
| 241 | kind: String, |
| 242 | code: String, |
| 243 | message: Option<String>, |
| 244 | } |
| 245 | let invalid = || { |
| 246 | PdfTextError::Execution("PDF host returned a malformed or inconsistent decision; no Rust fallback was attempted".into()) |
| 247 | }; |
| 248 | if !result.success { |
| 249 | return Err(invalid()); |
| 250 | } |
| 251 | let decision: Decision = |
| 252 | serde_json::from_value(result.metadata.ok_or_else(invalid)?).map_err(|_| invalid())?; |
| 253 | if decision.kind != "pdf_decision" { |
| 254 | return Err(invalid()); |
| 255 | } |
| 256 | match self.output { |
| 257 | // Cancellation/unavailability keep their real typed terminal status. |
| 258 | Err(error) => { |
| 259 | let code = match &error { |
| 260 | PdfTextError::BinaryUnavailable => "binary_unavailable", |
| 261 | PdfTextError::Cancelled => "cancelled", |
| 262 | PdfTextError::TimedOut => "timed_out", |
| 263 | PdfTextError::Execution(_) => "execution", |
| 264 | }; |
| 265 | if decision.code != code { |
| 266 | return Err(invalid()); |
| 267 | } |
| 268 | Err(error) |
| 269 | } |
| 270 | Ok((stdout, _, status)) => match decision.code.as_str() { |
| 271 | // Mandatory data-loss/process-success guard remains Core-owned. |
| 272 | "success" |
| 273 | if !stdout.truncated && status.success() && decision.message.is_none() => |
| 274 | { |
| 275 | Ok(String::from_utf8_lossy(&stdout.bytes).into_owned()) |
| 276 | } |
| 277 | "execution" if stdout.truncated || !status.success() => Err( |
| 278 | PdfTextError::Execution(decision.message.ok_or_else(invalid)?), |
| 279 | ), |
| 280 | _ => Err(invalid()), |
| 281 | }, |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | async fn extract_captured( |
| 287 | input: CapturedPdf, |
| 288 | request: PdfTextCommand<'_>, |
| 289 | ) -> Result<String, PdfTextError> { |
| 290 | if request.cancel.is_some_and(CancellationToken::is_cancelled) { |
| 291 | return Err(PdfTextError::Cancelled); |
| 292 | } |
| 293 | if let Some(context) = request.context.filter(|context| { |
| 294 | context |
| 295 | .features |
| 296 | .enabled(codewhale_runtime::features::Feature::PdfHost) |
| 297 | }) { |
| 298 | // Capture the existing Core deadline before entering the broker. An |
| 299 | // expired job's final receipt check can beat its timeout response; the |
| 300 | // generic RPC error must not erase the real Core terminal outcome. |
| 301 | let deadline = context |
| 302 | .turn_deadline |
| 303 | .map(|deadline| deadline.min(tokio::time::Instant::now() + input.timeout)) |
| 304 | .unwrap_or_else(|| tokio::time::Instant::now() + input.timeout); |
| 305 | let result = crate::extension_host::manager() |
| 306 | .execute_pdf(input, context) |
| 307 | .await; |
| 308 | return match result { |
| 309 | Ok((outcome, decision)) => outcome.into_host_text(decision), |
| 310 | Err(error) => Err(host_terminal_error(error, deadline, request.cancel)), |
| 311 | }; |
| 312 | } |
| 313 | run_pdf_driver(input, request.cancel).await.into_rust_text() |
| 314 | } |
| 315 | |
| 316 | fn host_terminal_error( |
| 317 | error: ToolError, |
| 318 | deadline: tokio::time::Instant, |
| 319 | cancel: Option<&CancellationToken>, |
| 320 | ) -> PdfTextError { |
| 321 | if cancel.is_some_and(CancellationToken::is_cancelled) |
| 322 | || matches!(error, ToolError::Cancelled { .. }) |
| 323 | { |
| 324 | PdfTextError::Cancelled |
| 325 | } else if tokio::time::Instant::now() >= deadline || matches!(error, ToolError::Timeout { .. }) |
| 326 | { |
| 327 | PdfTextError::TimedOut |
| 328 | } else { |
| 329 | PdfTextError::Execution(format!( |
| 330 | "PDF host failed: {error}; no Rust fallback was attempted" |
| 331 | )) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// One actual process driver shared by default Rust and the admitted Host job. |
| 336 | /// Host only receives the small process projection; stdout stays in this result. |
| 337 | pub async fn run_pdf_driver( |
| 338 | input: CapturedPdf, |
| 339 | cancel: Option<&CancellationToken>, |
| 340 | ) -> PdfProcessOutcome { |
| 341 | let output = async { |
| 342 | if cancel.is_some_and(CancellationToken::is_cancelled) { return Err(PdfTextError::Cancelled); } |
| 343 | let mut command = tokio::process::Command::new(&input.binary); |
| 344 | codewhale_util::utils::suppress_tokio_console_window(&mut command); |
| 345 | command.arg("-layout"); |
| 346 | if let Some((start,end))=input.page_range { command.arg("-f").arg(start.to_string()).arg("-l").arg(end.to_string()); } |
| 347 | command.arg(&input.path).arg("-").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true); |
| 348 | codewhale_runtime::child_env::apply_to_tokio_command(&mut command,std::iter::empty::<(&str,&str)>()); |
| 349 | #[cfg(unix)] command.process_group(0); |
| 350 | let mut child = command.spawn().map_err(|error| if error.kind()==std::io::ErrorKind::NotFound { PdfTextError::BinaryUnavailable } else { PdfTextError::Execution(format!("failed to launch pdftotext: {error}")) })?; |
| 351 | let tree = codewhale_runtime::process_tree::ProcessTree::attach_tokio(&child).map_err(|error| PdfTextError::Execution(format!("failed to contain pdftotext: {error}")))?; |
| 352 | let stdout=child.stdout.take().ok_or_else(||PdfTextError::Execution("failed to capture pdftotext stdout".into()))?; |
| 353 | let stderr=child.stderr.take().ok_or_else(||PdfTextError::Execution("failed to capture pdftotext stderr".into()))?; |
| 354 | let stdout_task=tokio::spawn(read_bounded(stdout,MAX_PDF_STDOUT_BYTES)); |
| 355 | let stderr_task=tokio::spawn(read_bounded(stderr,MAX_PDF_STDERR_BYTES)); |
| 356 | let status = tokio::select! { |
| 357 | biased; |
| 358 | ()=wait_for_cancellation(cancel)=>{ |
| 359 | let _=tree.kill(); terminate_child(&mut child).await; |
| 360 | finish_capture_tasks(stdout_task,stderr_task).await?; return Err(PdfTextError::Cancelled); |
| 361 | } |
| 362 | ()=tokio::time::sleep(input.timeout)=>{ |
| 363 | let _=tree.kill(); terminate_child(&mut child).await; |
| 364 | finish_capture_tasks(stdout_task,stderr_task).await?; return Err(PdfTextError::TimedOut); |
| 365 | } |
| 366 | status=child.wait()=>status.map_err(|error|PdfTextError::Execution(format!("failed to wait for pdftotext: {error}")))?, |
| 367 | }; |
| 368 | // No parser descendant may retain the capture pipes after the primary exits. |
| 369 | let _=tree.kill(); |
| 370 | let (stdout,stderr)=finish_capture_tasks(stdout_task,stderr_task).await?; |
| 371 | Ok((stdout,stderr,status)) |
| 372 | }.await; |
| 373 | PdfProcessOutcome { output } |
| 374 | } |
| 375 | |
| 376 | async fn wait_for_cancellation(cancel: Option<&CancellationToken>) { |
| 377 | match cancel { |
| 378 | Some(cancel) => cancel.cancelled().await, |
| 379 | None => std::future::pending::<()>().await, |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | async fn terminate_child(child: &mut tokio::process::Child) { |
| 384 | let _ = child.kill().await; |
| 385 | let _ = child.wait().await; |
| 386 | } |
| 387 | |
| 388 | struct BoundedOutput { |
| 389 | bytes: Vec<u8>, |
| 390 | truncated: bool, |
| 391 | } |
| 392 | |
| 393 | async fn read_bounded( |
| 394 | mut reader: impl AsyncRead + Unpin, |
| 395 | max_bytes: usize, |
| 396 | ) -> std::io::Result<BoundedOutput> { |
| 397 | let mut bytes = Vec::with_capacity(max_bytes.min(8 * 1024)); |
| 398 | let mut buffer = [0u8; 8 * 1024]; |
| 399 | let mut truncated = false; |
| 400 | loop { |
| 401 | let read = reader.read(&mut buffer).await?; |
| 402 | if read == 0 { |
| 403 | break; |
| 404 | } |
| 405 | let remaining = max_bytes.saturating_sub(bytes.len()); |
| 406 | let retained = read.min(remaining); |
| 407 | bytes.extend_from_slice(&buffer[..retained]); |
| 408 | truncated |= retained < read; |
| 409 | } |
| 410 | Ok(BoundedOutput { bytes, truncated }) |
| 411 | } |
| 412 | |
| 413 | async fn finish_capture_tasks( |
| 414 | mut stdout: tokio::task::JoinHandle<std::io::Result<BoundedOutput>>, |
| 415 | mut stderr: tokio::task::JoinHandle<std::io::Result<BoundedOutput>>, |
| 416 | ) -> Result<(BoundedOutput, BoundedOutput), PdfTextError> { |
| 417 | let joined = tokio::time::timeout(PDF_PIPE_DRAIN_TIMEOUT, async { |
| 418 | tokio::join!(&mut stdout, &mut stderr) |
| 419 | }) |
| 420 | .await; |
| 421 | let (stdout, stderr) = match joined { |
| 422 | Ok(output) => output, |
| 423 | Err(_) => { |
| 424 | stdout.abort(); |
| 425 | stderr.abort(); |
| 426 | let _ = tokio::join!(stdout, stderr); |
| 427 | return Err(PdfTextError::Execution( |
| 428 | "pdftotext output pipes did not close after process termination".to_string(), |
| 429 | )); |
| 430 | } |
| 431 | }; |
| 432 | let stdout = stdout |
| 433 | .map_err(|error| PdfTextError::Execution(format!("stdout reader failed: {error}")))? |
| 434 | .map_err(|error| PdfTextError::Execution(format!("stdout reader failed: {error}")))?; |
| 435 | let stderr = stderr |
| 436 | .map_err(|error| PdfTextError::Execution(format!("stderr reader failed: {error}")))? |
| 437 | .map_err(|error| PdfTextError::Execution(format!("stderr reader failed: {error}")))?; |
| 438 | Ok((stdout, stderr)) |
| 439 | } |
| 440 | |
| 441 | fn sanitized_text(bytes: &[u8]) -> String { |
| 442 | String::from_utf8_lossy(bytes) |
| 443 | .trim() |
| 444 | .chars() |
| 445 | .map(|character| match character { |
| 446 | '\n' | '\t' => character, |
| 447 | character if character.is_control() => '\u{fffd}', |
| 448 | character => character, |
| 449 | }) |
| 450 | .collect() |
| 451 | } |
| 452 | |
| 453 | #[cfg(test)] |
| 454 | mod tests; |
| 455 | |
| 456 | #[cfg(all(test, unix))] |
| 457 | #[path = "pdf/host_tests.rs"] |
| 458 | mod host_tests; |
| 459 |