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 let options = ExtractOptions { ocr_enabled };
331
332 // Try shell-out accelerators first (feature-gated)
333 #[cfg(feature = "shell-accel")]
334 {
335 if let Some(path) = std::path::Path::new(name).extension() {
336 if let Some(ext) = path.to_str() {
337 if let Ok(Some(docs)) =
338 crate::core::extract::accel::try_accelerators(std::path::Path::new(name), ext)
339 {
340 if !docs.is_empty() {
341 return Ok(Some(docs));
342 }
343 }
344 }
345 }
346 }
347
348 for extractor in extractors() {
349 if !extractor.can_handle(name, bytes) {
350 continue;
351 }
352 let caps = extractor.capabilities();
353
354 // Enforce memory cap before parsing.
355 if bytes.len() as u64 > caps.max_file_bytes {
356 return Ok(Some(single(
357 name,
358 extractor.name(),
359 Vec::new(),
360 vec![format!(
361 "file size {} exceeds maximum {} bytes",
362 bytes.len(),
363 caps.max_file_bytes
364 )],
365 )));
366 }
367
368 // Per-parser timeout: run extract in a separate thread with a 5-second
369 // deadline. `std::thread` + mpsc avoids nesting a tokio runtime.
370 //
371 // A parser that ignores its deadline must not be able to spawn an
372 // unbounded number of threads. Reap any that have since finished, and
373 // refuse to start more while the stalled set is at its cap. Normal
374 // concurrent parsing is never limited.
375 {
376 reap_stuck_parsers();
377 ensure_reaper();
378 let stuck = STUCK_PARSERS.lock().unwrap_or_else(|e| e.into_inner());
379 if stuck.len() >= MAX_STUCK_PARSERS {
380 return Ok(Some(single(
381 name,
382 extractor.name(),
383 Vec::new(),
384 vec![format!(
385 "skipped: {MAX_STUCK_PARSERS} parsers are stalled; restart the indexer"
386 )],
387 )));
388 }
389 drop(stuck);
390 }
391
392 let extractor_clone = extractor.clone();
393 let name_owned = name.to_string();
394 let bytes_owned = bytes.to_vec();
395 let (tx, rx) = std::sync::mpsc::channel();
396 let handle = std::thread::spawn(move || {
397 let _ =
398 tx.send(extractor_clone.extract_with_options(&name_owned, &bytes_owned, &options));
399 });
400 // OCR is CPU-bound on a 960x960 network per page, so a scanned document
401 // legitimately needs minutes. Everything else keeps the tight deadline
402 // that protects the index run from a parser that never returns.
403 let deadline = if options.ocr_enabled {
404 std::time::Duration::from_secs(180)
405 } else {
406 std::time::Duration::from_secs(5)
407 };
408 let result = rx.recv_timeout(deadline);
409
410 let mut docs = match result {
411 Ok(Ok(Some(docs))) => {
412 let _ = handle.join();
413 docs
414 }
415 Ok(Ok(None)) => {
416 let _ = handle.join();
417 continue;
418 }
419 Ok(Err(err)) => {
420 let _ = handle.join();
421 return Ok(Some(single(
422 name,
423 extractor.name(),
424 Vec::new(),
425 vec![format!("extraction error: {err}")],
426 )));
427 }
428 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
429 // Deliberately do NOT join: the parser may never return. Park the
430 // handle so it occupies a stalled slot until it finishes. A
431 // background reaper joins finished handles so threads don't leak.
432 tracing::warn!("{}: extraction timed out after 5 seconds", name);
433 ensure_reaper();
434 STUCK_PARSERS
435 .lock()
436 .unwrap_or_else(|e| e.into_inner())
437 .push(handle);
438 return Ok(Some(single(
439 name,
440 extractor.name(),
441 Vec::new(),
442 vec!["extraction timed out after 5 seconds".to_string()],
443 )));
444 }
445 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
446 let _ = handle.join();
447 return Ok(Some(single(
448 name,
449 extractor.name(),
450 Vec::new(),
451 vec!["extraction task panicked".to_string()],
452 )));
453 }
454 };
455
456 for doc in &mut docs {
457 doc.format = extractor.name();
458 if doc.path.is_empty() {
459 doc.path = name.to_string();
460 }
461 doc.blocks = finish_blocks(std::mem::take(&mut doc.blocks));
462 }
463 docs.retain(|doc| !doc.blocks.is_empty());
464 if docs.is_empty() {
465 // Matched the format but had nothing citable (empty or unreadable).
466 return Ok(None);
467 }
468 return Ok(Some(docs));
469 }
470 Ok(None)
471}
472
473/// Drop empty blocks and cap their size. Anchors are never modified.
474pub(crate) fn finish_blocks(mut blocks: Vec<Block>) -> Vec<Block> {
475 let mut total = 0usize;
476 blocks.retain(|b| !b.text.trim().is_empty());
477 for block in &mut blocks {
478 if block.text.len() > MAX_EXTRACTED_BYTES {
479 let mut cut = MAX_EXTRACTED_BYTES;
480 while cut > 0 && !block.text.is_char_boundary(cut) {
481 cut -= 1;
482 }
483 block.text.truncate(cut);
484 }
485 total += block.text.len();
486 if total > MAX_EXTRACTED_BYTES {
487 break;
488 }
489 }
490 blocks
491}
492
493/// Helper for extractors: build a single-document result.
494pub(crate) fn single(
495 name: &str,
496 format: &'static str,
497 blocks: Vec<Block>,
498 warnings: Vec<String>,
499) -> Vec<ExtractedDocument> {
500 vec![ExtractedDocument {
501 path: name.to_string(),
502 format,
503 blocks,
504 warnings,
505 }]
506}