Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

IX13: raea index add|search|status|remove|serve, the fast pass kept open for the feed

shinyobjectzc5d3f83c79b6
diff --git a/Cargo.lock b/Cargo.lock
index 01db9a79..a2f7fb30 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14196,6 +14196,7 @@ dependencies = [
"raea-runtime-plugins",
"raea-runtime-react",
"raea-runtime-sound",
+ "raea-sys-index",
"regex",
"serde",
"serde_json",
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index c12b8d99..08cd8189 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -55,6 +55,8 @@ raea-app-direction = { path = "../../apps/direction" }
raea-app-notes = { path = "../../apps/notes" }
# `raea fingerprint`: axes with small heads over on-device encoders, and the service that keeps them loaded (docs/fingerprint.feature FP3a)
raea-app-fingerprint = { path = "../../apps/fingerprint" }
+# `raea index`: every picture on a folder or a drive searchable by words, embedded on the Neural Engine (docs/index.feature IX13)
+raea-sys-index = { path = "../../systems/index" }
raea-app-sound = { path = "../../apps/sound" }
raea-app-ci = { path = "../../apps/ci" }
raea-app-tools = { path = "../../apps/tools" }
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index e49fe5be..f0c14ae0 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -137,7 +137,7 @@ pub fn run(args: &[String]) -> R<String> {
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
- let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE);
+ let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
@@ -207,6 +207,7 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)
if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)
if args[0] == "fingerprint" { std::process::exit(raea_app_fingerprint::cli(&args[1..], spec::spec_json)); } // a person's sense of good work as axes over on-device encoders (docs/fingerprint.feature FP3a, FP14a)
+ if args[0] == "index" { std::process::exit(raea_sys_index::cli::cli(&args[1..])); } // every picture on a folder or a drive searchable by words, embedded on the Neural Engine (docs/index.feature IX13)
if args[0] == "traces" { return traces(args); }
if args.first().map(String::as_str) == Some("play") {
return raea_app_play::play(args);
diff --git a/systems/index/examples/fast.rs b/systems/index/examples/fast.rs
index caf90d3e..e13d3f0d 100644
--- a/systems/index/examples/fast.rs
+++ b/systems/index/examples/fast.rs
@@ -1,42 +1,6 @@
-//! The fast pass by hand, to measure it (docs/index.feature IX1, IX14):
-//! fast index FOLDER list it and embed its pictures, printing progress as JSON lines
-//! fast search WORDS... the best ten for the words
-//! RAEA_INDEX_HOME picks the index's folder.
-use raea_sys_index::{Progress, search, store::Store, text::Text};
-use std::path::Path;
-
-fn main() -> anyhow::Result<()> {
+//! `raea index` without building all of raea, to measure the fast pass (docs/index.feature IX1, IX14):
+//! fast add FOLDER | fast search WORDS... | fast status | fast remove ID | fast serve (cli.rs USAGE)
+fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
- let mut store = Store::open(&Store::default_dir())?;
- let say = |p: &Progress| println!("{}", serde_json::to_string(p).unwrap());
- match args.first().map(String::as_str) {
- Some("index") => {
- let root = Path::new(&args[1]);
- let (source, found) = raea_sys_index::list_folder(&mut store, root, &mut |p| say(p))?;
- eprintln!("listed {found}");
- let t = std::time::Instant::now();
- let model = raea_sys_index::apple::Model::load(&raea_sys_index::image_package()).map_err(anyhow::Error::msg)?;
- eprintln!("model loaded in {:.2} s", t.elapsed().as_secs_f64());
- let p = raea_sys_index::embed_pictures(&mut store, &model, &source, &mut |p| say(p))?;
- eprintln!("done: {} embedded, {} failed, {:.0}/s over {:.1} s", p.done, p.failed, p.per_sec, p.seconds);
- }
- Some("search") => {
- let words = args[1..].join(" ");
- let (m, tok) = raea_sys_index::text_files();
- let t = std::time::Instant::now();
- let mut text = Text::load(&m, &tok)?;
- let rows = search::Rows::load(&store, raea_sys_index::store::MODEL)?;
- eprintln!("loaded {} rows and the text tower in {:.2} s", rows.len(), t.elapsed().as_secs_f64());
- let t = std::time::Instant::now();
- let q = text.embed(&words)?;
- let e = t.elapsed().as_secs_f64();
- let hits = search::search(&store, &rows, &q, 10)?;
- eprintln!("query {:.0} ms, search {:.0} ms", e * 1e3, (t.elapsed().as_secs_f64() - e) * 1e3);
- for h in hits {
- println!("{:.3} {}", h.score, h.locator);
- }
- }
- _ => eprintln!("fast index FOLDER | fast search WORDS..."),
- }
- Ok(())
+ std::process::exit(raea_sys_index::cli::cli(&args));
}
diff --git a/systems/index/src/cli.rs b/systems/index/src/cli.rs
new file mode 100644
index 00000000..f10f50a8
--- /dev/null
+++ b/systems/index/src/cli.rs
@@ -0,0 +1,165 @@
+//! `raea index` (docs/index.feature IX13): the fast pass from a terminal, and the server the feed keeps open.
+
+use crate::search::{self, Rows};
+use crate::store::{MODEL, Store};
+use crate::text::Text;
+use anyhow::{Result, anyhow};
+use std::io::IsTerminal;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+
+pub const USAGE: &str = "raea index add FOLDER... [--json] | raea index search WORDS... [--k N] [--source ID|FOLDER] [--json] | raea index status [--json] | raea index remove ID|FOLDER | raea index serve [--home DIR] (every picture on a folder or a drive made searchable by words on this Mac, fast: add lists it and embeds each picture's small copy with SigLIP 2 on the Neural Engine, a counter as it goes, JSON lines with --json; search gives the best for the words; status lists the sources and what each holds; remove takes one out; serve keeps the index open for the raea app, one JSON ask a line on stdin; the index lives in ~/.raea/library/fast, or --home / RAEA_INDEX_HOME)";
+
+pub fn cli(args: &[String]) -> i32 {
+ match run(args) {
+ Ok(()) => 0,
+ Err(e) => {
+ eprintln!("raea index: {e:#}");
+ 1
+ }
+ }
+}
+
+struct Flags {
+ json: bool,
+ k: usize,
+ source: Option<String>,
+ rest: Vec<String>,
+}
+
+fn flags(args: &[String]) -> Result<(Flags, PathBuf)> {
+ let mut f = Flags { json: false, k: 10, source: None, rest: vec![] };
+ let mut home = Store::default_dir();
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ let mut value = |name: &str| it.next().cloned().ok_or_else(|| anyhow!("{name} needs a value"));
+ match a.as_str() {
+ "--json" => f.json = true,
+ "--k" => f.k = value("--k")?.parse().map_err(|_| anyhow!("--k takes a number"))?,
+ "--source" => f.source = Some(value("--source")?),
+ "--home" => home = PathBuf::from(value("--home")?),
+ _ => f.rest.push(a.clone()),
+ }
+ }
+ Ok((f, home))
+}
+
+fn run(args: &[String]) -> Result<()> {
+ let verb = args.first().map(String::as_str).unwrap_or("");
+ let (f, home) = flags(args.get(1..).unwrap_or(&[]))?;
+ match verb {
+ "serve" => crate::serve::serve(&home),
+ "add" => add(&f, &home),
+ "search" => find(&f, &home),
+ "status" => status(&f, &home),
+ "remove" => {
+ let which = f.rest.first().ok_or_else(|| anyhow!("remove takes a source id or the folder"))?;
+ let mut store = Store::open(&home)?;
+ let canon = std::fs::canonicalize(which).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| which.clone());
+ let source = store.find(which)?.or(store.find(&canon)?).ok_or_else(|| anyhow!("no source {which}"))?;
+ let n = store.remove(&source)?;
+ println!("removed {source}: {n} items");
+ Ok(())
+ }
+ _ => Err(anyhow!("usage: {USAGE}")),
+ }
+}
+
+fn add(f: &Flags, home: &std::path::Path) -> Result<()> {
+ if f.rest.is_empty() {
+ anyhow::bail!("add takes a folder or a drive");
+ }
+ let mut store = Store::open(home)?;
+ let tty = std::io::stderr().is_terminal() && !f.json;
+ let say = |p: &crate::Progress| {
+ if f.json {
+ println!("{}", serde_json::to_string(p).unwrap_or_default());
+ } else if tty {
+ match p.stage {
+ "listing" => eprint!("\r\x1b[2Kfound {}", p.found),
+ _ => eprint!("\r\x1b[2K{} of {} searchable · {:.0} a second", p.done, p.found, p.per_sec),
+ }
+ }
+ };
+ #[cfg(target_vendor = "apple")]
+ let mut model: Option<crate::apple::Model> = None;
+ for path in &f.rest {
+ let root = std::fs::canonicalize(path).map_err(|e| anyhow!("{path}: {e}"))?;
+ if !root.is_dir() {
+ anyhow::bail!("{path} isn't a folder");
+ }
+ let l = crate::list_folder(&mut store, &root, &mut |p| say(p))?;
+ #[cfg(target_vendor = "apple")]
+ {
+ if model.is_none() {
+ let pkg = crate::image_package();
+ model = Some(crate::apple::Model::load(&pkg).map_err(|e| anyhow!("SigLIP 2's picture model ({e})"))?);
+ }
+ let stop = Arc::new(AtomicBool::new(false));
+ let p = crate::embed_pictures(&mut store, model.as_ref().expect("loaded"), &l.source, &stop, &mut |p| say(p))?;
+ if tty {
+ eprint!("\r\x1b[2K");
+ }
+ if !f.json {
+ println!("{}: {} found ({} new), {} searchable, {} failed; {:.0} a second over {:.1} s", root.display(), l.found, l.added, p.done, p.failed, p.per_sec, p.seconds);
+ }
+ }
+ #[cfg(not(target_vendor = "apple"))]
+ {
+ let _ = (&l, Arc::new(AtomicBool::new(false)));
+ anyhow::bail!("listed {} in {}; embedding runs on a Mac for now", l.found, root.display());
+ }
+ }
+ Ok(())
+}
+
+fn find(f: &Flags, home: &std::path::Path) -> Result<()> {
+ let words = f.rest.join(" ");
+ if words.trim().is_empty() {
+ anyhow::bail!("search takes words");
+ }
+ let store = Store::open(home)?;
+ let source = match &f.source {
+ Some(s) => {
+ let canon = std::fs::canonicalize(s).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| s.clone());
+ Some(store.find(s)?.or(store.find(&canon)?).ok_or_else(|| anyhow!("no source {s}"))?)
+ }
+ None => None,
+ };
+ let (m, tok) = crate::text_files();
+ let mut text = Text::load(&m, &tok)?;
+ let rows = Rows::load(&store, MODEL)?;
+ let q = text.embed(&words)?;
+ let hits = search::search(&store, &rows, &q, f.k, source.as_deref())?;
+ if f.json {
+ println!("{}", serde_json::to_string(&hits)?);
+ return Ok(());
+ }
+ if hits.is_empty() {
+ eprintln!("nothing searchable yet: raea index add FOLDER");
+ }
+ for h in hits {
+ let at = if h.kind == "video" { format!(" at {:.1} s", h.t) } else { String::new() };
+ println!("{:.3} {}{at}", h.score, h.locator);
+ }
+ Ok(())
+}
+
+fn status(f: &Flags, home: &std::path::Path) -> Result<()> {
+ let store = Store::open(home)?;
+ let sources = store.sources()?;
+ let rows = store.counts(None)?.rows;
+ if f.json {
+ println!("{}", serde_json::json!({ "home": home, "model": MODEL, "rows": rows, "sources": sources }));
+ return Ok(());
+ }
+ println!("{} ({MODEL}, {rows} rows)", home.display());
+ if sources.is_empty() {
+ println!(" nothing yet: raea index add FOLDER");
+ }
+ for s in sources {
+ println!(" {} {} {} found, {} searchable, {} failed", s.id, s.root, s.found, s.done, s.failed);
+ }
+ Ok(())
+}
diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rs
index ff7b9e14..16c159b2 100644
--- a/systems/index/src/lib.rs
+++ b/systems/index/src/lib.rs
@@ -6,7 +6,9 @@
#[cfg(target_vendor = "apple")]
pub mod apple;
+pub mod cli;
pub mod search;
+pub mod serve;
pub mod store;
pub mod text;
pub mod walk;
@@ -14,7 +16,7 @@ pub mod walk;
use anyhow::Result;
use std::path::{Path, PathBuf};
use std::time::Instant;
-use store::{DONE, LISTED, MODEL, Store};
+use store::{MODEL, Store};
/// A picture or a video a source holds, before the fast pass reads it
#[derive(Debug, Clone, Default)]
@@ -67,30 +69,47 @@ pub fn text_files() -> (PathBuf, PathBuf) {
(d.join("onnx/text_model.onnx"), d.join("tokenizer.json"))
}
-/// Lists a folder or a drive into the index; returns its source id and how many it found
-pub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)) -> Result<(String, u64)> {
+/// What listing a source found
+#[derive(Debug, Clone, Default)]
+pub struct Listed {
+ pub source: String,
+ pub found: u64,
+ pub added: u64,
+ /// items whose file changed since the last listing: their old rows are gone
+ pub changed: u64,
+}
+
+/// Lists a folder or a drive into the index: new files added, changed ones put back in line
+pub fn list_folder(store: &mut Store, root: &Path, on: &mut dyn FnMut(&Progress)) -> Result<Listed> {
let label = root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string());
let source = store.source("folder", &root.to_string_lossy(), &label)?;
let started = Instant::now();
- let mut found = 0u64;
+ let mut l = Listed { source: source.clone(), ..Listed::default() };
let mut err = None;
walk::walk(root, 2000, &mut |batch| {
- found += batch.len() as u64;
- if let Err(e) = store.list(&source, &batch) {
- err.get_or_insert(e);
+ l.found += batch.len() as u64;
+ match store.list(&source, &batch) {
+ Ok((a, c)) => {
+ l.added += a as u64;
+ l.changed += c as u64;
+ }
+ Err(e) => {
+ err.get_or_insert(e);
+ }
}
- on(&Progress { source: source.clone(), found, stage: "listing", seconds: started.elapsed().as_secs_f64(), ..Progress::default() });
+ on(&Progress { source: source.clone(), found: l.found, stage: "listing", seconds: started.elapsed().as_secs_f64(), ..Progress::default() });
});
if let Some(e) = err {
return Err(e);
}
- Ok((source, found))
+ Ok(l)
}
/// The fast pass over a source's pictures that wait for it: decoded on every core but two, embedded 32 at a time on
/// the Neural Engine, each batch's rows written as it finishes. Videos wait for their frames (IX2).
#[cfg(target_vendor = "apple")]
-pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on: &mut dyn FnMut(&Progress)) -> Result<Progress> {
+pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, stop: &std::sync::Arc<std::sync::atomic::AtomicBool>, on: &mut dyn FnMut(&Progress)) -> Result<Progress> {
+ use std::sync::atomic::Ordering;
use rayon::prelude::*;
const BATCH: usize = 32;
let all: Vec<store::Pending> = store.pending(source, usize::MAX)?.into_iter().filter(|p| p.kind == "picture").collect();
@@ -98,10 +117,14 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on:
let (tx, rx) = std::sync::mpsc::sync_channel::<Result<apple::Ready, (i64, String)>>(BATCH * 8);
let thumbs: Vec<PathBuf> = all.iter().map(|p| store.thumb(p.id)).collect();
let threads = std::thread::available_parallelism().map(|n| n.get().saturating_sub(2).max(2)).unwrap_or(4);
+ let halt = stop.clone();
let decoder = std::thread::spawn(move || {
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().expect("a decoding pool");
pool.install(|| {
all.par_iter().zip(thumbs.par_iter()).for_each_with(tx, |tx, (p, thumb)| {
+ if halt.load(Ordering::Relaxed) {
+ return;
+ }
let r = apple::picture(Path::new(&p.locator), Some(thumb)).map(|(px, w, h)| apple::Ready { item: p.id, t: 0.0, px, w, h }).map_err(|e| (p.id, e));
let _ = tx.send(r);
})
@@ -112,7 +135,7 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on:
let mut prog = Progress { source: source.into(), found: base.found, done: base.done, failed: base.failed, stage: "embedding", ..Progress::default() };
let mut batch: Vec<apple::Ready> = Vec::with_capacity(BATCH);
let mut embedded = 0u64;
- let mut flush = |batch: &mut Vec<apple::Ready>, prog: &mut Progress, store: &mut Store| -> Result<()> {
+ let flush = |batch: &mut Vec<apple::Ready>, prog: &mut Progress, store: &mut Store| -> Result<()> {
if batch.is_empty() {
return Ok(());
}
@@ -127,6 +150,10 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on:
Ok(())
};
for r in rx {
+ if stop.load(Ordering::Relaxed) {
+ prog.stage = "stopped";
+ break;
+ }
match r {
Ok(ready) => {
batch.push(ready);
@@ -153,9 +180,10 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, on:
let _ = decoder.join();
prog.seconds = started.elapsed().as_secs_f64();
prog.per_sec = embedded as f64 / prog.seconds.max(1e-3);
- prog.stage = "done";
+ if prog.stage != "stopped" {
+ prog.stage = "done";
+ }
on(&prog);
prog.newest.clear();
- let _ = (LISTED, DONE);
Ok(prog)
}
diff --git a/systems/index/src/search.rs b/systems/index/src/search.rs
index 888f6299..8d081e5d 100644
--- a/systems/index/src/search.rs
+++ b/systems/index/src/search.rs
@@ -1,11 +1,13 @@
//! Searching the fast pass (docs/index.feature IX3): a query vector against every row of the model's file, brute
//! force over f16 on every core, best `k` kept, one hit per item (its best moment). Rows of removed or changed items
-//! are left out.
+//! are left out. A long-lived searcher grows its rows from the file's tail as batches land, and reads them all again
+//! only after something was removed or changed.
use crate::store::{DIM, Store};
use anyhow::Result;
use rayon::prelude::*;
use std::collections::HashMap;
+use std::io::{Read, Seek, SeekFrom};
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hit {
@@ -13,41 +15,85 @@ pub struct Hit {
pub score: f32,
/// the moment in a video, seconds; 0 for a picture
pub t: f64,
+ pub source: String,
pub kind: String,
pub name: String,
pub locator: String,
pub thumb: String,
}
-/// The rows' vectors as f16 bits, and which item and moment each row is
+/// The rows' vectors as f16 bits, and which item, moment and source each row is (item -1: out of search)
+#[derive(Default)]
pub struct Rows {
pub bits: Vec<u16>,
pub item: Vec<i64>,
pub t: Vec<f64>,
+ src: Vec<u16>,
+ sources: Vec<String>,
}
impl Rows {
pub fn load(store: &Store, model: &str) -> Result<Rows> {
- let raw = std::fs::read(store.vectors(model)).unwrap_or_default();
- let n = raw.len() / (DIM * 2);
- let bits: Vec<u16> = raw[..n * DIM * 2].chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect();
- let mut item = vec![-1i64; n];
- let mut t = vec![0f64; n];
- let mut q = store.db.prepare("SELECT r.row, r.item, r.t FROM rows r JOIN items i ON i.id = r.item WHERE r.model = ?1 AND i.state = 1")?;
- let mut it = q.query(rusqlite::params![model])?;
- while let Some(r) = it.next()? {
- let row: i64 = r.get(0)?;
- if (row as usize) < n {
- item[row as usize] = r.get(1)?;
- t[row as usize] = r.get(2)?;
- }
- }
- Ok(Rows { bits, item, t })
+ let mut r = Rows::default();
+ r.grow(store, model)?;
+ Ok(r)
}
pub fn len(&self) -> usize {
self.item.len()
}
+
+ pub fn is_empty(&self) -> bool {
+ self.item.is_empty()
+ }
+
+ /// Reads the rows written since the last read: the file's tail, up to the last row the list already knows (a
+ /// batch's vectors land in the file just before its rows land in the list). Returns how many it added.
+ pub fn grow(&mut self, store: &Store, model: &str) -> Result<usize> {
+ let have = self.len();
+ let known: Option<i64> = store.db.query_row("SELECT MAX(row) FROM rows WHERE model = ?1", [model], |r| r.get(0))?;
+ let file = store.vectors(model);
+ let on_disk = std::fs::metadata(&file).map(|m| m.len() as usize / (DIM * 2)).unwrap_or(0);
+ let to = on_disk.min(known.map(|k| k as usize + 1).unwrap_or(0));
+ if to <= have {
+ return Ok(0);
+ }
+ let mut raw = vec![0u8; (to - have) * DIM * 2];
+ let mut f = std::fs::File::open(&file)?;
+ f.seek(SeekFrom::Start((have * DIM * 2) as u64))?;
+ f.read_exact(&mut raw)?;
+ self.bits.extend(raw.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])));
+ self.item.resize(to, -1);
+ self.t.resize(to, 0.0);
+ self.src.resize(to, 0);
+ let mut q = store.db.prepare("SELECT r.row, r.item, r.t, i.source FROM rows r JOIN items i ON i.id = r.item WHERE r.model = ?1 AND r.row >= ?2 AND r.row < ?3 AND i.state = 1")?;
+ let mut it = q.query(rusqlite::params![model, have as i64, to as i64])?;
+ while let Some(r) = it.next()? {
+ let row = r.get::<_, i64>(0)? as usize;
+ self.item[row] = r.get(1)?;
+ self.t[row] = r.get(2)?;
+ let s: String = r.get(3)?;
+ self.src[row] = match self.sources.iter().position(|x| *x == s) {
+ Some(i) => i as u16,
+ None => {
+ self.sources.push(s);
+ (self.sources.len() - 1) as u16
+ }
+ };
+ }
+ Ok(to - have)
+ }
+
+ /// An item's vector (its first row: a picture's only one), to find what looks like it
+ pub fn vector(&self, item: i64) -> Option<Vec<f32>> {
+ let i = self.item.iter().position(|&x| x == item)?;
+ Some(self.bits[i * DIM..(i + 1) * DIM].iter().map(|&b| half::f16::from_bits(b).to_f32()).collect())
+ }
+
+ /// How many rows are in search
+ pub fn live(&self) -> usize {
+ self.item.iter().filter(|&&i| i >= 0).count()
+ }
}
fn dot(bits: &[u16], q: &[f32]) -> f32 {
@@ -60,13 +106,20 @@ fn dot(bits: &[u16], q: &[f32]) -> f32 {
acc.iter().sum()
}
-/// The `k` best items for the query, best first
-pub fn search(store: &Store, rows: &Rows, q: &[f32], k: usize) -> Result<Vec<Hit>> {
+/// The `k` best items for the query, best first; `source` keeps one source's
+pub fn search(store: &Store, rows: &Rows, q: &[f32], k: usize, source: Option<&str>) -> Result<Vec<Hit>> {
+ let only = match source {
+ Some(s) => match rows.sources.iter().position(|x| x == s) {
+ Some(i) => Some(i as u16),
+ None => return Ok(vec![]),
+ },
+ None => None,
+ };
let scored: Vec<(usize, f32)> = rows
.bits
.par_chunks_exact(DIM)
.enumerate()
- .filter(|(i, _)| rows.item[*i] >= 0)
+ .filter(|(i, _)| rows.item[*i] >= 0 && only.is_none_or(|s| rows.src[*i] == s))
.map(|(i, v)| (i, dot(v, q)))
.collect();
// best row per item
@@ -83,8 +136,10 @@ pub fn search(store: &Store, rows: &Rows, q: &[f32], k: usize) -> Result<Vec<Hit
let mut q = store.db.prepare_cached("SELECT kind, name, locator FROM items WHERE id = ?1")?;
let mut hits = Vec::with_capacity(top.len());
for (item, i, score) in top {
- let (kind, name, locator): (String, String, String) = q.query_row([item], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;
- hits.push(Hit { item, score, t: rows.t[i], kind, name, locator, thumb: store.thumb(item).to_string_lossy().into_owned() });
+ // removed since the rows were read
+ let Some((kind, name, locator)) = rusqlite::OptionalExtension::optional(q.query_row([item], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))))? else { continue };
+ let source = rows.sources[rows.src[i] as usize].clone();
+ hits.push(Hit { item, score, t: rows.t[i], source, kind, name, locator, thumb: store.thumb(item).to_string_lossy().into_owned() });
}
Ok(hits)
}
diff --git a/systems/index/src/serve.rs b/systems/index/src/serve.rs
new file mode 100644
index 00000000..a031665d
--- /dev/null
+++ b/systems/index/src/serve.rs
@@ -0,0 +1,271 @@
+//! `raea index serve` (docs/index.feature IX13): the index kept open for the feed, one JSON object a line each way.
+//! Each ask on stdin carries an `id` and an `op` and gets one answer with the same id on stdout; the fast pass's
+//! progress comes between them as `{"ev": ...}` lines. Indexing runs on a worker with its own connection and the
+//! Neural Engine model, searches on a searcher that keeps the text tower and the rows loaded, so a search answers
+//! while a drive is still going in.
+//! {"id":1,"op":"add","path":"/Volumes/Photos"} a folder or a drive: listed, then embedded
+//! {"id":2,"op":"search","q":"a red car","k":60,"source":ID} `source` optional: one source's
+//! {"id":3,"op":"similar","item":42,"k":60} what looks like an item
+//! {"id":4,"op":"status"} the sources, what's running and waiting
+//! {"id":5,"op":"remove","source":ID} (or the folder's path)
+//! {"id":6,"op":"stop"} the run going now, and the ones waiting
+//! {"id":7,"op":"warm"} the text tower loaded before the first search
+//! Events: ready {home, model}, progress (lib.rs Progress: stage listing|embedding|done|stopped, newest item ids),
+//! error {root, message}. A thumbnail is home/thumbs/<id % 256>/<id>.jpg.
+
+use crate::search::{self, Rows};
+use crate::store::{MODEL, Store};
+use crate::text::Text;
+use anyhow::{Result, anyhow};
+use serde_json::{Value, json};
+use std::io::{BufRead, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, mpsc};
+use std::time::Instant;
+
+struct Shared {
+ out: Mutex<std::io::Stdout>,
+ /// bumped when rows leave search (a source removed, a file changed), so the searcher reads them all again
+ epoch: AtomicU64,
+ stop: Arc<AtomicBool>,
+ /// the folder going in now, and its source once it's listed
+ running: Mutex<Option<(String, Option<String>)>>,
+ /// folders waiting their turn; a stopped or removed one leaves this list and the worker skips it
+ waiting: Mutex<Vec<String>>,
+}
+
+impl Shared {
+ fn send(&self, v: &Value) {
+ let mut o = self.out.lock().unwrap_or_else(|e| e.into_inner());
+ let _ = writeln!(o, "{v}");
+ let _ = o.flush();
+ }
+
+ fn progress(&self, p: &crate::Progress) {
+ let mut v = serde_json::to_value(p).unwrap_or_default();
+ v["ev"] = "progress".into();
+ self.send(&v);
+ }
+}
+
+enum Find {
+ Words { id: Value, q: String, k: usize, source: Option<String> },
+ Like { id: Value, item: i64, k: usize, source: Option<String> },
+ Warm { id: Value },
+}
+
+pub fn serve(dir: &Path) -> Result<()> {
+ let sh = Arc::new(Shared { out: Mutex::new(std::io::stdout()), epoch: AtomicU64::new(0), stop: Arc::new(AtomicBool::new(false)), running: Mutex::new(None), waiting: Mutex::new(vec![]) });
+ let mut store = Store::open(dir)?;
+ let (jobs, jrx) = mpsc::channel::<PathBuf>();
+ let (finds, frx) = mpsc::channel::<Find>();
+ let worker = {
+ let (sh, dir) = (sh.clone(), dir.to_path_buf());
+ std::thread::spawn(move || work(&sh, &dir, jrx))
+ };
+ let finder = {
+ let (sh, dir) = (sh.clone(), dir.to_path_buf());
+ std::thread::spawn(move || find(&sh, &dir, frx))
+ };
+ // what was there before: each folder listed again (new files in, changed ones redone) and its waiting pictures embedded
+ for s in store.sources()? {
+ if s.kind == "folder" && Path::new(&s.root).is_dir() {
+ sh.waiting.lock().unwrap().push(s.root.clone());
+ let _ = jobs.send(PathBuf::from(&s.root));
+ }
+ }
+ sh.send(&json!({ "ev": "ready", "home": dir, "model": MODEL }));
+ for line in std::io::stdin().lock().lines() {
+ let line = line?;
+ if line.trim().is_empty() {
+ continue;
+ }
+ let ask: Value = match serde_json::from_str(&line) {
+ Ok(v) => v,
+ Err(e) => {
+ sh.send(&json!({ "ev": "error", "message": format!("not JSON: {e}") }));
+ continue;
+ }
+ };
+ let id = ask.get("id").cloned().unwrap_or(Value::Null);
+ match answer(&sh, &mut store, &jobs, &finds, &ask, id.clone()) {
+ Ok(Some(mut v)) => {
+ v["id"] = id;
+ sh.send(&v);
+ }
+ Ok(None) => {}
+ Err(e) => sh.send(&json!({ "id": id, "error": format!("{e:#}") })),
+ }
+ }
+ // the feed went away: the searches asked are answered, the batch in hand is written, then out
+ drop(finds);
+ let _ = finder.join();
+ sh.stop.store(true, Ordering::Relaxed);
+ sh.waiting.lock().unwrap().clear();
+ drop(jobs);
+ let _ = worker.join();
+ Ok(())
+}
+
+fn answer(sh: &Shared, store: &mut Store, jobs: &mpsc::Sender<PathBuf>, finds: &mpsc::Sender<Find>, ask: &Value, id: Value) -> Result<Option<Value>> {
+ let s = |k: &str| ask.get(k).and_then(Value::as_str).map(str::to_string);
+ let k = ask.get("k").and_then(Value::as_u64).unwrap_or(60).clamp(1, 2000) as usize;
+ match ask.get("op").and_then(Value::as_str).unwrap_or("") {
+ "add" => {
+ let path = s("path").ok_or_else(|| anyhow!("add needs a path"))?;
+ let root = std::fs::canonicalize(&path).map_err(|e| anyhow!("{path}: {e}"))?;
+ if !root.is_dir() {
+ anyhow::bail!("{path} isn't a folder");
+ }
+ let r = root.to_string_lossy().into_owned();
+ let going = sh.running.lock().unwrap().as_ref().is_some_and(|(x, _)| *x == r);
+ let mut w = sh.waiting.lock().unwrap();
+ if !going && !w.contains(&r) {
+ w.push(r.clone());
+ jobs.send(root).map_err(|_| anyhow!("the indexer stopped"))?;
+ }
+ Ok(Some(json!({ "ok": true, "root": r })))
+ }
+ "search" => {
+ let q = s("q").filter(|q| !q.trim().is_empty()).ok_or_else(|| anyhow!("search needs words (q)"))?;
+ finds.send(Find::Words { id, q, k, source: s("source") }).map_err(|_| anyhow!("the searcher stopped"))?;
+ Ok(None)
+ }
+ "similar" => {
+ let item = ask.get("item").and_then(Value::as_i64).ok_or_else(|| anyhow!("similar needs an item"))?;
+ finds.send(Find::Like { id, item, k, source: s("source") }).map_err(|_| anyhow!("the searcher stopped"))?;
+ Ok(None)
+ }
+ "warm" => {
+ finds.send(Find::Warm { id }).map_err(|_| anyhow!("the searcher stopped"))?;
+ Ok(None)
+ }
+ "status" => {
+ let running = sh.running.lock().unwrap().clone().map(|(root, source)| json!({ "root": root, "source": source }));
+ let rows = store.counts(None)?.rows;
+ Ok(Some(json!({ "sources": store.sources()?, "running": running, "waiting": *sh.waiting.lock().unwrap(), "rows": rows, "home": store.dir, "model": MODEL })))
+ }
+ "remove" => {
+ let which = s("source").or_else(|| s("path")).ok_or_else(|| anyhow!("remove needs a source"))?;
+ let canon = std::fs::canonicalize(&which).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| which.clone());
+ let Some(source) = store.find(&which)?.or(store.find(&canon)?) else { anyhow::bail!("no source {which}") };
+ let root: String = store.db.query_row("SELECT root FROM sources WHERE id = ?1", [&source], |r| r.get(0))?;
+ sh.waiting.lock().unwrap().retain(|r| *r != root);
+ if sh.running.lock().unwrap().as_ref().is_some_and(|(r, s)| *r == root || s.as_deref() == Some(source.as_str())) {
+ sh.stop.store(true, Ordering::Relaxed);
+ }
+ let n = store.remove(&source)?;
+ sh.epoch.fetch_add(1, Ordering::Relaxed);
+ Ok(Some(json!({ "ok": true, "source": source, "removed": n })))
+ }
+ "stop" => {
+ sh.waiting.lock().unwrap().clear();
+ sh.stop.store(true, Ordering::Relaxed);
+ Ok(Some(json!({ "ok": true })))
+ }
+ op => anyhow::bail!("no op {op:?}: add, search, similar, warm, status, remove, stop"),
+ }
+}
+
+/// The worker: one folder at a time, listed then embedded, the Neural Engine model loaded on its first picture
+fn work(sh: &Shared, dir: &Path, jobs: mpsc::Receiver<PathBuf>) {
+ let mut store = match Store::open(dir) {
+ Ok(s) => s,
+ Err(e) => return sh.send(&json!({ "ev": "error", "message": format!("the index at {}: {e:#}", dir.display()) })),
+ };
+ #[cfg(target_vendor = "apple")]
+ let mut model: Option<crate::apple::Model> = None;
+ for root in jobs {
+ let r = root.to_string_lossy().into_owned();
+ {
+ let mut w = sh.waiting.lock().unwrap();
+ let Some(i) = w.iter().position(|x| *x == r) else { continue };
+ w.remove(i);
+ *sh.running.lock().unwrap() = Some((r.clone(), None));
+ sh.stop.store(false, Ordering::Relaxed);
+ }
+ let done = (|| -> Result<()> {
+ let l = crate::list_folder(&mut store, &root, &mut |p| sh.progress(p))?;
+ if l.changed > 0 {
+ sh.epoch.fetch_add(1, Ordering::Relaxed);
+ }
+ *sh.running.lock().unwrap() = Some((r.clone(), Some(l.source.clone())));
+ if sh.stop.load(Ordering::Relaxed) {
+ return Ok(());
+ }
+ #[cfg(target_vendor = "apple")]
+ {
+ if model.is_none() {
+ model = Some(crate::apple::Model::load(&crate::image_package()).map_err(anyhow::Error::msg)?);
+ }
+ crate::embed_pictures(&mut store, model.as_ref().expect("loaded"), &l.source, &sh.stop, &mut |p| sh.progress(p))?;
+ Ok(())
+ }
+ #[cfg(not(target_vendor = "apple"))]
+ anyhow::bail!("the fast pass runs on a Mac for now")
+ })();
+ if let Err(e) = done {
+ sh.send(&json!({ "ev": "error", "root": r, "message": format!("{e:#}") }));
+ }
+ *sh.running.lock().unwrap() = None;
+ }
+}
+
+/// The searcher: the text tower loaded once, the rows grown from the file's tail before each search
+fn find(sh: &Shared, dir: &Path, finds: mpsc::Receiver<Find>) {
+ let store = match Store::open(dir) {
+ Ok(s) => s,
+ Err(e) => return sh.send(&json!({ "ev": "error", "message": format!("the index at {}: {e:#}", dir.display()) })),
+ };
+ let mut text: Option<Text> = None;
+ let mut rows = Rows::default();
+ let mut seen = u64::MAX;
+ let tower = |text: &mut Option<Text>| -> Result<f64> {
+ if text.is_some() {
+ return Ok(0.0);
+ }
+ let t = Instant::now();
+ let (m, tok) = crate::text_files();
+ *text = Some(Text::load(&m, &tok)?);
+ Ok(t.elapsed().as_secs_f64() * 1e3)
+ };
+ for f in finds {
+ let id = match &f {
+ Find::Words { id, .. } | Find::Like { id, .. } | Find::Warm { id } => id.clone(),
+ };
+ let r = (|| -> Result<Value> {
+ let e = sh.epoch.load(Ordering::Relaxed);
+ if e != seen {
+ rows = Rows::load(&store, MODEL)?;
+ seen = e;
+ } else {
+ rows.grow(&store, MODEL)?;
+ }
+ match f {
+ Find::Warm { .. } => Ok(json!({ "ok": true, "load_ms": tower(&mut text)?, "rows": rows.live() })),
+ Find::Words { q, k, source, .. } => {
+ let load = tower(&mut text)?;
+ let t = Instant::now();
+ let v = text.as_mut().expect("loaded").embed(&q)?;
+ let words = t.elapsed().as_secs_f64() * 1e3;
+ let hits = search::search(&store, &rows, &v, k, source.as_deref())?;
+ Ok(json!({ "hits": hits, "rows": rows.live(), "ms": { "load": load, "words": words, "search": t.elapsed().as_secs_f64() * 1e3 - words } }))
+ }
+ Find::Like { item, k, source, .. } => {
+ let v = rows.vector(item).ok_or_else(|| anyhow!("item {item} isn't searchable yet"))?;
+ let t = Instant::now();
+ let hits: Vec<search::Hit> = search::search(&store, &rows, &v, k + 1, source.as_deref())?.into_iter().filter(|h| h.item != item).take(k).collect();
+ Ok(json!({ "hits": hits, "rows": rows.live(), "ms": { "search": t.elapsed().as_secs_f64() * 1e3 } }))
+ }
+ }
+ })();
+ match r {
+ Ok(mut v) => {
+ v["id"] = id;
+ sh.send(&v);
+ }
+ Err(e) => sh.send(&json!({ "id": id, "error": format!("{e:#}") })),
+ }
+ }
+}
diff --git a/systems/index/src/store.rs b/systems/index/src/store.rs
index baf14635..e7e21426 100644
--- a/systems/index/src/store.rs
+++ b/systems/index/src/store.rs
@@ -42,6 +42,18 @@ pub struct Counts {
pub rows: u64,
}
+/// A source and what it holds
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct Source {
+ pub id: String,
+ pub kind: String,
+ pub root: String,
+ pub label: String,
+ pub found: u64,
+ pub done: u64,
+ pub failed: u64,
+}
+
/// An item waiting for the fast pass
#[derive(Debug, Clone)]
pub struct Pending {
@@ -55,7 +67,7 @@ impl Store {
pub fn open(dir: &Path) -> Result<Store> {
std::fs::create_dir_all(dir.join("thumbs")).with_context(|| format!("making {}", dir.display()))?;
let db = Connection::open(dir.join("index.db"))?;
- db.execute_batch("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?;
+ db.execute_batch("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 10000;")?;
db.execute_batch(SCHEMA)?;
Ok(Store { dir: dir.to_path_buf(), db })
}
@@ -77,28 +89,36 @@ impl Store {
if let Some(id) = self.db.query_row("SELECT id FROM sources WHERE kind = ?1 AND root = ?2", params![kind, root], |r| r.get(0)).optional()? {
return Ok(id);
}
- let n: i64 = self.db.query_row("SELECT COUNT(*) FROM sources", [], |r| r.get(0))?;
- let id = format!("ix{}-{n}", kind.chars().next().unwrap_or('s'));
+ // never a removed source's id again
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
+ let id = format!("ix{}-{stamp:x}", kind.chars().next().unwrap_or('s'));
self.db.execute("INSERT INTO sources (id, kind, root, label, created) VALUES (?1, ?2, ?3, ?4, strftime('%s','now'))", params![id, kind, root, label])?;
Ok(id)
}
- /// Lists items in one transaction: new ones as LISTED, a changed one (size or mtime) back to LISTED; the rest kept
- pub fn list(&mut self, source: &str, items: &[crate::Found]) -> Result<usize> {
+ /// Lists items in one transaction: new ones as LISTED, a changed one (size or mtime) back to LISTED with its old
+ /// rows dropped; the rest kept. Returns how many were new and how many changed.
+ pub fn list(&mut self, source: &str, items: &[crate::Found]) -> Result<(usize, usize)> {
let tx = self.db.transaction()?;
- let mut added = 0;
+ let (mut added, mut changed) = (0, 0);
{
- let mut up = tx.prepare_cached(
- "INSERT INTO items (source, locator, kind, name, size, mtime, taken, w, h, dur) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
- ON CONFLICT (source, locator) DO UPDATE SET size = excluded.size, mtime = excluded.mtime, state = 0, err = NULL
- WHERE items.size != excluded.size OR items.mtime != excluded.mtime",
- )?;
+ let mut had = tx.prepare_cached("SELECT id, size, mtime FROM items WHERE source = ?1 AND locator = ?2")?;
+ let mut add = tx.prepare_cached("INSERT INTO items (source, locator, kind, name, size, mtime, taken, w, h, dur) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)")?;
+ let mut redo = tx.prepare_cached("UPDATE items SET size = ?2, mtime = ?3, state = 0, err = NULL WHERE id = ?1")?;
+ let mut drop = tx.prepare_cached("DELETE FROM rows WHERE item = ?1")?;
for f in items {
- added += up.execute(params![source, f.locator, f.kind, f.name, f.size as i64, f.mtime, f.taken, f.w, f.h, f.dur])?;
+ match had.query_row(params![source, f.locator], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?, r.get::<_, i64>(2)?))).optional()? {
+ None => added += add.execute(params![source, f.locator, f.kind, f.name, f.size as i64, f.mtime, f.taken, f.w, f.h, f.dur])?,
+ Some((id, size, mtime)) if size != f.size as i64 || mtime != f.mtime => {
+ drop.execute([id])?;
+ changed += redo.execute(params![id, f.size as i64, f.mtime])?;
+ }
+ Some(_) => {}
+ }
}
}
tx.commit()?;
- Ok(added)
+ Ok((added, changed))
}
pub fn pending(&self, source: &str, limit: usize) -> Result<Vec<Pending>> {
@@ -140,6 +160,40 @@ impl Store {
Ok(())
}
+ /// Every source with what it holds, oldest first
+ pub fn sources(&self) -> Result<Vec<Source>> {
+ let mut q = self.db.prepare(
+ "SELECT s.id, s.kind, s.root, s.label, COUNT(i.id), COALESCE(SUM(i.state = 1), 0), COALESCE(SUM(i.state = 2), 0)
+ FROM sources s LEFT JOIN items i ON i.source = s.id GROUP BY s.id ORDER BY s.created, s.id",
+ )?;
+ let rows = q.query_map([], |r| {
+ Ok(Source { id: r.get(0)?, kind: r.get(1)?, root: r.get(2)?, label: r.get(3)?, found: r.get::<_, i64>(4)? as u64, done: r.get::<_, i64>(5)? as u64, failed: r.get::<_, i64>(6)? as u64 })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// A source by its id, or by its root (the folder someone added)
+ pub fn find(&self, id_or_root: &str) -> Result<Option<String>> {
+ Ok(self.db.query_row("SELECT id FROM sources WHERE id = ?1 OR root = ?1", [id_or_root], |r| r.get(0)).optional()?)
+ }
+
+ /// A source gone from the index: its items, their rows (left in the vectors' file, out of search) and thumbnails
+ pub fn remove(&mut self, source: &str) -> Result<u64> {
+ let ids: Vec<i64> = {
+ let mut q = self.db.prepare("SELECT id FROM items WHERE source = ?1")?;
+ q.query_map([source], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?
+ };
+ let tx = self.db.transaction()?;
+ tx.execute("DELETE FROM rows WHERE item IN (SELECT id FROM items WHERE source = ?1)", [source])?;
+ tx.execute("DELETE FROM items WHERE source = ?1", [source])?;
+ tx.execute("DELETE FROM sources WHERE id = ?1", [source])?;
+ tx.commit()?;
+ for id in &ids {
+ let _ = std::fs::remove_file(self.thumb(*id));
+ }
+ Ok(ids.len() as u64)
+ }
+
pub fn counts(&self, source: Option<&str>) -> Result<Counts> {
let (w, p) = match source {
Some(s) => ("WHERE source = ?1", vec![s.to_string()]),