Skip to content

A fast, helpful, and open-source document parser

fix: use RAII for buffer conversion temp directory cleanup

AdemBoukhris4570adb791f7b53
diff --git a/crates/liteparse/src/conversion.rs b/crates/liteparse/src/conversion.rs
index 3e4f3c1..d0362db 100644
--- a/crates/liteparse/src/conversion.rs
+++ b/crates/liteparse/src/conversion.rs
@@ -37,6 +37,16 @@ pub struct ConversionResult {
pub original_extension: String,
}
+/// Temp directories created during buffer-to-PDF conversion. Retained until
+/// dropped so staging and output dirs are removed on both success and failure.
+#[derive(Debug)]
+pub struct BufferConversionTemps {
+ #[allow(dead_code)]
+ staging: TempDir,
+ #[allow(dead_code)]
+ output: Option<TempDir>,
+}
+
enum ConversionTool {
LibreOffice,
ImageMagick,
@@ -84,7 +94,6 @@ pub fn is_supported_extension(path: &str) -> bool {
pub async fn convert_to_pdf(
path: &str,
password: Option<&str>,
- is_temporary_path: bool,
) -> Result<(ConversionResult, Option<TempDir>), LiteParseError> {
let ext = Path::new(path)
.extension()
@@ -125,10 +134,6 @@ pub async fn convert_to_pdf(
convert_office_document(path, tmp_dir.path().to_str().unwrap(), password).await?
}
};
- // Remove temporary path for Office docs/images bytes
- if is_temporary_path {
- tokio::fs::remove_dir_all(Path::new(path).parent().unwrap()).await?;
- }
Ok((
ConversionResult {
@@ -482,14 +487,24 @@ pub fn guess_extension_from_data(data: &[u8]) -> Option<String> {
pub async fn convert_data_to_pdf(
data: Vec<u8>,
password: Option<&str>,
-) -> Result<(ConversionResult, Option<TempDir>), LiteParseError> {
+) -> Result<(ConversionResult, BufferConversionTemps), LiteParseError> {
let ext = guess_extension_from_data(&data);
- let tmp_dir = tempfile::Builder::new().prefix("liteparse-").tempdir()?;
- let tmp_path = tmp_dir
- .keep()
+ let staging_dir = tempfile::Builder::new()
+ .prefix("liteparse-staging-")
+ .tempdir()?;
+ let tmp_path = staging_dir
+ .path()
.join(format!("input.{}", ext.unwrap_or("bin".to_string())));
tokio::fs::write(&tmp_path, data).await?;
- convert_to_pdf(tmp_path.to_str().unwrap(), password, true).await
+ let (converted, output_dir) =
+ convert_to_pdf(tmp_path.to_str().unwrap(), password).await?;
+ Ok((
+ converted,
+ BufferConversionTemps {
+ staging: staging_dir,
+ output: output_dir,
+ },
+ ))
}
#[cfg(test)]
@@ -596,15 +611,38 @@ mod tests {
#[tokio::test]
async fn test_convert_to_pdf_passthrough_pdf() {
- let (res, _) = convert_to_pdf("/some/file.pdf", None, false).await.unwrap();
+ let (res, _) = convert_to_pdf("/some/file.pdf", None).await.unwrap();
assert_eq!(res.pdf_path, "/some/file.pdf");
assert_eq!(res.original_extension, "pdf");
}
#[tokio::test]
async fn test_convert_to_pdf_unsupported() {
- let r = convert_to_pdf("/some/file.xyz", None, false).await;
+ let r = convert_to_pdf("/some/file.xyz", None).await;
assert!(r.is_err());
assert!(r.unwrap_err().to_string().contains("unsupported"));
}
+
+ #[tokio::test]
+ async fn test_convert_data_to_pdf_cleans_staging_on_failure() {
+ let test_tmp = tempfile::tempdir().expect("test temp dir");
+ // SAFETY: single-threaded test; restored after scope
+ unsafe {
+ std::env::set_var("TMPDIR", test_tmp.path());
+ std::env::set_var("TEMP", test_tmp.path());
+ std::env::set_var("TMP", test_tmp.path());
+ }
+
+ let data = vec![0u8, 1, 2, 3];
+ let err = convert_data_to_pdf(data, None).await.unwrap_err();
+ assert!(err.to_string().contains("unsupported"));
+
+ let remaining: Vec<_> = std::fs::read_dir(test_tmp.path())
+ .expect("read test temp dir")
+ .collect();
+ assert!(
+ remaining.is_empty(),
+ "staging temp dir should be removed when conversion fails"
+ );
+ }
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index be046e8..c7742ea 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1,5 +1,3 @@
-use std::path::Path;
-
use crate::config::{LiteParseConfig, parse_target_pages};
#[cfg(not(target_arch = "wasm32"))]
use crate::conversion;
@@ -74,11 +72,10 @@ impl LiteParse {
let t0 = web_time::Instant::now();
- let mut is_converted = false;
#[cfg(not(target_arch = "wasm32"))]
- let _tmp_dir: Option<tempfile::TempDir>;
+ let mut _buffer_temps: Option<conversion::BufferConversionTemps> = None;
#[cfg(not(target_arch = "wasm32"))]
- let _conv_tmp_dir: Option<tempfile::TempDir>;
+ let mut _conv_tmp_dir: Option<tempfile::TempDir> = None;
let validated_input = {
#[cfg(target_arch = "wasm32")]
@@ -93,7 +90,7 @@ impl LiteParse {
PdfInput::Path(p)
} else {
let (converted, tmp_dir) =
- conversion::convert_to_pdf(&p, self.config.password.as_deref(), false)
+ conversion::convert_to_pdf(&p, self.config.password.as_deref())
.await?;
_conv_tmp_dir = tmp_dir;
// The on-disk source isn't ours to delete; only the
@@ -102,10 +99,9 @@ impl LiteParse {
}
}
PdfInput::Bytes(b) => {
- let (converted, tmp_dir) =
+ let (converted, buffer_temps) =
convert_data_to_pdf(b, self.config.password.as_deref()).await?;
- _tmp_dir = tmp_dir;
- is_converted = true;
+ _buffer_temps = Some(buffer_temps);
PdfInput::Path(converted.pdf_path)
}
}
@@ -198,15 +194,6 @@ impl LiteParse {
let total = t2.duration_since(t0).as_secs_f64() * 1000.0;
log(&format!("[liteparse] total: {:.1}ms", total));
- // Office docs and images that are temporarily created from bytes
- // are removed, but not PDFs, as they pass through the coversion logic
- // and are used directly as input.
- // With this block, we insure that temporary PDFs created from bytes and/or
- // converted from Office/image files are cleaned up as well.
- if is_converted && let PdfInput::Path(p) = validated_input {
- std::fs::remove_dir_all(Path::new(&p).parent().unwrap())?;
- }
-
Ok(ParseResult {
pages: parsed_pages,
text: full_text,