Skip to main content

paper/core/extract/
mod.rs

1//! Document extraction with media-native citation anchors.
2//!
3//! # Design
4//!
5//! Extraction produces **facts**, never interpretations. A block carries the
6//! text exactly as the file states it plus the locator the file itself exposes:
7//! a PDF page number, a spreadsheet cell range, a slide index, a paragraph
8//! range, an EPUB spine position, an email message id. Nothing is classified,
9//! dated, summarised or normalised semantically. If the library cannot read a
10//! format or a page, it says so; it never guesses.
11//!
12//! Formats are handled by an ordered registry of [`Extractor`] implementations.
13//! Selection is by declared extension first and by unambiguous magic bytes
14//! second; an unrecognised file is *unsupported*, not "probably text". New
15//! formats are additive: implement `Extractor` and [`register`] it.
16//!
17//! # Anchors
18//!
19//! A chunk inherits the anchor of the block it was cut from, so a citation can
20//! name `report.pdf [page 7]`, `budget.xlsx [Q3!B4:H4]` or `deck.pptx [slide 2]`
21//! and a reader can verify it in one step. Line ranges are added where the
22//! format has real lines.
23
24#[cfg(feature = "shell-accel")]
25pub mod accel;
26mod archive;
27mod email;
28#[cfg(feature = "ocr")]
29pub mod ocr;
30mod ooxml;
31mod pdf;
32mod sheet;
33mod textfmt;
34
35use anyhow::Result;
36use std::path::Path;
37use std::sync::{Arc, Mutex, OnceLock};
38
39/// Hard cap on a single extracted text, to bound memory on hostile input.
40pub const MAX_EXTRACTED_BYTES: usize = 32 * 1024 * 1024;
41/// Hard cap on archive members and PDF pages.
42pub const MAX_ARCHIVE_ENTRIES: usize = 2_000;
43pub const MAX_PDF_PAGES: u32 = 5_000;
44
45/// A parser that blows its five-second deadline is not killed (Rust has no safe
46/// cancellation), so its thread and input copy survive. This keeps the handles
47/// of stalled parsers so finished ones can be reaped and the set can be capped.
48/// Normal concurrency is not limited: only threads that outlived the deadline
49/// occupy a slot. Worst-case retention is `MAX_STUCK_PARSERS` input copies.
50const MAX_STUCK_PARSERS: usize = 4;
51static STUCK_PARSERS: Mutex<Vec<std::thread::JoinHandle<()>>> = Mutex::new(Vec::new());
52
53/// Background reaper: joins finished stuck parser threads so their resources
54/// are reclaimed instead of leaking until the next extraction attempt.
55fn reap_stuck_parsers() {
56    let mut stuck = STUCK_PARSERS.lock().unwrap_or_else(|e| e.into_inner());
57    let mut i = 0;
58    while i < stuck.len() {
59        if stuck[i].is_finished() {
60            let handle = stuck.remove(i);
61            let _ = handle.join();
62        } else {
63            i += 1;
64        }
65    }
66    drop(stuck);
67}
68
69/// Start a lazy background reaper that drains finished stuck parsers every few
70/// seconds. Spawned on first use.
71fn ensure_reaper() {
72    static REAPER: std::sync::OnceLock<std::thread::JoinHandle<()>> = std::sync::OnceLock::new();
73    let _ = REAPER.get_or_init(|| {
74        std::thread::spawn(move || loop {
75            std::thread::sleep(std::time::Duration::from_secs(5));
76            reap_stuck_parsers();
77        })
78    });
79}
80
81/// Capabilities declared by an extractor.
82///
83/// These bounds are enforced by the extraction pipeline before and during
84/// parsing. An extractor should choose conservative values that reflect the
85/// worst-case resource consumption of its parser on malicious input.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Capabilities {
88    /// Maximum file size this extractor will accept, in bytes.
89    /// Files larger than this are rejected before parsing begins.
90    pub max_file_bytes: u64,
91    /// Maximum number of pages (for paged formats) or entries (for archives).
92    pub max_pages: u32,
93    /// Maximum number of archive members or spreadsheet rows to process.
94    pub max_entries: usize,
95    /// Whether the extractor can process input incrementally without loading
96    /// the entire file into memory.
97    pub streaming: bool,
98    /// Whether the extractor is safe to call concurrently from multiple tasks.
99    pub thread_safe: bool,
100    /// Whether the extractor requires an external binary or system dependency.
101    pub requires_external: bool,
102}
103
104/// Per-run switches a caller can pass to extraction.
105///
106/// Options are separate from [`Capabilities`] because capabilities describe an
107/// extractor, while options describe what this call is allowed to do. A format
108/// that ignores an option inherits the trait's default method, so adding a knob
109/// never forces every extractor to change.
110#[derive(Debug, Clone, Copy, Default)]
111pub struct ExtractOptions {
112    /// Attempt OCR on textless pages and standalone images.
113    pub ocr_enabled: bool,
114}
115
116impl Default for Capabilities {
117    fn default() -> Self {
118        Self {
119            max_file_bytes: 64 * 1024 * 1024, // 64 MB
120            max_pages: 5_000,
121            max_entries: 2_000,
122            streaming: false,
123            thread_safe: true,
124            requires_external: false,
125        }
126    }
127}
128
129/// One extracted document. Archives yield several, addressed as
130/// `outer.zip!/inner/path`.
131#[derive(Debug, Clone)]
132pub struct ExtractedDocument {
133    pub path: String,
134    pub format: &'static str,
135    pub blocks: Vec<Block>,
136    /// Explicit failures such as `page 3: no text layer`. Reported to the user
137    /// instead of being silently swallowed.
138    pub warnings: Vec<String>,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct Block {
143    pub text: String,
144    /// 1-based page for paged formats, 0 when the format has no pages.
145    pub page: i64,
146    /// Format-specific anchor: `page 3`, `Sheet1!A5:H5`, `slide 2`,
147    /// `para 4-9`, `spine 1: chapter.xhtml`, `message <id>`.
148    pub anchor: Option<String>,
149    /// Declared section path (`Warranty / Coverage`), when the format states
150    /// one. Never inferred from layout.
151    pub section: Option<String>,
152    /// 1-based line range *within the block's text source*, 0 when the format
153    /// has no meaningful lines (DOCX, spreadsheets, slides, email).
154    pub line_start: i64,
155    pub line_end: i64,
156}
157
158impl Block {
159    pub fn text(text: impl Into<String>) -> Self {
160        let text = text.into();
161        let lines = text.lines().count().max(1) as i64;
162        Self {
163            text,
164            page: 0,
165            anchor: None,
166            section: None,
167            line_start: 1,
168            line_end: lines,
169        }
170    }
171
172    pub fn anchored(text: impl Into<String>, anchor: impl Into<String>) -> Self {
173        let mut block = Self::text(text);
174        block.anchor = Some(anchor.into());
175        block
176    }
177}
178
179/// A format handler.
180///
181/// `extract` must either return text it actually decoded or `Ok(None)`. It must
182/// not fall back to treating arbitrary bytes as text.
183pub trait Extractor: Send + Sync {
184    /// Stable format name, used for reporting and for `Hit::anchor_kind`.
185    fn name(&self) -> &'static str;
186
187    /// Extensions handled, lower-case, without the dot.
188    fn extensions(&self) -> &'static [&'static str];
189
190    /// Unambiguous content check, for files with a missing or wrong extension.
191    fn sniff(&self, _bytes: &[u8]) -> bool {
192        false
193    }
194
195    /// Resource and safety capabilities of this extractor.
196    ///
197    /// The extraction pipeline enforces `max_file_bytes` before calling
198    /// `extract`, wraps the call in a 5-second timeout, and respects
199    /// `thread_safe` when deciding on parallelism.
200    fn capabilities(&self) -> Capabilities {
201        Capabilities::default()
202    }
203
204    fn can_handle(&self, name: &str, bytes: &[u8]) -> bool {
205        self.extensions().contains(&extension_of(name).as_str()) || self.sniff(bytes)
206    }
207
208    fn extract(&self, name: &str, bytes: &[u8]) -> Result<Option<Vec<ExtractedDocument>>>;
209
210    /// `extract` with caller-supplied options.
211    ///
212    /// Extractors that honour an option override this; the rest keep the
213    /// default body and are unaffected by new options.
214    fn extract_with_options(
215        &self,
216        name: &str,
217        bytes: &[u8],
218        _options: &ExtractOptions,
219    ) -> Result<Option<Vec<ExtractedDocument>>> {
220        self.extract(name, bytes)
221    }
222}
223
224fn builtin() -> Vec<Arc<dyn Extractor>> {
225    #[allow(unused_mut)]
226    let mut formats: Vec<Arc<dyn Extractor>> = vec![
227        Arc::new(pdf::Pdf),
228        Arc::new(ooxml::Docx),
229        Arc::new(ooxml::Pptx),
230        Arc::new(ooxml::Epub),
231        Arc::new(sheet::Sheet),
232        Arc::new(archive::Archive),
233        Arc::new(email::Email),
234        Arc::new(textfmt::Html),
235        // Last: only claims extensions it declares or unambiguous text markers.
236        Arc::new(textfmt::Plain),
237    ];
238    // Images are only claimed once OCR weights are on disk, so a build (or a
239    // machine) without them reports `unsupported` instead of indexing silence.
240    #[cfg(feature = "ocr")]
241    if ocr::models_present() {
242        // Before `Plain`: a PNG is never text, so it must win the extension.
243        formats.insert(8, Arc::new(ocr::ImageOcr));
244    }
245    formats
246}
247
248fn custom() -> &'static Mutex<Vec<Arc<dyn Extractor>>> {
249    static CUSTOM: OnceLock<Mutex<Vec<Arc<dyn Extractor>>>> = OnceLock::new();
250    CUSTOM.get_or_init(|| Mutex::new(Vec::new()))
251}
252
253/// Add an extractor. Custom extractors are tried after the built-ins, so a
254/// custom handler can widen support without changing built-in behaviour.
255pub fn register(extractor: Arc<dyn Extractor>) {
256    if let Ok(mut list) = custom().lock() {
257        list.push(extractor);
258    }
259}
260
261/// Every registered extractor, built-ins first.
262pub fn extractors() -> Vec<Arc<dyn Extractor>> {
263    let mut all = builtin();
264    if let Ok(list) = custom().lock() {
265        all.extend(list.iter().cloned());
266    }
267    all
268}
269
270/// Every extension any extractor declares.
271pub fn supported_extensions() -> Vec<&'static str> {
272    let mut out: Vec<&'static str> = Vec::new();
273    for extractor in extractors() {
274        out.extend_from_slice(extractor.extensions());
275    }
276    out.sort_unstable();
277    out.dedup();
278    out
279}
280
281pub fn extension_of(path: &str) -> String {
282    Path::new(path)
283        .extension()
284        .and_then(|e| e.to_str())
285        .unwrap_or("")
286        .to_ascii_lowercase()
287}
288
289/// Whether any extractor claims this path by extension.
290pub fn is_supported(path: &str) -> bool {
291    let ext = extension_of(path);
292    extractors()
293        .iter()
294        .any(|e| e.extensions().contains(&ext.as_str()))
295}
296
297/// Extract a file from disk. Returns zero or more documents (archives yield
298/// many). An unsupported file is `Ok(None)`.
299pub fn extract_path(path: &Path) -> Result<Option<Vec<ExtractedDocument>>> {
300    let name = path.to_string_lossy().to_string();
301    if !is_supported(&name) {
302        return Ok(None);
303    }
304    // Pre-read size cap: refuse to load a file larger than every applicable
305    // extractor will accept, preventing memory DoS on hostile input (I7).
306    let metadata = std::fs::symlink_metadata(path)?;
307    let mut max_allowed: u64 = 0;
308    for extractor in extractors() {
309        if extractor
310            .extensions()
311            .contains(&extension_of(&name).as_str())
312        {
313            max_allowed = max_allowed.max(extractor.capabilities().max_file_bytes);
314        }
315    }
316    if max_allowed == 0 || metadata.len() > max_allowed {
317        return Ok(None);
318    }
319    let bytes = std::fs::read(path)?;
320    extract_named(&name, &bytes, false)
321}
322
323/// Extract bytes that are already in memory (archive members, tests).
324/// `ocr_enabled` controls whether OCR is attempted for scanned PDF pages.
325pub fn extract_named(
326    name: &str,
327    bytes: &[u8],
328    ocr_enabled: bool,
329) -> Result<Option<Vec<ExtractedDocument>>> {
330    extract_selected(name, bytes, ocr_enabled, false)
331}
332
333/// Extract an archive member. Another archive is never opened from here,
334/// whatever the member's extension or magic bytes, so nesting cannot recurse.
335pub(crate) fn extract_member(name: &str, bytes: &[u8]) -> Result<Option<Vec<ExtractedDocument>>> {
336    extract_selected(name, bytes, false, true)
337}
338
339fn extract_selected(
340    name: &str,
341    bytes: &[u8],
342    ocr_enabled: bool,
343    inside_archive: bool,
344) -> Result<Option<Vec<ExtractedDocument>>> {
345    let options = ExtractOptions { ocr_enabled };
346
347    // Try shell-out accelerators first (feature-gated)
348    #[cfg(feature = "shell-accel")]
349    {
350        if let Some(path) = std::path::Path::new(name).extension() {
351            if let Some(ext) = path.to_str() {
352                if let Ok(Some(docs)) =
353                    crate::core::extract::accel::try_accelerators(std::path::Path::new(name), ext)
354                {
355                    if !docs.is_empty() {
356                        return Ok(Some(docs));
357                    }
358                }
359            }
360        }
361    }
362
363    for extractor in extractors() {
364        if !extractor.can_handle(name, bytes) {
365            continue;
366        }
367        // Final, not skipped: the member ends as a failed nested parse always did.
368        if inside_archive && extractor.name() == archive::Archive.name() {
369            return Ok(Some(single(
370                name,
371                extractor.name(),
372                Vec::new(),
373                vec!["nested archive not followed".to_string()],
374            )));
375        }
376        let caps = extractor.capabilities();
377
378        // Enforce memory cap before parsing.
379        if bytes.len() as u64 > caps.max_file_bytes {
380            return Ok(Some(single(
381                name,
382                extractor.name(),
383                Vec::new(),
384                vec![format!(
385                    "file size {} exceeds maximum {} bytes",
386                    bytes.len(),
387                    caps.max_file_bytes
388                )],
389            )));
390        }
391
392        // Per-parser timeout: run extract in a separate thread with a 5-second
393        // deadline. `std::thread` + mpsc avoids nesting a tokio runtime.
394        //
395        // A parser that ignores its deadline must not be able to spawn an
396        // unbounded number of threads. Reap any that have since finished, and
397        // refuse to start more while the stalled set is at its cap. Normal
398        // concurrent parsing is never limited.
399        {
400            reap_stuck_parsers();
401            ensure_reaper();
402            let stuck = STUCK_PARSERS.lock().unwrap_or_else(|e| e.into_inner());
403            if stuck.len() >= MAX_STUCK_PARSERS {
404                return Ok(Some(single(
405                    name,
406                    extractor.name(),
407                    Vec::new(),
408                    vec![format!(
409                        "skipped: {MAX_STUCK_PARSERS} parsers are stalled; restart the indexer"
410                    )],
411                )));
412            }
413            drop(stuck);
414        }
415
416        let extractor_clone = extractor.clone();
417        let name_owned = name.to_string();
418        let bytes_owned = bytes.to_vec();
419        let (tx, rx) = std::sync::mpsc::channel();
420        let handle = std::thread::spawn(move || {
421            let _ =
422                tx.send(extractor_clone.extract_with_options(&name_owned, &bytes_owned, &options));
423        });
424        // OCR is CPU-bound on a 960x960 network per page, so a scanned document
425        // legitimately needs minutes. Everything else keeps the tight deadline
426        // that protects the index run from a parser that never returns.
427        let deadline = if options.ocr_enabled {
428            std::time::Duration::from_secs(180)
429        } else {
430            std::time::Duration::from_secs(5)
431        };
432        let result = rx.recv_timeout(deadline);
433
434        let mut docs = match result {
435            Ok(Ok(Some(docs))) => {
436                let _ = handle.join();
437                docs
438            }
439            Ok(Ok(None)) => {
440                let _ = handle.join();
441                continue;
442            }
443            Ok(Err(err)) => {
444                let _ = handle.join();
445                return Ok(Some(single(
446                    name,
447                    extractor.name(),
448                    Vec::new(),
449                    vec![format!("extraction error: {err}")],
450                )));
451            }
452            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
453                // Deliberately do NOT join: the parser may never return. Park the
454                // handle so it occupies a stalled slot until it finishes. A
455                // background reaper joins finished handles so threads don't leak.
456                tracing::warn!("{}: extraction timed out after 5 seconds", name);
457                ensure_reaper();
458                STUCK_PARSERS
459                    .lock()
460                    .unwrap_or_else(|e| e.into_inner())
461                    .push(handle);
462                return Ok(Some(single(
463                    name,
464                    extractor.name(),
465                    Vec::new(),
466                    vec!["extraction timed out after 5 seconds".to_string()],
467                )));
468            }
469            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
470                let _ = handle.join();
471                return Ok(Some(single(
472                    name,
473                    extractor.name(),
474                    Vec::new(),
475                    vec!["extraction task panicked".to_string()],
476                )));
477            }
478        };
479
480        for doc in &mut docs {
481            doc.format = extractor.name();
482            if doc.path.is_empty() {
483                doc.path = name.to_string();
484            }
485            doc.blocks = finish_blocks(std::mem::take(&mut doc.blocks));
486        }
487        docs.retain(|doc| !doc.blocks.is_empty());
488        if docs.is_empty() {
489            // Matched the format but had nothing citable (empty or unreadable).
490            return Ok(None);
491        }
492        return Ok(Some(docs));
493    }
494    Ok(None)
495}
496
497/// Drop empty blocks and cap their size. Anchors are never modified.
498pub(crate) fn finish_blocks(mut blocks: Vec<Block>) -> Vec<Block> {
499    let mut total = 0usize;
500    blocks.retain(|b| !b.text.trim().is_empty());
501    for block in &mut blocks {
502        if block.text.len() > MAX_EXTRACTED_BYTES {
503            let mut cut = MAX_EXTRACTED_BYTES;
504            while cut > 0 && !block.text.is_char_boundary(cut) {
505                cut -= 1;
506            }
507            block.text.truncate(cut);
508        }
509        total += block.text.len();
510        if total > MAX_EXTRACTED_BYTES {
511            break;
512        }
513    }
514    blocks
515}
516
517/// Helper for extractors: build a single-document result.
518pub(crate) fn single(
519    name: &str,
520    format: &'static str,
521    blocks: Vec<Block>,
522    warnings: Vec<String>,
523) -> Vec<ExtractedDocument> {
524    vec![ExtractedDocument {
525        path: name.to_string(),
526        format,
527        blocks,
528        warnings,
529    }]
530}