use super::connection::Connection;
use super::schema::init_db;
use crate::core::extract;
use crate::core::fields;
use crate::core::search::serialize_f32_vec;
use crate::core::search::SharedEmbedder;
use crate::core::text::{fts_segment, same_tokens};
use anyhow::{Context, Result};
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct IndexStats {
pub scanned: usize,
pub indexed: usize,
pub unchanged: usize,
pub skipped: usize,
pub chunks: usize,
pub warnings: usize,
#[serde(default)]
pub denied: usize,
#[serde(default)]
pub backed_off: usize,
}
impl IndexStats {
pub fn merge(&mut self, other: IndexStats) {
self.scanned += other.scanned;
self.indexed += other.indexed;
self.unchanged += other.unchanged;
self.skipped += other.skipped;
self.chunks += other.chunks;
self.warnings += other.warnings;
self.denied += other.denied;
self.backed_off += other.backed_off;
}
}
#[derive(Debug, Clone)]
pub struct Chunk {
pub page: i64,
pub line_start: i64,
pub line_end: i64,
pub anchor: Option<String>,
pub section: Option<String>,
pub content: String,
}
const INDEXER_VERSION: &str = "extract4+chunk1";
pub struct Indexer {
conn: Connection,
embedder: Option<SharedEmbedder>,
max_chunk_words: usize,
overlap_words: usize,
ocr_enabled: bool,
}
impl Indexer {
pub fn new(conn: Connection, embedder: Option<SharedEmbedder>) -> Result<Self> {
Self::with_ocr(conn, embedder, ocr_by_default())
}
pub fn ocr_enabled(&self) -> bool {
self.ocr_enabled
}
pub fn with_ocr(
conn: Connection,
embedder: Option<SharedEmbedder>,
ocr_enabled: bool,
) -> Result<Self> {
init_db(&conn)?;
invalidate_on_upgrade(&conn)?;
if let Some(embedder) = &embedder {
Self::record_embedding_model(&conn, embedder.model_id())?;
}
Ok(Self {
conn,
embedder,
max_chunk_words: 400,
overlap_words: 40,
ocr_enabled,
})
}
fn record_embedding_model(conn: &Connection, model_id: &str) -> Result<()> {
let stored: Option<String> = conn
.inner()
.query_row(
"SELECT value FROM index_meta WHERE key = 'embedding_model'",
[],
|row| row.get(0),
)
.optional()?;
if stored.as_deref().is_some_and(|old| old != model_id) {
let tx = conn.inner().unchecked_transaction()?;
tx.execute("DELETE FROM chunks_vec", [])?;
tx.execute("DELETE FROM chunks", [])?;
tx.commit()?;
}
conn.inner().execute(
"INSERT INTO index_meta (key, value) VALUES ('embedding_model', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
[model_id],
)?;
Ok(())
}
pub fn connection(&self) -> &Connection {
&self.conn
}
pub fn index_roots(&self, roots: &[PathBuf]) -> Result<IndexStats> {
self.index_roots_within(roots, &[])
}
pub fn index_roots_within(
&self,
roots: &[PathBuf],
configured: &[PathBuf],
) -> Result<IndexStats> {
let mut stats = IndexStats::default();
let (known, recent) = self.denied_state()?;
let known = RefCell::new(known);
let pruned_dirs = Cell::new(0usize);
for root in roots {
if root.is_file() {
if root.file_name().is_some_and(is_hidden) {
continue;
}
if recent.contains(root) {
stats.backed_off += 1;
continue;
}
match self.index_file_within(root, Some(&enclosing_root(root, configured))) {
Ok(file_stats) => {
stats.merge(file_stats);
self.forget_recorded(root, &known);
}
Err(err) if is_permission_denied(&err) => {
self.note_denied(root, &format!("{err:#}"));
known.borrow_mut().insert(root.clone());
stats.denied += 1;
tracing::warn!("{}", denied_summary(root, 1));
}
Err(err) => return Err(err),
}
continue;
}
let mut root_denied = 0usize;
for entry in walkdir::WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry(|e| {
if is_hidden(e.file_name()) {
return false;
}
if e.file_type().is_dir() && recent.contains(e.path()) {
pruned_dirs.set(pruned_dirs.get() + 1);
return false;
}
true
})
{
let entry = match entry {
Ok(e) => e,
Err(e) => {
if is_walk_permission_denied(&e) {
if let Some(path) = e.path() {
self.note_denied(path, &format!("{e}"));
let first_time = known.borrow_mut().insert(path.to_path_buf());
if first_time {
root_denied += 1;
}
} else {
root_denied += 1;
}
} else {
tracing::warn!("walk error: {e}");
}
stats.skipped += 1;
continue;
}
};
self.forget_recorded(entry.path(), &known);
if entry.file_type().is_file() {
if recent.contains(entry.path()) {
stats.backed_off += 1;
continue;
}
match self.index_file_within(entry.path(), Some(root)) {
Ok(file_stats) => stats.merge(file_stats),
Err(err) => {
if is_permission_denied(&err) {
self.note_denied(entry.path(), &format!("{err:#}"));
let first_time =
known.borrow_mut().insert(entry.path().to_path_buf());
if first_time {
root_denied += 1;
}
} else {
tracing::warn!("{}: {err:#}", entry.path().display());
}
stats.skipped += 1;
}
}
}
}
stats.denied += root_denied;
if root_denied > 0 {
tracing::warn!("{}", denied_summary(root, root_denied));
}
}
stats.backed_off += pruned_dirs.get();
if let Err(err) = self.forget_vanished_unreadable() {
tracing::warn!("could not tidy the unreadable cache: {err:#}");
}
Ok(stats)
}
pub fn index_file(&self, path: &Path) -> Result<IndexStats> {
self.index_file_within(path, None)
}
pub fn index_file_within(&self, path: &Path, root: Option<&Path>) -> Result<IndexStats> {
let mut stats = IndexStats {
scanned: 1,
..Default::default()
};
let path_string = path.to_string_lossy().to_string();
if !extract::is_supported(&path_string) {
stats.skipped = 1;
return Ok(stats);
}
let metadata = std::fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || !metadata.is_file() {
stats.skipped = 1;
return Ok(stats);
}
let mut max_allowed: u64 = 0;
for extractor in extract::extractors() {
if extractor
.extensions()
.contains(&extract::extension_of(&path_string).as_str())
{
max_allowed = max_allowed.max(extractor.capabilities().max_file_bytes);
}
}
if max_allowed == 0 || metadata.len() > max_allowed {
stats.skipped = 1;
return Ok(stats);
}
let mtime = metadata
.modified()?
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64;
let size = metadata.len() as i64;
let unchanged: Option<i64> = self
.conn
.inner()
.query_row(
"SELECT 1 FROM chunks WHERE source_path = ? AND mtime = ? AND size = ? LIMIT 1",
rusqlite::params![path_string, mtime, size],
|row| row.get(0),
)
.optional()?;
if unchanged.is_some() {
stats.unchanged = 1;
return Ok(stats);
}
let bytes = match read_regular_file(path, root, max_allowed)
.with_context(|| format!("reading {path_string}"))?
{
Some(bytes) => bytes,
None => {
stats.skipped = 1;
return Ok(stats);
}
};
let hash = blake3::hash(&bytes);
let stored_hash: Option<Vec<u8>> = self
.conn
.inner()
.query_row(
"SELECT content_hash FROM chunks WHERE source_path = ? LIMIT 1",
[&path_string],
|row| row.get(0),
)
.optional()?;
if stored_hash.as_deref() == Some(hash.as_bytes().as_slice()) {
self.conn.inner().execute(
"UPDATE chunks SET mtime = ?, size = ? WHERE source_path = ?",
rusqlite::params![mtime, size, path_string],
)?;
stats.unchanged = 1;
return Ok(stats);
}
let docs = match extract::extract_named(&path_string, &bytes, self.ocr_enabled)? {
Some(docs) => docs,
None => {
stats.skipped = 1;
return Ok(stats);
}
};
let mut warnings = 0usize;
for doc in &docs {
for warning in &doc.warnings {
tracing::warn!("{path_string}: {warning}");
warnings += 1;
}
}
if warnings > 0 && docs.iter().all(|doc| doc.blocks.is_empty()) {
stats.warnings = warnings;
stats.skipped = 1;
return Ok(stats);
}
struct Row<'a> {
doc_path: &'a str,
chunk: Chunk,
fts_text: String,
fts_section: String,
metadata: String,
vector: Option<Vec<f32>>,
}
let mut rows = Vec::new();
for doc in &docs {
for chunk in chunk_blocks(&doc.blocks, self.max_chunk_words, self.overlap_words) {
let mut fts_text = fts_segment(&chunk.content);
if same_tokens(&fts_text, &chunk.content) {
fts_text.clear();
}
let section = chunk.section.as_deref().unwrap_or("");
let mut fts_section = fts_segment(section);
if same_tokens(&fts_section, section) {
fts_section.clear();
}
let metadata = fields::analyse(&chunk.content);
let vector = match &self.embedder {
Some(embedder) => Some(embedder.embed(&chunk.content)?),
None => None,
};
rows.push(Row {
doc_path: &doc.path,
chunk,
fts_text,
fts_section,
metadata,
vector,
});
}
}
let tx = self.conn.inner().unchecked_transaction()?;
tx.execute(
"DELETE FROM chunks_vec WHERE rowid IN (SELECT id FROM chunks WHERE source_path = ?)",
[&path_string],
)?;
tx.execute("DELETE FROM chunks WHERE source_path = ?", [&path_string])?;
let inserted = rows.len();
for row in &rows {
let chunk = &row.chunk;
tx.execute(
"INSERT INTO chunks
(path, source_path, page, line_start, line_end, anchor, section, content,
fts_text, fts_section, content_hash, mtime, size, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
rusqlite::params![
row.doc_path,
path_string,
chunk.page,
chunk.line_start,
chunk.line_end,
chunk.anchor,
chunk.section,
chunk.content,
row.fts_text,
row.fts_section,
hash.as_bytes().as_slice(),
mtime,
size,
row.metadata,
],
)?;
if let Some(vector) = &row.vector {
tx.execute(
"INSERT INTO chunks_vec (rowid, embedding) VALUES (?, ?)",
rusqlite::params![tx.last_insert_rowid(), serialize_f32_vec(vector)],
)?;
}
}
tx.commit()?;
stats.warnings = warnings;
if inserted == 0 {
stats.skipped = 1;
} else {
stats.indexed = 1;
stats.chunks = inserted;
}
Ok(stats)
}
pub fn reindex_file(&self, path: &Path) -> Result<IndexStats> {
self.index_file(path)
}
fn denied_state(&self) -> Result<(HashSet<PathBuf>, HashSet<PathBuf>)> {
let cutoff = now_unix() - DENIED_BACKOFF.as_secs() as i64;
let mut stmt = self
.conn
.inner()
.prepare("SELECT path, last_attempt FROM unreadable")?;
let rows = stmt.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
})?;
let mut known = HashSet::new();
let mut recent = HashSet::new();
for row in rows {
let (path, last_attempt) = row?;
let path = PathBuf::from(path);
if last_attempt > cutoff {
recent.insert(path.clone());
}
known.insert(path);
}
Ok((known, recent))
}
fn unreadable_paths(&self) -> Result<Vec<PathBuf>> {
let mut stmt = self.conn.inner().prepare("SELECT path FROM unreadable")?;
let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
Ok(rows
.collect::<std::result::Result<Vec<_>, _>>()?
.into_iter()
.map(PathBuf::from)
.collect())
}
fn forget_recorded(&self, path: &Path, known: &RefCell<HashSet<PathBuf>>) {
let was_recorded = known.borrow_mut().remove(path);
if !was_recorded {
return;
}
if let Err(err) = self.forget_unreadable(path) {
tracing::warn!(
"could not clear the unreadable mark on {}: {err:#}",
path.display()
);
}
}
fn forget_unreadable(&self, path: &Path) -> Result<()> {
self.conn.inner().execute(
"DELETE FROM unreadable WHERE path = ?1",
[path.to_string_lossy()],
)?;
Ok(())
}
fn forget_vanished_unreadable(&self) -> Result<()> {
let mut stale = Vec::new();
for path in self.unreadable_paths()? {
if !path.exists() {
stale.push(path);
}
}
for path in stale {
self.forget_unreadable(&path)?;
}
Ok(())
}
fn note_denied(&self, path: &Path, reason: &str) {
if let Err(err) = self.remember_unreadable(path, reason) {
tracing::warn!(
"could not record {} as unreadable ({err:#}); it will be retried next pass",
path.display()
);
}
}
fn remember_unreadable(&self, path: &Path, reason: &str) -> Result<()> {
let now = now_unix();
self.conn.inner().execute(
"INSERT INTO unreadable (path, reason, first_seen, last_attempt)
VALUES (?1, ?2, ?3, ?3)
ON CONFLICT(path) DO UPDATE SET
reason = excluded.reason,
last_attempt = excluded.last_attempt",
rusqlite::params![path.to_string_lossy(), reason, now],
)?;
Ok(())
}
pub fn prune_missing(&self) -> Result<usize> {
let mut stmt = self
.conn
.inner()
.prepare("SELECT DISTINCT source_path FROM chunks")?;
let paths: Vec<String> = stmt
.query_map([], |row| row.get(0))?
.collect::<std::result::Result<_, _>>()?;
drop(stmt);
let unreadable = self.unreadable_paths()?;
let hidden_by_permission = |path: &str| {
let path = Path::new(path);
unreadable.iter().any(|denied| path.starts_with(denied))
};
let missing: Vec<String> = paths
.into_iter()
.filter(|path| {
!path.is_empty() && !Path::new(path).exists() && !hidden_by_permission(path)
})
.collect();
if missing.is_empty() {
return Ok(0);
}
let tx = self.conn.inner().unchecked_transaction()?;
let mut removed = 0usize;
{
let mut del_vec = tx.prepare(
"DELETE FROM chunks_vec WHERE rowid IN
(SELECT id FROM chunks WHERE source_path = ?1)",
)?;
let mut del_chunks = tx.prepare("DELETE FROM chunks WHERE source_path = ?1")?;
for path in &missing {
if !path.is_empty() && !Path::new(path).exists() {
del_vec.execute([path])?;
del_chunks.execute([path])?;
removed += 1;
}
}
}
tx.commit()?;
self.conn
.inner()
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
Ok(removed)
}
}
use rusqlite::OptionalExtension;
fn invalidate_on_upgrade(conn: &Connection) -> Result<()> {
let stored: Option<String> = conn
.inner()
.query_row(
"SELECT value FROM index_meta WHERE key = 'indexer_version'",
[],
|row| row.get(0),
)
.optional()?;
if stored.as_deref() == Some(INDEXER_VERSION) {
return Ok(());
}
let tx = conn.inner().unchecked_transaction()?;
tx.execute("DELETE FROM chunks_vec", [])?;
tx.execute("DELETE FROM chunks", [])?;
tx.execute(
"INSERT INTO index_meta (key, value) VALUES ('indexer_version', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
[INDEXER_VERSION],
)?;
tx.commit()?;
Ok(())
}
pub fn enclosing_root(file: &Path, configured: &[PathBuf]) -> PathBuf {
configured
.iter()
.find(|root| *file != **root && file.starts_with(root))
.cloned()
.or_else(|| file.parent().map(Path::to_path_buf))
.unwrap_or_default()
}
fn read_regular_file(
path: &Path,
root: Option<&Path>,
max_bytes: u64,
) -> std::io::Result<Option<Vec<u8>>> {
let file = fs::File::open(path)?;
let opened = file.metadata()?;
let named = fs::symlink_metadata(path)?;
if !opened.is_file()
|| !named.is_file()
|| file_id(&opened) != file_id(&named)
|| opened.len() > max_bytes
{
return Ok(None);
}
if let Some(root) = root {
match (real_path(path, Some(&file)), real_path(root, None)) {
(Ok(real), Ok(root_real)) => {
let same = fs::metadata(&real).is_ok_and(|m| file_id(&m) == file_id(&opened));
if !real.starts_with(&root_real) {
if cfg!(target_os = "linux") || link_count(&opened) <= 1 {
return Ok(None);
}
warn_unverified_once(path);
} else if !same {
return Ok(None);
}
}
_ => warn_unverified_once(path),
}
}
let mut bytes = Vec::new();
file.take(max_bytes + 1).read_to_end(&mut bytes)?;
Ok((bytes.len() as u64 <= max_bytes).then_some(bytes))
}
fn warn_unverified_once(path: &Path) {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(
"cannot verify where {} really lives on this platform; indexing it without the under-root check",
path.display()
);
});
}
fn real_path(path: &Path, file: Option<&fs::File>) -> std::io::Result<PathBuf> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let opened;
let file = match file {
Some(file) => file,
None => {
opened = fs::File::open(path)?;
&opened
}
};
if let Some(real) = fd_path(file) {
return Ok(real);
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let _ = file;
fs::canonicalize(path)
}
#[cfg(target_os = "linux")]
fn fd_path(file: &fs::File) -> Option<PathBuf> {
use std::os::fd::AsRawFd;
fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()
}
#[cfg(target_os = "macos")]
fn fd_path(file: &fs::File) -> Option<PathBuf> {
use std::ffi::{c_int, OsString};
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStringExt;
unsafe extern "C" {
fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
}
const F_GETPATH: c_int = 50;
let mut buf = vec![0u8; 1024];
if unsafe { fcntl(file.as_raw_fd(), F_GETPATH, buf.as_mut_ptr()) } == -1 {
return None;
}
buf.truncate(buf.iter().position(|&b| b == 0)?);
Some(PathBuf::from(OsString::from_vec(buf)))
}
#[cfg(unix)]
fn file_id(metadata: &fs::Metadata) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
Some((metadata.dev(), metadata.ino()))
}
#[cfg(unix)]
fn link_count(metadata: &fs::Metadata) -> u64 {
std::os::unix::fs::MetadataExt::nlink(metadata)
}
#[cfg(not(unix))]
fn file_id(_: &fs::Metadata) -> Option<(u64, u64)> {
None
}
#[cfg(not(unix))]
fn link_count(_: &fs::Metadata) -> u64 {
1
}
pub(crate) fn is_hidden(name: &std::ffi::OsStr) -> bool {
name.to_string_lossy().starts_with('.')
}
const DENIED_BACKOFF: Duration = Duration::from_secs(10 * 60);
fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
fn is_permission_denied(error: &anyhow::Error) -> bool {
error.chain().any(|cause| {
cause
.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::PermissionDenied)
})
}
fn is_walk_permission_denied(error: &walkdir::Error) -> bool {
error
.io_error()
.is_some_and(|io| io.kind() == std::io::ErrorKind::PermissionDenied)
}
fn permission_remedy() -> &'static str {
if cfg!(target_os = "macos") {
"grant access in System Settings → Privacy & Security → Full Disk Access or Files and \
Folders"
} else if cfg!(windows) {
"grant your user read permission on the folder (Properties → Security)"
} else {
"fix the directory permissions (`ls -ld` on the path)"
}
}
fn denied_summary(root: &Path, entries: usize) -> String {
let entry = if entries == 1 { "entry" } else { "entries" };
format!(
"{}: {entries} {entry} could not be read (permission denied) — {}; Paper retries in {} \
minutes and picks the files up on the next pass once access is granted",
root.display(),
permission_remedy(),
DENIED_BACKOFF.as_secs() / 60
)
}
pub fn is_indexable(path: &Path) -> bool {
extract::is_supported(&path.to_string_lossy())
}
pub fn chunk_text(text: &str, max_words: usize, overlap_words: usize) -> Vec<Chunk> {
let max_words = max_words.max(1);
let overlap = overlap_words.min(max_words - 1);
let lines: Vec<&str> = text.lines().collect();
let mut chunks = Vec::new();
let mut current: Vec<&str> = Vec::new();
let mut current_words = 0usize;
let mut start_line = 1usize;
for (idx, line) in lines.iter().enumerate() {
let line_no = idx + 1;
let words = line.split_whitespace().count();
let heading = is_markdown_heading(line);
if !current.is_empty() && (current_words + words > max_words || heading) {
chunks.push(Chunk {
page: 0,
line_start: start_line as i64,
line_end: (line_no - 1) as i64,
anchor: None,
section: None,
content: current.join("\n"),
});
let mut kept: Vec<&str> = Vec::new();
let mut kept_words = 0usize;
if !heading {
for prev in current.iter().rev() {
let w = prev.split_whitespace().count();
if kept_words + w > overlap {
break;
}
kept.insert(0, prev);
kept_words += w;
}
}
start_line = line_no.saturating_sub(kept.len());
current = kept;
current_words = kept_words;
}
if current.is_empty() {
start_line = line_no;
}
current.push(line);
current_words += words;
}
if current.iter().any(|l| !l.trim().is_empty()) {
chunks.push(Chunk {
page: 0,
line_start: start_line as i64,
line_end: lines.len().max(1) as i64,
anchor: None,
section: None,
content: current.join("\n"),
});
}
chunks
}
fn is_markdown_heading(line: &str) -> bool {
let trimmed = line.trim_start();
let hashes = trimmed.chars().take_while(|c| *c == '#').count();
(1..=6).contains(&hashes) && trimmed.chars().nth(hashes) == Some(' ')
}
pub fn chunk_blocks(
blocks: &[extract::Block],
max_words: usize,
overlap_words: usize,
) -> Vec<Chunk> {
let mut out = Vec::new();
for block in blocks {
for chunk in chunk_text(&block.text, max_words, overlap_words) {
let (line_start, line_end) = if block.line_start > 0 {
(
block.line_start + chunk.line_start - 1,
block.line_start + chunk.line_end - 1,
)
} else {
(0, 0)
};
out.push(Chunk {
page: block.page,
line_start,
line_end,
anchor: block.anchor.clone(),
section: block.section.clone(),
content: chunk.content,
});
}
}
out
}
pub fn index_with_defaults(
db_path: &Path,
roots: &[PathBuf],
embedder: Option<SharedEmbedder>,
) -> Result<IndexStats> {
index_with_defaults_atomic(db_path, roots, embedder)
}
fn index_with_defaults_atomic(
db_path: &Path,
roots: &[PathBuf],
embedder: Option<SharedEmbedder>,
) -> Result<IndexStats> {
let tmp_path = db_path.with_extension("db.tmp");
let _ = fs::remove_file(&tmp_path);
let conn = Connection::open_or_create(&tmp_path).context("opening temp index database")?;
let stats = Indexer::new(conn, embedder)?.index_roots(roots)?;
atomic_replace(&tmp_path, db_path)?;
Ok(stats)
}
fn atomic_replace(src: &Path, dst: &Path) -> Result<()> {
match fs::rename(src, dst) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
fs::copy(src, dst).with_context(|| {
format!(
"copying {} -> {} (cross-device)",
src.display(),
dst.display()
)
})?;
fs::remove_file(src)
.with_context(|| format!("removing temp file {}", src.display()))?;
}
Err(e) => {
return Err(e)
.with_context(|| format!("renaming {} -> {}", src.display(), dst.display()))
}
}
Ok(())
}
fn ocr_by_default() -> bool {
#[cfg(feature = "ocr")]
{
crate::core::extract::ocr::enabled(false)
}
#[cfg(not(feature = "ocr"))]
{
false
}
}
#[cfg(test)]
mod tests {
use super::IndexStats;
#[test]
fn stats_from_an_older_daemon_deserialize() {
let old = r#"{"scanned":3,"indexed":1,"unchanged":0,"skipped":2,"chunks":4,"warnings":0}"#;
let stats: IndexStats = serde_json::from_str(old).expect("an older payload must parse");
assert_eq!(stats.indexed, 1);
assert_eq!((stats.denied, stats.backed_off), (0, 0));
}
#[test]
fn stats_carry_the_permission_counters_over_the_wire() {
let stats = IndexStats {
denied: 2,
backed_off: 3,
..IndexStats::default()
};
let json = serde_json::to_string(&stats).expect("serialize");
let back: IndexStats = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, stats);
}
}