1#[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
39pub const MAX_EXTRACTED_BYTES: usize = 32 * 1024 * 1024;
41pub const MAX_ARCHIVE_ENTRIES: usize = 2_000;
43pub const MAX_PDF_PAGES: u32 = 5_000;
44
45const MAX_STUCK_PARSERS: usize = 4;
51static STUCK_PARSERS: Mutex<Vec<std::thread::JoinHandle<()>>> = Mutex::new(Vec::new());
52
53fn 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
69fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Capabilities {
88 pub max_file_bytes: u64,
91 pub max_pages: u32,
93 pub max_entries: usize,
95 pub streaming: bool,
98 pub thread_safe: bool,
100 pub requires_external: bool,
102}
103
104#[derive(Debug, Clone, Copy, Default)]
111pub struct ExtractOptions {
112 pub ocr_enabled: bool,
114}
115
116impl Default for Capabilities {
117 fn default() -> Self {
118 Self {
119 max_file_bytes: 64 * 1024 * 1024, 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#[derive(Debug, Clone)]
132pub struct ExtractedDocument {
133 pub path: String,
134 pub format: &'static str,
135 pub blocks: Vec<Block>,
136 pub warnings: Vec<String>,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct Block {
143 pub text: String,
144 pub page: i64,
146 pub anchor: Option<String>,
149 pub section: Option<String>,
152 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
179pub trait Extractor: Send + Sync {
184 fn name(&self) -> &'static str;
186
187 fn extensions(&self) -> &'static [&'static str];
189
190 fn sniff(&self, _bytes: &[u8]) -> bool {
192 false
193 }
194
195 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 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 Arc::new(textfmt::Plain),
237 ];
238 #[cfg(feature = "ocr")]
241 if ocr::models_present() {
242 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
253pub fn register(extractor: Arc<dyn Extractor>) {
256 if let Ok(mut list) = custom().lock() {
257 list.push(extractor);
258 }
259}
260
261pub 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
270pub 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
289pub 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
297pub 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 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
323pub 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
333pub(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 #[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 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 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 {
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 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 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 return Ok(None);
491 }
492 return Ok(Some(docs));
493 }
494 Ok(None)
495}
496
497pub(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
517pub(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}