Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions crates/videre-core/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,23 @@ pub struct RowSig {
/// but cannot stat, or a row with no stored mtime, is never current.
pub fn is_current(sig: &RowSig, cur_size: u64, cur_mtime: Option<&str>) -> bool {
sig.has_mime
&& sig.size_bytes == cur_size
&& cur_mtime.is_some()
&& sig.modified_at.as_deref() == cur_mtime
&& is_unchanged(
sig.size_bytes,
sig.modified_at.as_deref(),
cur_size,
cur_mtime,
)
}

/// Shared stamp comparison for indexed media and cached content exclusions.
/// Missing modification times never establish that a file is unchanged.
pub fn is_unchanged(
stored_size: u64,
stored_mtime: Option<&str>,
cur_size: u64,
cur_mtime: Option<&str>,
) -> bool {
stored_size == cur_size && cur_mtime.is_some() && stored_mtime == cur_mtime
}

/// Load every row's signature in one query, keyed by path. Empty when the
Expand Down
97 changes: 97 additions & 0 deletions crates/videre-core/src/ignored_files.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//! Cached content exclusions, kept outside the media index. A missing table
//! is an empty cache, so older libraries and older readers remain usable.

use rusqlite::{params, Connection};
use std::collections::{HashMap, HashSet};

pub const APPLEDOUBLE: &str = "appledouble";

#[derive(Clone, Debug)]
pub struct IgnoredFile {
pub path: String,
pub size_bytes: u64,
pub modified_at: Option<String>,
pub reason: String,
}

pub fn ensure_table(conn: &Connection) -> rusqlite::Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS ignored_files (
path TEXT PRIMARY KEY,
size_bytes INTEGER NOT NULL,
modified_at TEXT,
reason TEXT NOT NULL
);",
)
}

/// Only exclusions this version understands may suppress a probe. New reasons
/// written by a newer version are harmless cache misses to an older reader.
pub fn stored_signatures(conn: &Connection) -> rusqlite::Result<HashMap<String, IgnoredFile>> {
if !crate::db::table_exists(conn, "ignored_files")? {
return Ok(HashMap::new());
}
let mut stmt = conn.prepare(
"SELECT path, size_bytes, modified_at, reason FROM ignored_files WHERE reason = ?1",
)?;
let rows = stmt.query_map([APPLEDOUBLE], |row| {
let entry = IgnoredFile {
path: row.get(0)?,
size_bytes: row.get::<_, i64>(1)? as u64,
modified_at: row.get(2)?,
reason: row.get(3)?,
};
Ok((entry.path.clone(), entry))
})?;
rows.collect()
}

/// Called inside the scan writer's transaction, alongside media writes and
/// removal of exclusions for files now recognized as media.
pub fn write(conn: &Connection, entries: &[IgnoredFile]) -> rusqlite::Result<()> {
let mut stmt = conn.prepare(
"INSERT INTO ignored_files(path, size_bytes, modified_at, reason)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(path) DO UPDATE SET size_bytes = excluded.size_bytes,
modified_at = excluded.modified_at, reason = excluded.reason",
)?;
for entry in entries {
stmt.execute(params![
entry.path,
entry.size_bytes as i64,
entry.modified_at,
entry.reason
])?;
}
Ok(())
}

pub fn forget<'a>(
conn: &Connection,
paths: impl IntoIterator<Item = &'a str>,
) -> rusqlite::Result<()> {
let mut stmt = conn.prepare("DELETE FROM ignored_files WHERE path = ?1")?;
for path in paths {
stmt.execute([path])?;
}
Ok(())
}

/// A full scan already knows which paths it saw. Drop obsolete cache entries
/// without another filesystem pass. A partial walk can only lose cache hits;
/// it never removes anything from the media index.
pub fn retain_seen(conn: &Connection, seen: &HashSet<String>) -> rusqlite::Result<()> {
let obsolete: Vec<String> = {
let mut stmt = conn.prepare("SELECT path FROM ignored_files")?;
let paths = stmt.query_map([], |row| row.get::<_, String>(0))?;
paths
.filter_map(|path| match path {
Ok(path) if seen.contains(&path) => None,
other => Some(other),
})
.collect::<rusqlite::Result<_>>()?
};
let tx = conn.unchecked_transaction()?;
forget(&tx, obsolete.iter().map(String::as_str))?;
tx.commit()
}
1 change: 1 addition & 0 deletions crates/videre-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub mod geocode;
pub mod heic;
pub(crate) mod held_lock;
pub mod hf_cache;
pub mod ignored_files;
pub mod image_decode;
pub mod import_location;
pub mod import_providers;
Expand Down
3 changes: 3 additions & 0 deletions crates/videre-core/src/library_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@ pub fn ensure_scan_schema(conn: &Connection) -> rusqlite::Result<()> {
add_missing_columns(conn, "file_hashes", FILE_HASHES_COLUMNS)?;
ensure_hash_index(conn)?;
ensure_capture_date_index(conn)?;
// Optional cache: its absence must not make an otherwise current library
// unreadable or require a schema-version upgrade.
crate::ignored_files::ensure_table(conn)?;
// The declared location-cluster key needs its parent table to exist
// before any row is written, including through standalone scan writers
// that never run the full schema preparation.
Expand Down
56 changes: 56 additions & 0 deletions crates/videre/src/appledouble.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! Recognize AppleDouble metadata by its contents, independently of its name.

pub const HEADER_LEN: usize = 26;

/// Identify the container from its magic and supported version, checking that
/// the fixed header and declared entry table fit in the file. Resource contents
/// are not validated. Uncertain headers and AppleSingle remain indexable.
pub fn is_header(head: &[u8], file_len: u64) -> bool {
if head.len() < HEADER_LEN || !head.starts_with(b"\x00\x05\x16\x07") {
return false;
}
if !matches!(&head[4..8], b"\x00\x01\x00\x00" | b"\x00\x02\x00\x00") {
return false;
}
let entries = u16::from_be_bytes([head[24], head[25]]);
HEADER_LEN as u64 + u64::from(entries) * 12 <= file_len
}

#[cfg(test)]
mod tests {
use super::*;

fn header(version: u32, entries: u16) -> [u8; HEADER_LEN] {
let mut head = [0; HEADER_LEN];
head[..4].copy_from_slice(&0x0005_1607u32.to_be_bytes());
head[4..8].copy_from_slice(&version.to_be_bytes());
head[24..].copy_from_slice(&entries.to_be_bytes());
head
}

#[test]
fn appledouble_header_detection_preserves_other_formats_and_uncertain_data() {
let v1 = header(0x0001_0000, 1);
let v2 = header(0x0002_0000, 1);
let empty = header(0x0002_0000, 0);
let unknown = header(0x0003_0000, 0);
let mut single = v2;
single[..4].copy_from_slice(&0x0005_1600u32.to_be_bytes());
let mut jpeg = v2;
jpeg[..3].copy_from_slice(b"\xff\xd8\xff");

let cases: [(&str, &[u8], u64, bool); 8] = [
("version 1", &v1, 70, true),
("version 2", &v2, 70, true),
("no entries", &empty, 26, true),
("short header", &v2[..25], 70, false),
("truncated entry table", &v2, 37, false),
("unknown version", &unknown, 70, false),
("AppleSingle", &single, 70, false),
("JPEG", &jpeg, 70, false),
];
for (name, head, file_len, expected) in cases {
assert_eq!(is_header(head, file_len), expected, "{name}");
}
}
}
51 changes: 35 additions & 16 deletions crates/videre/src/commands/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,16 @@ fn run_inner(args: &ScanArgs, ctx: &CommandContext) -> anyhow::Result<ScanJson>

let (records, skipped) =
videre_core::pipeline_runs::track_in(&conn, &ctx.library, &guard, "scan", || {
let (records, skipped, _walked) = gather_records(args, ctx, &conn);
sqlite_output::write_records_in(&conn, &ctx.library, &records)?;
let gathered = gather_records(args, ctx, &conn)?;
sqlite_output::write_scan_in(
&conn,
&ctx.library,
&gathered.batch.records,
&gathered.batch.ignored,
)?;
videre_core::ignored_files::retain_seen(&conn, &gathered.seen)?;
let records = gathered.batch.records;
let skipped = gathered.skipped;
// Rows written before capture dates get theirs from what they
// already hold; nothing is hashed again.
let resolved = sqlite_output::resolve_unresolved(&conn)?;
Expand Down Expand Up @@ -142,28 +150,30 @@ fn run_inner(args: &ScanArgs, ctx: &CommandContext) -> anyhow::Result<ScanJson>
})
}

struct GatheredRecords {
batch: crate::indexing::IndexBatch,
skipped: usize,
seen: std::collections::HashSet<String>,
}

fn gather_records(
args: &ScanArgs,
ctx: &CommandContext,
conn: &Connection,
) -> (Vec<videre::types::FileRecord>, usize, usize) {
) -> anyhow::Result<GatheredRecords> {
// Incremental by default: skip a file whose row is already current. `--force`
// loads no signatures, so everything is reprocessed. A file the walk sees
// but cannot stat, and any new path, falls through to the hash path.
let sigs = if args.force {
std::collections::HashMap::new()
} else {
videre_core::db::stored_signatures(conn).unwrap_or_default()
};
let all_paths = scanner::scan(&ctx.library.paths.root);
let walked = all_paths.len();
let paths: Vec<_> = all_paths
.into_iter()
.filter(|path| videre::incremental::needs_processing(&sigs, path))
let seen = all_paths
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
let candidates = videre::incremental::candidates(conn, all_paths, args.force)?;
let paths = candidates.paths;
let progress = videre_core::progress::Progress::new(paths.len() as u64, args.silent);

let records: Vec<_> = paths
let files = paths
.par_iter()
.filter_map(|path| {
// Tracked while it hashes, so a large file shows its bytes beside
Expand All @@ -176,15 +186,24 @@ fn gather_records(
let tracked = progress.track(&name, handle.clone());
let hashed = hasher::hash_file_in_observed(&ctx.library, path, &handle);
drop(tracked);
let result = record_or_skip(hashed, &progress, &path.display().to_string());
let result = record_or_skip(
crate::indexing::classify(hashed),
&progress,
&path.display().to_string(),
);
progress.tick();
result
})
.collect();
progress.finish();
let skipped = paths.len() - records.len();
let batch = crate::indexing::IndexBatch::from_files(files);
let skipped = candidates.ignored + paths.len() - batch.records.len();

(records, skipped, walked)
Ok(GatheredRecords {
batch,
skipped,
seen,
})
}

fn record_or_skip<T>(
Expand Down
Loading
Loading