From 305dbdd536ec546fca659e67d42bccd8270cb26c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 09:41:44 -0300 Subject: [PATCH] Show the code of #15 since the last review Everything #15 changes after the head the last review covered, apart from the translations. This branch is for review only and is not merged. --- Cargo.lock | 29 +- Cargo.toml | 27 + README.md | 4 +- approved-crates.txt | 2 + apps/big-docinfo/src/main.rs | 25 +- apps/big-docinfo/tests/cli.rs | 25 + apps/big-search/Cargo.toml | 1 + apps/big-search/DESIGN.md | 179 +++- apps/big-search/fuzz/README.md | 2 +- apps/big-search/packaging/big-search.service | 7 +- apps/big-search/src/browser_downloads.rs | 1 - apps/big-search/src/catalogue.rs | 220 ++-- apps/big-search/src/catalogue/tests.rs | 100 +- apps/big-search/src/cjk_tokenizer.rs | 6 +- apps/big-search/src/config.rs | 10 +- apps/big-search/src/config_cmd.rs | 37 +- apps/big-search/src/content.rs | 176 ++-- apps/big-search/src/content/tests.rs | 118 ++- apps/big-search/src/content_dedupe.rs | 40 +- apps/big-search/src/extract.rs | 176 ++-- apps/big-search/src/extract/tests.rs | 103 +- apps/big-search/src/extract_pdf.rs | 12 +- apps/big-search/src/fold.rs | 151 +++ apps/big-search/src/history.rs | 392 ++++++-- apps/big-search/src/history/disk.rs | 105 +- apps/big-search/src/history/eligibility.rs | 96 +- apps/big-search/src/history/retention.rs | 24 +- apps/big-search/src/history/store.rs | 297 +++++- apps/big-search/src/history/tests.rs | 487 ++++++++- apps/big-search/src/history/worker.rs | 389 ++++++-- apps/big-search/src/index.rs | 349 +++---- apps/big-search/src/index/tests.rs | 223 +++++ apps/big-search/src/index_cmd.rs | 157 ++- apps/big-search/src/ipc.rs | 94 +- apps/big-search/src/ipc/tests.rs | 2 - apps/big-search/src/lib.rs | 2 + apps/big-search/src/main.rs | 102 +- apps/big-search/src/meta.rs | 36 +- apps/big-search/src/mime.rs | 6 +- apps/big-search/src/mounts.rs | 97 +- apps/big-search/src/nosync_dir.rs | 34 +- apps/big-search/src/origin.rs | 549 +++++----- apps/big-search/src/origin/downloads.rs | 2 - apps/big-search/src/origin/tests.rs | 308 ++++++ apps/big-search/src/query.rs | 35 +- apps/big-search/src/query/both.rs | 2 +- apps/big-search/src/query/content.rs | 2 +- apps/big-search/src/query/listing.rs | 12 +- apps/big-search/src/query/names.rs | 7 +- apps/big-search/src/query/names/tests.rs | 3 +- apps/big-search/src/query/tests.rs | 61 +- apps/big-search/src/scan.rs | 189 ++-- apps/big-search/src/scan/scope.rs | 478 +++++++-- apps/big-search/src/scan_roots.rs | 10 - apps/big-search/src/settings.rs | 211 +++- apps/big-search/src/test_env.rs | 42 + apps/big-search/src/throttle.rs | 195 +++- apps/big-search/src/watch.rs | 667 ++++++------- apps/big-search/src/watch/content_backfill.rs | 215 +++- apps/big-search/src/watch/event_batch.rs | 189 +++- apps/big-search/src/watch/reconcile.rs | 238 +++++ apps/big-search/src/watch/start.rs | 10 +- apps/big-search/src/watch/tests.rs | 216 ++++ apps/big-search/src/watch/watches.rs | 96 +- apps/big-search/tests/cli.rs | 163 ++- apps/big-search/tests/daemon/mod.rs | 78 +- apps/big-search/tests/daemon_control.rs | 666 +++++++++++-- apps/big-search/tests/daemon_restart.rs | 145 ++- apps/big-search/tests/daemon_scope.rs | 543 ++++++++++ apps/big-search/tests/daemon_singleton.rs | 24 +- apps/big-search/tests/history_sequences.rs | 942 ++++++++++++++++++ apps/big-search/tests/history_store.rs | 383 ++++++- apps/big-search/tests/origin_ipc.rs | 36 +- clippy.toml | 2 + crates/foundation/big-indexd-client/README.md | 2 +- .../big-indexd-client/src/client.rs | 93 +- .../foundation/big-indexd-client/src/lib.rs | 23 +- .../big-indexd-client/tests/wire.jsonl | 4 +- .../foundation/big-search-config/src/edit.rs | 2 +- .../foundation/big-search-config/src/lib.rs | 7 +- rules/document-open-regular.yml | 38 + rules/rust-sqlite-rows-dropped.yml | 40 + 82 files changed, 8861 insertions(+), 2410 deletions(-) create mode 100644 apps/big-search/src/fold.rs create mode 100644 apps/big-search/src/index/tests.rs create mode 100644 apps/big-search/src/origin/tests.rs create mode 100644 apps/big-search/src/watch/reconcile.rs create mode 100644 apps/big-search/src/watch/tests.rs create mode 100644 apps/big-search/tests/daemon_scope.rs create mode 100644 apps/big-search/tests/history_sequences.rs create mode 100644 rules/document-open-regular.yml create mode 100644 rules/rust-sqlite-rows-dropped.yml diff --git a/Cargo.lock b/Cargo.lock index 1551a92..aa7a5a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,6 +151,7 @@ dependencies = [ "rusqlite", "serde", "serde_json", + "signal-hook", "symphonia", "tantivy", "unicode-normalization", @@ -439,7 +440,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1287,7 +1288,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1372,6 +1373,26 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -1724,7 +1745,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2001,7 +2022,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a09eccf..5e4071e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,30 @@ exit = "deny" todo = "deny" undocumented_unsafe_blocks = "deny" unwrap_used = "deny" +unimplemented = "deny" +unnecessary_safety_comment = "deny" +allow_attributes_without_reason = "deny" +unused_result_ok = "warn" +significant_drop_in_scrutinee = "warn" +unchecked_time_subtraction = "warn" +read_zero_byte_vec = "warn" +path_buf_push_overwrite = "warn" +debug_assert_with_mut_call = "warn" +unused_peekable = "warn" +redundant_clone = "warn" +implicit_clone = "warn" +cloned_instead_of_copied = "warn" +inefficient_to_string = "warn" +unnecessary_join = "warn" +manual_instant_elapsed = "warn" +large_futures = "warn" +cast_lossless = "warn" +non_std_lazy_statics = "warn" +missing_errors_doc = "warn" +missing_panics_doc = "warn" +ignore_without_reason = "warn" +should_panic_without_expect = "warn" +redundant_test_prefix = "warn" [workspace.package] edition = "2024" @@ -37,3 +61,6 @@ debug = "line-tables-only" lto = "thin" codegen-units = 1 strip = "symbols" + +[workspace.lints.cargo] +unused_dependencies = "deny" diff --git a/README.md b/README.md index b122415..fceafa3 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,8 @@ Pre-release: the socket protocol, the configuration file and the on-disk format searchable without a dictionary. - **Live index:** inotify on every visible folder, so a saved file is searchable within seconds. A restart finds files created, renamed or deleted - while the service was down without reading every file; `big-search rescan` - also rereads files edited in place. + while the service was down without reading every file, then, a minute + later, walks the folders once in the background for files edited in place. - **Earlier versions:** on filesystems with reflinks (Btrfs, XFS) a copy of a document is kept before each save, within a disk budget. - **Origin:** where a file came from (a browser download, a copy, a move), diff --git a/approved-crates.txt b/approved-crates.txt index 4f3a5aa..1cc7a18 100644 --- a/approved-crates.txt +++ b/approved-crates.txt @@ -147,6 +147,8 @@ serde_json serde_spanned serde-tuple-vec-map shlex +signal-hook +signal-hook-registry simd-adler32 sketches-ddsketch slab diff --git a/apps/big-docinfo/src/main.rs b/apps/big-docinfo/src/main.rs index 3a55598..39c763b 100644 --- a/apps/big-docinfo/src/main.rs +++ b/apps/big-docinfo/src/main.rs @@ -31,8 +31,8 @@ fn main() -> ExitCode { // SAFETY: called once, before any thread exists that could read the locale. unsafe { gettextrs::setlocale(gettextrs::LocaleCategory::LcAll, "") }; // Without a catalog every message stays in English, the source language. - gettextrs::bindtextdomain("big-docinfo", LOCALE_DIR).ok(); - gettextrs::textdomain("big-docinfo").ok(); + let _ = gettextrs::bindtextdomain("big-docinfo", LOCALE_DIR); + let _ = gettextrs::textdomain("big-docinfo"); // Messages are written for the person reading the dialog: one sentence with // the cause and what to do, no paths or error chains. match run() { @@ -76,11 +76,22 @@ enum Output { } fn describe(path: &Path, output: Output) -> Result<()> { - let file = big_search::extract::described(path).with_context(|| { - gettext( - "This file has no readable text: its type is not supported, or it is a scanned PDF.", - ) - })?; + let Some(file) = big_search::extract::described(path) else { + // Extraction reads no cause back; opening the file tells an unreadable + // one from a type without text. + bail!(match std::fs::File::open(path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + gettext("This file is no longer there: it was moved or deleted.") + } + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + gettext("You do not have permission to read this file.") + } + Err(_) => gettext("This file could not be read."), + Ok(_) => gettext( + "This file has no readable text: its type is not supported, or it is a scanned PDF.", + ), + }); + }; let ext = extension(path); let hints = Hints { declared_title: file.declared_title.as_deref(), diff --git a/apps/big-docinfo/tests/cli.rs b/apps/big-docinfo/tests/cli.rs index 022be35..17f3c21 100644 --- a/apps/big-docinfo/tests/cli.rs +++ b/apps/big-docinfo/tests/cli.rs @@ -167,3 +167,28 @@ fn report_escapes_control_characters() { fn usage_error_exits_two() { assert_eq!(run(&["--bogus", "x", "y"]).status.code(), Some(2)); } + +/// The dialog names why a file gave no text: gone, not readable by this user, +/// or a type with no text to read. +#[test] +fn unreadable_file_cause_named() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("unreadable"); + let locked = dir.join("locked.txt"); + fs::write(&locked, CONTRACT).expect("write"); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod"); + let opaque = dir.join("opaque.bin"); + fs::write(&opaque, [0u8, 1, 2, 3]).expect("write"); + let cases = [ + (dir.join("missing.txt"), "moved or deleted"), + (locked, "permission"), + (opaque, "no readable text"), + ]; + for (file, cause) in &cases { + let out = run(&[arg(file)]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", file.display()); + assert!(stderr.contains(cause), "{}: {stderr}", file.display()); + } + fs::remove_dir_all(dir).expect("cleanup"); +} diff --git a/apps/big-search/Cargo.toml b/apps/big-search/Cargo.toml index 364e1f5..f122562 100644 --- a/apps/big-search/Cargo.toml +++ b/apps/big-search/Cargo.toml @@ -27,6 +27,7 @@ quick-xml = { version = "0.42.0", features = ["escape-html"] } rusqlite = { version = "0.43.0", default-features = false, features = ["cache"] } serde = { version = "1.0.228", features = ["derive"] } serde_json = { version = "1.0.150" } +signal-hook = { version = "0.4.6" } symphonia = { version = "0.6", default-features = false, features = ["mp3", "isomp4", "mkv", "ogg", "flac", "wav"] } # Only the mmap directory and the store's lz4: the default stemmer, stopword # lists and columnar zstd (a C library) go unused. diff --git a/apps/big-search/DESIGN.md b/apps/big-search/DESIGN.md index f89c7f4..60349a8 100644 --- a/apps/big-search/DESIGN.md +++ b/apps/big-search/DESIGN.md @@ -72,8 +72,8 @@ runtime. big-search CLI, settings page, other BigLinux programs ``` -A query never waits for extraction, and indexing runs on CPU time nobody else -wants (section 7). +A query never waits for extraction, and indexing yields the CPU to queries +(section 7). | Module | Owns | |---|---| @@ -108,7 +108,8 @@ The name index holds one document per visible file: The content index holds `path` and `body`. `body` stores no text and keeps either document lists or term frequencies (`content_index_mode`, `auto` by -default); changing the mode changes the schema and recreates the content index. +default). `auto` chooses only when the content index is created and then keeps +what it holds; setting `basic` or `freqs` to the other detail recreates it. Keeping the two apart lets a name schema change rebuild only the name index: the content rows stay unless the content index is empty. @@ -158,7 +159,7 @@ tantivy. ### Name search Names are folded once, before the grams (`index::name_text` over -`extract::fold_lower`: precomposed or decomposed accents, Latin through +`fold::fold_lower`: precomposed or decomposed accents, Latin through tantivy's `AsciiFoldingFilter`, ё to е, Greek tonos and final sigma, separators as spaces and a space at each end). The post-filter reads the same text, so recall and verification agree. @@ -218,7 +219,7 @@ filter, and counts its total from the postings up to a ceiling ### Folding and scripts -Every text is put in NFKC before anything else reads it (`extract::compose`, +Every text is put in NFKC before anything else reads it (`fold::compose`, used by `fold_lower` and by the content tokenizer, so names, pages, content and queries agree): Korean syllables written as jamo, kana with a separate voicing mark (macOS names, some PDFs), halfwidth katakana, Arabic presentation forms, @@ -230,7 +231,7 @@ this finds 100 % of Korean NFD documents (0 % without), and of Japanese NFD and halfwidth documents (79 % and 37 % without), with no other result changed. Content words are folded at index time like names (`index::ScriptFold` over -`extract::fold_script_into`, then ASCII folding): combining marks, ё, Greek +`fold::fold_script_into`, then ASCII folding): combining marks, ё, Greek accents and final sigma, Arabic hamza alef, alef maqsura and Persian yeh, Persian kaf, ta marbuta as heh, vowel signs, tatweel and the article. The tokenizer keeps combining marks inside a word, so a decomposed accent does not @@ -289,10 +290,23 @@ store, 1.6 MB of stored paths, so it stays as is. ## 4. Scan `scan.rs` walks each root with the `ignore` crate's `WalkBuilder`, the walker -behind `fd` and `rg`: hidden entries are skipped, every gitignore source applies -(the repository's, the global one, `.git/info/exclude`, parent folders), and the -effective ignore file, the built-in defaults followed by the user's -`~/.config/big-search/ignore` so the user's lines win, takes precedence. +behind `fd` and `rg`, with its own filters off: one decision, `scan::Scope`, +judges each entry, and the watcher and a forced reindex ask it about each +folder from below the source holding a path down to the path, so no pass keeps +what another leaves out. Hidden entries are skipped; the effective ignore file, +the built-in defaults followed by the user's `~/.config/big-search/ignore` so +the user's lines win, comes first, so no folder's file brings back what it +leaves out; then the first ignore file with an opinion decides: the `.ignore` +files of the folders above the entry, nearest first, then, inside a work tree +(a folder holding `.git`, or `.jj` for a Jujutsu repository), its `.gitignore` +files, its `info/exclude` and the global excludes file, which git anchors at +the root of the work tree. The effective rules are anchored at +the source holding each entry, so a source nested in another reads +`/Archive/` as its own `Archive`. A source itself is always in scope and +nothing above it is tested: a `.gitignore` above a source speaks only for what +lies below it. The walk reads each folder's files once on the way down; the +watcher reads them only for a path new to the catalogue. The global excludes +file is read once per run, as the effective rules are. Symlinks are never followed during the walk; a symlinked folder at the top of a root is resolved into a root of its own by `scan_roots::resolve_roots` according to the symlink policy, and network mounts, virtual mounts and operating-system @@ -311,10 +325,16 @@ hidden and gitignored churn never wakes the daemon. none for what it held, so the tree goes as one `dir` term in the name index and one key range in the catalogue, never read into memory; its content documents follow through the orphan prune of the next backfill passes. -- At most 16,384 events wait for the watcher (`MAX_QUEUED_EVENTS`), so a backup - or a recursive copy cannot queue its whole tree in memory. Past that, or when - the kernel's own queue overflows, the events are dropped and the watcher - rescans every root. +- What the inotify thread hears waits in one batch the watcher takes whole, + one entry per path however often it changes, in memory only: what a stop + loses, the next start's catch-up or walk finds. Past 16,384 paths + (`MAX_PATHS`) they collapse into their folders, each walked whole, so a + backup or a recursive copy cannot hold its whole tree in memory. Past 256 + folders (`MAX_FOLDERS`), or when the kernel's own queue overflows, the batch + is dropped and the watcher rescans every root; the log tells the two apart. +- The inotify thread runs in the indexer's idle class (section 7), so intake + yields the CPU to queries; under sustained load the kernel's queue may + overflow into that rescan. ## 6. Extraction @@ -405,10 +425,15 @@ candidate should a crate replace the subprocess. ## 7. Throttle `throttle::lower_priority` is called by the watcher, the content workers, the -history worker and a foreground reindex. It moves the calling thread into the -indexer's cgroup, which has `cpu.idle`, and gives it `SCHED_IDLE` with a -utilization clamp of 512 out of 1024, nice 19 as the fallback, and -`IOPRIO_CLASS_IDLE`; the programs it starts inherit all of it. The query +history worker, a foreground reindex and the short-lived thread that starts +the inotify reader (`throttle::spawn_lowered`). It moves the calling thread +into the indexer's cgroup, which has `cpu.idle`, and gives it `SCHED_IDLE` +with a utilization clamp of 512 out of 1024, nice 19 as the fallback, and +`IOPRIO_CLASS_IDLE`; the threads and programs it starts inherit all of it. +The cgroup carries the same clamp (`cpu.uclamp.max`), since the unit's +`RestrictRealtime=yes` refuses `sched_setattr` and the thread then gets +`SCHED_IDLE` through `sched_setscheduler`, without a clamp of its own; the log +says once whether the cgroup's clamp covers it. The query threads keep a normal program's weight. The goal is that indexing is never the cause of a perceptible slowdown. @@ -419,23 +444,38 @@ Measured on an i5-13400 (6 P and 4 E cores, SMT, `intel_cpufreq` with |---|---| | nice 19, unit `CPUWeight=20` | 27 % | | `SCHED_IDLE`, unit `CPUWeight=20` | 32 % | -| unit `CPUWeight=idle`, or the indexer's own `cpu.idle` group | about 0 to 1 % | +| unit `CPUWeight=idle` | about 0 to 1 % | +| the indexer's own `cpu.idle` group, unit at its normal weight | 46 % | | on the core's SMT sibling, any policy | 42 to 50 % | -A thread's policy only counts inside its cgroup, so the unit's weight decides -against other programs. Making the whole unit idle costs the searches: with 16 -saturated CPUs a 5000-hit query took 412 to 831 ms instead of 109 to 162 ms. So -the indexer gets a group of its own, in cgroup v2's threaded mode, which lets -the threads of one process sit in different groups. The unit delegates the cpu -controller (`Delegate=cpu`, `DelegateSubgroup=main`, and -`ProtectControlGroups=private` so the daemon writes only inside its own -namespace); the process and the query threads stay in `main`, and -`throttle::prepare_idle_cgroup` makes `main/index` threaded with `cpu.idle`, or -the lowest `cpu.weight` before Linux 5.15. With it, on 16 saturated CPUs, the -same queries take what they take on an idle machine (77 to 83 ms by name, 14 to -15 ms by content), and `pdftotext` starts in `main/index`. Started without -delegation, from a terminal, the daemon leaves cgroups alone and the thread -policies still apply. +A thread's policy only counts inside its cgroup, and a group's `cpu.idle` only +against its siblings, so the unit's weight decides against other programs. +Making the whole unit idle costs the searches: with 16 saturated CPUs a 5000-hit +query took 412 to 831 ms instead of 109 to 162 ms. So the indexer gets a group +of its own, in cgroup v2's threaded mode, which lets the threads of one process +sit in different groups. The unit delegates the cpu controller (`Delegate=cpu`, +`DelegateSubgroup=main`, and `ProtectControlGroups=private` so the daemon writes +only inside its own namespace); the process and the query threads stay in +`main`, and `throttle::prepare_idle_cgroup` makes `main/index` threaded with +`cpu.idle`, or the lowest `cpu.weight` before Linux 5.15. With it, on 16 +saturated CPUs, the same queries take what they take on an idle machine (77 to +83 ms by name, 14 to 15 ms by content), and `pdftotext` starts in `main/index`. +Started without delegation, from a terminal, the daemon leaves cgroups alone and +the thread policies still apply. + +So indexing yields to the daemon's own queries, and the unit as a whole, +indexing included, competes with other programs at its normal CPU weight. A +lower unit weight costs the searches more than it gives back. Measured on the +notebook with 8 CPU loops in another unit and 20,000 new files to index: + +| Unit weight | Indexed in | Search median, max | +|---|---|---| +| normal | 11 to 12 s, about 7 % of the machine | 14 to 25 ms, 327 to 549 ms | +| `CPUWeight=20` | 32 s | 22 ms, 2848 ms | +| `CPUWeight=idle` | 202 files in 600 s | 186 ms, 15360 ms | + +Without load the files were indexed in 3.6 to 4.8 s and searches took 5 to +8 ms. On every stop systemd logs "Failed to kill control group …, ignoring: Operation not supported": the kernel refuses `cgroup.kill` and process listing in a @@ -448,7 +488,7 @@ hardware (`throttle::topology`: physical cores and SMT over the CPUs the process may use); the scheduler gives each busy program a core of its own while it can, so the free cores are the cores minus the CPUs the others kept busy during the batch. Measured on machines simulated with `taskset` on P-core pairs, a CPU loop -in a program's place and two workers flat out in an idle cgroup: +in a program's place and two workers flat out in a `cpu.idle` cgroup beside it: | Machine | Program loses | |---|---| @@ -457,12 +497,14 @@ in a program's place and two workers flat out in an idle cgroup: | SMT, one free core short | 23 to 28 % | | SMT, no free core | 42 to 49 % at 100 % duty, 17 to 24 % at 50 %, 2 to 12 % at 20 % | -So without SMT the CPU never makes the backfill wait. With SMT it runs at a -20 % duty cycle when the free cores are fewer than its workers, and rests 30 s -when none is free. Memory pressure, its own and others' I/O pressure (most disk -schedulers ignore I/O priority) and battery slow it on any machine; the duty -cycle is 80 % on a calm machine, then 50 %, 20 % and a 30 s rest. Its own CPU -stall is not a signal: at idle priority it only says that others are busy. +So without SMT the CPU never makes the backfill wait: a worker sharing a CPU +with a program in another unit takes only the unit's share of it, as above. With +SMT it runs at a 20 % duty cycle when the free cores are fewer than its workers, +and rests 30 s when none is free. Memory pressure, its own and others' I/O +pressure (most disk schedulers ignore I/O priority) and battery slow it on any +machine; the duty cycle is 80 % on a calm machine, then 50 %, 20 % and a 30 s +rest. Its own CPU stall is not a signal: at idle priority it only says that +others are busy. The duty cycle follows the CPU time the service used in a batch, not the batch's wall time: at idle priority on a busy machine a 250-file batch took @@ -528,7 +570,10 @@ The catch-up then compares: A file rewritten in place changes no folder, an edited `.gitignore` or `.ignore` inside a source changes no fingerprint, and joining a group changes no folder: -all three wait for the next walk, `big-search rescan`. +all three wait for the walk such a start runs once, a minute after it, at the +watcher's background priority, or for `big-search rescan`. Like a rescan, that +walk drops the run record until it ends, so a stop during it makes the next +start walk. Mounts change no folder either. The daemon holds `/proc/self/mountinfo` open and wakes only when the kernel flags a change on it: a disk mounted or unmounted @@ -536,6 +581,14 @@ in or above a source starts a rescan, and a source that comes or goes (a removab disk plugged in) changes the roots the daemon started with, so it exits with status 75 and the unit starts it again (`RestartForceExitStatus=75`). +That exit and a stop (SIGTERM from the service manager, or SIGINT) wait for the +watcher: after the events already queued, it gathers what the kernel reports +for one more debounce window, applies it, and lets the versions worker note +every save it was sent, so a document saved just before a logout keeps its +versions where a kill would leave them parked at the next start. A walk or the +start's sync can hold the watcher longer, so the daemon exits after 5 s +without it. + The settings are conservative for old machines: `cache_size=-2048` (2 MiB), file-backed temporary storage (`SQLITE_TMPDIR` points at the data folder), and a 64 MiB mmap window. @@ -601,9 +654,10 @@ or `0`, `false`, `no` or `off`, in any case; any other value is ignored. | `BIG_SEARCH_BENCH` | prints timings from `reindex` | Debug builds and tests also read `BIG_SEARCH_CATALOG_CONTENT_BATCH`, -`BIG_SEARCH_DAEMON_CONTENT_BATCH`, `BIG_SEARCH_DAEMON_CONTENT_BATCH_MB` and -`BIG_SEARCH_DAEMON_CONTENT_IDLE_MS`, which shrink batches and waits; a release -build ignores them. +`BIG_SEARCH_DAEMON_CONTENT_BATCH`, `BIG_SEARCH_DAEMON_CONTENT_BATCH_MB`, +`BIG_SEARCH_DAEMON_CONTENT_IDLE_MS` and `BIG_SEARCH_SAVED_START_CHECK_MS`, +which shrink batches and waits, and `BIG_SEARCH_KEEP_PRIORITY`, which keeps +the indexer at normal priority; a release build ignores them. ## 10. Dependencies @@ -619,6 +673,43 @@ D-Bus. `deny.toml` admits crates.io only, and `Cargo.lock` is committed. `CAP_SYS_ADMIN`. - Every path, event and file is untrusted. The walk never follows symlinks; configured roots are resolved and checked before anything is indexed. +- A path a client names for the daemon to read (`reindex`, `save_version`, the + `register_*` targets) is taken only when, with every symlink on the way + followed, it lands inside a source as resolved when the daemon started, and + is keyed by where it lands; `..` is refused everywhere. `versions` and + `forget_versions` answer for the rows kept under the path as spelled, and + only when there are none for those under where it lands: a kept key was a + real path when written, and a symlink put in its place since leads to + another document. For that reason `save_version` through a path with rows + kept under it that lands on a file elsewhere is refused, since the restore + that follows could write one document's version over another's; with + nothing there it proceeds. `forget_versions` errs toward erasing: the rows + kept under the path as spelled and under where it lands, those parked from + either, and every row recorded for the file where it lands (filesystem, + `ino`, birth time), whoever they were kept for. +- History follows a document only through what the watcher hears: a rename + moves its rows, a folder's rename the rows below it, and every other row + below the destination is parked (a folder is renamed only onto an empty + one, so they are deleted documents' or those of documents moved away while + the service was stopped). A heard save keeps the row at the path, since an + editor's save is a new file there. Nothing hands rows to a file by its + identity. A row is parked when its path holds a file it does not record + that the service cannot have seen arrive: one born before the run (checked + for every row at a start, before anything heard), or one arriving where + the row's document was found gone by the missing sweep; also a row that + reaches its file through a folder replaced by a link. A parked row has no + path, is never listed or given one again, is erased by `forget_versions` + through the path it was parked from, and expires as a missing document's + does. So a document moved, or edited, while the service was stopped starts + a new history where it is; its earlier versions wait, parked or at the + path it left, until they expire. A pause stops indexing, not this: heard + saves and renames still reach the versions worker. A folder left unwatched + (past `max_user_watches`) hears nothing, so its documents fare as if + edited while stopped. At one path, files are told apart by + `ino` and birth time; the filesystem is its `f_fsid`, which XFS draws from + the device number, so it serves only to reach a file's rows under other + paths. It never keeps a version of a file reached through a folder + replaced by a link, and checks a reindex again before it reads. - Extraction subprocesses get argv arrays, never `sh -c`; a failure or a timeout skips the file and is logged, and never stops the daemon. - The socket lives in `$XDG_RUNTIME_DIR`, mode `0600`, `AF_UNIX` only, same UID. diff --git a/apps/big-search/fuzz/README.md b/apps/big-search/fuzz/README.md index 930f57e..fdfa0c7 100644 --- a/apps/big-search/fuzz/README.md +++ b/apps/big-search/fuzz/README.md @@ -20,7 +20,7 @@ cargo +nightly fuzz run docinfo_text -- -max_total_time=300 | Target | Exercises | |--------|-----------| -| `xml_text` | `extract::xml_text` and `extract::xml_text_lines`: the quick-xml character-data walks | +| `xml_text` | `extract::xml_text_lines`: the quick-xml character-data walk | | `office_zip` | `extract::office_text_from_reader`: zip parsing, entry selection and the XML walk, with arbitrary bytes as the archive (the main hostile-document path) | | `text_bytes` | `extract::text_from_bytes`: NUL/binary rejection and lossy UTF-8 decoding | | `mail_bytes` | `extract::mail_text`: an `.eml` message with MIME parts, base64, quoted-printable and encoded headers | diff --git a/apps/big-search/packaging/big-search.service b/apps/big-search/packaging/big-search.service index 2883308..0de20c2 100644 --- a/apps/big-search/packaging/big-search.service +++ b/apps/big-search/packaging/big-search.service @@ -28,9 +28,10 @@ Environment=RUST_LOG=info,tantivy=warn,symphonia_core=error,symphonia_format_iso # MemoryHigh reclaims page cache first; MemoryMax is the safety net. The # extraction pool's bounded queue keeps anonymous memory low. # The cpu controller is handed to the daemon, which runs in /main and puts -# its indexing threads in a threaded child group with cpu.idle: indexing takes -# only CPU time nobody else wants, searching keeps a normal program's share. A -# thread's SCHED_IDLE alone counts only inside its cgroup (DESIGN.md, section 7). +# its indexing threads in a threaded child group with cpu.idle: indexing yields +# to the daemon's searches. Against other programs the unit as a whole competes +# at its normal CPU weight, since a lower one slows searches on a busy machine; +# SCHED_IDLE and cpu.idle count only inside the unit (DESIGN.md, section 7). Delegate=cpu DelegateSubgroup=main IOAccounting=yes diff --git a/apps/big-search/src/browser_downloads.rs b/apps/big-search/src/browser_downloads.rs index fa4861b..6099081 100644 --- a/apps/big-search/src/browser_downloads.rs +++ b/apps/big-search/src/browser_downloads.rs @@ -257,6 +257,5 @@ mod tests { still_on_disk(rows), [(PathBuf::from(fresh), "new.example".to_string(), now - 5)] ); - std::fs::remove_dir_all(&dir).ok(); } } diff --git a/apps/big-search/src/catalogue.rs b/apps/big-search/src/catalogue.rs index 899227f..689dbe3 100644 --- a/apps/big-search/src/catalogue.rs +++ b/apps/big-search/src/catalogue.rs @@ -5,7 +5,7 @@ use anyhow::{Context, Result}; use big_indexd_client::Filter; use rusqlite::types::Value; -use rusqlite::{Connection, OpenFlags, params, params_from_iter}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, params, params_from_iter}; use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; @@ -35,7 +35,7 @@ pub struct State { dirty: bool, } -/// A difference a reconciliation pass found (see [`State::scan_changes_after`]). +/// A difference a reconciliation pass found (see `State::scan_changes_after`). #[derive(Debug, PartialEq, Eq)] pub enum ScanChange { /// On disk with this `(mtime, size)`, which the catalogue records otherwise @@ -57,47 +57,45 @@ enum PendingChange { } impl State { - /// The `namespace` rows of the state database at `db_path`, or an empty - /// in-memory state if the database cannot be opened. + /// The `namespace` rows of the state database at `db_path`. + /// + /// # Errors + /// + /// The database cannot be created, opened or given its schema. + pub fn open(db_path: &Path, namespace: &str) -> Result { + Ok(State { + db_path: db_path.to_path_buf(), + namespace: namespace.to_owned(), + conn: open_state_db(db_path)?, + pending: HashMap::new(), + removed_trees: Vec::new(), + clear_before_persist: false, + dirty: false, + }) + } + + /// [`State::open`], or an empty in-memory state that saves nothing when the + /// database cannot be opened, so readers and the service keep going. pub fn load(db_path: &Path, namespace: &str) -> Self { - match open_state_db(db_path) { - Ok(conn) => State { - db_path: db_path.to_path_buf(), - namespace: namespace.to_owned(), - conn, - pending: HashMap::new(), - removed_trees: Vec::new(), - clear_before_persist: false, - dirty: false, - }, - Err(error) => { - log::warn!( - "state database {} unavailable, nothing will be saved: {error:#}", - db_path.display() - ); - State::in_memory(db_path.to_path_buf(), namespace) - } - } + State::open(db_path, namespace).unwrap_or_else(|error| { + log::warn!( + "state database {} unavailable, nothing will be saved: {error:#}", + db_path.display() + ); + State::in_memory(db_path.to_path_buf(), namespace) + }) } /// Start empty (used for a forced full rebuild): the first persist replaces /// every row of `namespace`. - pub fn empty(db_path: &Path, namespace: &str) -> Self { - let conn = open_state_db(db_path).unwrap_or_else(|_| { - let conn = Connection::open_in_memory().expect("in-memory sqlite state opens"); - tune_connection_for_low_memory(&conn); - init_schema(&conn).expect("in-memory sqlite state schema initializes"); - conn - }); - State { - db_path: db_path.to_path_buf(), - namespace: namespace.to_owned(), - conn, - pending: HashMap::new(), - removed_trees: Vec::new(), - clear_before_persist: true, - dirty: true, - } + /// + /// # Errors + /// + /// As [`State::open`]. + pub fn empty(db_path: &Path, namespace: &str) -> Result { + let mut state = State::open(db_path, namespace)?; + state.clear(); + Ok(state) } /// Whether `path` is recorded with this exact mtime+size (→ unchanged). @@ -153,7 +151,7 @@ impl State { } /// The persisted paths directly inside `dir`. - pub fn children(&self, dir: &Path) -> Result> { + pub(crate) fn children(&self, dir: &Path) -> Result> { let (low, high) = subtree_range(&key(dir)); // substr() and length() both count characters, so they agree with // each other whatever the path holds. @@ -163,9 +161,39 @@ impl State { AND instr(substr(path, length(?2) + 1), '/') = 0", )?; let rows = statement.query_map(params![self.namespace, low, high], |row| { - row.get::<_, String>(0) + row.get::<_, String>(0).map(PathBuf::from) })?; - Ok(rows.flatten().map(PathBuf::from).collect()) + Ok(rows.collect::>()?) + } + + /// `dir` and the paths under it, pending changes included. + pub(crate) fn tree(&self, dir: &Path) -> Result> { + let dir_key = key(dir); + let (low, high) = subtree_range(&dir_key); + let in_tree = + |path: &str| path == dir_key || (path >= low.as_str() && path < high.as_str()); + let mut paths: Vec = Vec::new(); + if !self.clear_before_persist { + let mut statement = self.conn.prepare_cached( + "SELECT path FROM file_state + WHERE namespace = ?1 AND (path = ?2 OR (path >= ?3 AND path < ?4))", + )?; + let rows = statement.query_map(params![self.namespace, dir_key, low, high], |row| { + row.get::<_, String>(0) + })?; + for path in rows { + let path = path?; + if !self.pending.contains_key(&path) && !self.in_removed_tree(&path) { + paths.push(path); + } + } + } + for (path, change) in &self.pending { + if matches!(change, PendingChange::Set(..)) && in_tree(path) { + paths.push(path.clone()); + } + } + Ok(paths.into_iter().map(PathBuf::from).collect()) } /// Forget `path` and every path under it. A folder moved away, to the trash @@ -199,7 +227,7 @@ impl State { /// would otherwise take and release the database's locks on its own, two /// `fcntl` and an `fstat` apiece. Batches persisted meanwhile commit with /// the pass, and a failed pass rolls all of them back. - pub fn scan_pass(&mut self, pass: impl FnOnce(&mut Self) -> Result) -> Result { + pub(crate) fn scan_pass(&mut self, pass: impl FnOnce(&mut Self) -> Result) -> Result { self.conn .execute_batch("BEGIN") .context("begin scan transaction")?; @@ -222,7 +250,7 @@ impl State { /// Start a low-RAM reconciliation pass. Seen paths are recorded in a SQLite /// temporary B-tree instead of a process-wide `HashSet`. - pub fn begin_scan(&mut self) -> Result<()> { + pub(crate) fn begin_scan(&mut self) -> Result<()> { self.conn .execute_batch( " @@ -240,7 +268,7 @@ impl State { /// Mark `path` as observed in the current reconciliation pass, with the /// `(mtime, size)` found on disk when the pass compares them (see /// [`Self::scan_changes_after`]). - pub fn mark_seen(&mut self, path: &Path, found: Option<(i64, u64)>) -> Result<()> { + pub(crate) fn mark_seen(&mut self, path: &Path, found: Option<(i64, u64)>) -> Result<()> { let (mtime, size) = found.map_or((None, None), |(mtime, size)| { (Some(mtime), Some(u64_to_db_size(size))) }); @@ -262,7 +290,7 @@ impl State { /// where a lookup per path would cost three B-tree descents with the /// seen-mark and the deletion check. The catalogue must be persisted when /// the pass starts; rows written meanwhile all sort at or before `after`. - pub fn scan_changes_after( + pub(crate) fn scan_changes_after( &self, after: &str, limit: usize, @@ -311,7 +339,7 @@ impl State { /// Mark every cached path under the retained prefixes as seen. Used for /// offline removable/network sources whose catalogues must not be deleted just /// because the mount is absent during this scan. - pub fn mark_seen_prefixes(&mut self, prefixes: &[PathBuf]) -> Result<()> { + pub(crate) fn mark_seen_prefixes(&mut self, prefixes: &[PathBuf]) -> Result<()> { for prefix in prefixes { let prefix_text = key(prefix); let (low, high) = subtree_range(&prefix_text); @@ -334,7 +362,11 @@ impl State { /// Batch of cached paths not seen in the current scan, lexicographically after /// `after`. Batching avoids allocating the whole deletion set. - pub fn unseen_paths_after(&self, after: Option<&str>, limit: usize) -> Result> { + pub(crate) fn unseen_paths_after( + &self, + after: Option<&str>, + limit: usize, + ) -> Result> { if limit == 0 || self.clear_before_persist { return Ok(Vec::new()); } @@ -364,7 +396,7 @@ impl State { /// /// Deleting a file drops only its catalogue row; this finds the content /// rows and documents that would keep answering for paths that are gone. - pub fn paths_missing_from( + pub(crate) fn paths_missing_from( &self, other_namespace: &str, after: Option<&str>, @@ -418,7 +450,7 @@ impl State { /// `(mtime, size)` is absent or different in `other_namespace` of the same /// database. Streams the pending-work set in one indexed SQL join instead of /// re-walking the catalogue with a `stat` + a SELECT per file. - pub fn entries_stale_against( + pub(crate) fn entries_stale_against( &self, other_namespace: &str, after: Option<&str>, @@ -467,7 +499,11 @@ impl State { /// Recorded `(path, mtime, size)` after `after`, sorted, pending changes /// included. Used by bounded catalogue passes instead of materializing the - /// full catalogue. + /// full catalogue: a page shorter than `limit` is the last one. + /// + /// # Errors + /// + /// Returns an error when the catalogue database cannot be queried. pub fn entries_after( &self, after: Option<&str>, @@ -477,37 +513,30 @@ impl State { return Ok(Vec::new()); } let after_text = after.unwrap_or_default(); - let mut entries: Vec<(String, i64, u64)> = if self.clear_before_persist { - Vec::new() - } else { - let mut stmt = self - .conn - .prepare_cached( - " - SELECT path, mtime, size FROM file_state - WHERE namespace = ?1 AND path > ?2 - ORDER BY path - LIMIT ?3 - ", - ) - .context("prepare path batch query")?; - let rows = stmt - .query_map(params![self.namespace, after_text, limit as i64], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, i64>(1)?, - db_size_to_u64(row.get::<_, i64>(2)?), - )) - }) - .context("query path batch")?; - rows.collect::>>()? - }; + // Stored rows a pending change overrides do not count toward the page, + // and a pending row past the last stored row read waits for its page: + // either would end the pass early or move the cursor past unread rows. + let mut entries: Vec<(String, i64, u64)> = Vec::new(); + let mut stored_after = after_text.to_owned(); + let mut stored_done = self.clear_before_persist; + while !stored_done && entries.len() < limit { + let page = self.stored_page(&stored_after, limit)?; + stored_done = page.len() < limit; + if let Some((last, _, _)) = page.last() { + stored_after.clone_from(last); + } + entries.extend(page.into_iter().filter(|(path, _, _)| { + !self.pending.contains_key(path) && !self.in_removed_tree(path) + })); + } for (path, change) in &self.pending { if !after_text.is_empty() && path.as_str() <= after_text { continue; } - entries.retain(|(known, _, _)| known != path); + if !stored_done && path.as_str() > stored_after.as_str() { + continue; + } if let PendingChange::Set(mtime, size) = *change { entries.push((path.clone(), mtime, size)); } @@ -520,6 +549,31 @@ impl State { .collect()) } + /// Up to `limit` stored rows after `after`, in path order, pending changes ignored. + fn stored_page(&self, after: &str, limit: usize) -> Result> { + let mut stmt = self + .conn + .prepare_cached( + " + SELECT path, mtime, size FROM file_state + WHERE namespace = ?1 AND path > ?2 + ORDER BY path + LIMIT ?3 + ", + ) + .context("prepare path batch query")?; + let rows = stmt + .query_map(params![self.namespace, after, limit as i64], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, i64>(1)?, + db_size_to_u64(row.get::<_, i64>(2)?), + )) + }) + .context("query path batch")?; + Ok(rows.collect::>>()?) + } + pub fn len(&self) -> usize { let mut count = if self.clear_before_persist { 0usize @@ -555,18 +609,18 @@ impl State { } /// The value stored under `key` in the database's `meta` table. - pub fn meta(&self, key: &str) -> Option { + pub(crate) fn meta(&self, key: &str) -> rusqlite::Result> { self.conn .query_row( "SELECT value FROM meta WHERE key = ?1", params![key], |row| row.get(0), ) - .ok() + .optional() } /// Store `value` under `key` in the `meta` table, or remove the key. - pub fn set_meta(&self, key: &str, value: Option) -> Result<()> { + pub(crate) fn set_meta(&self, key: &str, value: Option) -> Result<()> { match value { Some(value) => self.conn.execute( "INSERT INTO meta(key, value) VALUES (?1, ?2) @@ -589,6 +643,10 @@ impl State { } /// Persist changed rows in one SQLite transaction. + /// + /// # Errors + /// + /// Returns an error when the transaction fails; the changes stay pending for the next call. pub fn persist(&mut self) -> Result<()> { if !self.dirty { return Ok(()); @@ -852,8 +910,8 @@ fn open_state_db(db_path: &Path) -> Result { std::fs::create_dir_all(parent)?; } let conn = Connection::open(db_path).with_context(|| format!("open {}", db_path.display()))?; - // The daemon's scan pass holds the write lock for its whole walk; a CLI - // command opening the same database waits for it rather than failing. + // Opening writes (init_schema), so an open while a scan pass holds the + // write lock waits up to 5 s, then fails into the in-memory fallback. conn.busy_timeout(std::time::Duration::from_secs(5))?; tune_connection_for_low_memory(&conn); init_schema(&conn)?; diff --git a/apps/big-search/src/catalogue/tests.rs b/apps/big-search/src/catalogue/tests.rs index 849f0af..d67efa5 100644 --- a/apps/big-search/src/catalogue/tests.rs +++ b/apps/big-search/src/catalogue/tests.rs @@ -6,7 +6,7 @@ fn dedup_roundtrip() { let file = dir.join("state.sqlite"); let p = Path::new("/x/y.txt"); - let mut s = State::empty(&file, NAME_NAMESPACE); + let mut s = State::empty(&file, NAME_NAMESPACE).unwrap(); assert!(!s.unchanged(p, 100, 5)); s.set(p, 100, 5); assert!(s.unchanged(p, 100, 5)); @@ -21,8 +21,6 @@ fn dedup_roundtrip() { let mut s2 = State::load(&file, NAME_NAMESPACE); s2.remove(p); assert!(!s2.unchanged(p, 100, 5)); - - std::fs::remove_dir_all(&dir).ok(); } /// A folder's inode, kept in the size column of the watch list, reads back as @@ -33,11 +31,11 @@ fn full_width_inode_kept() { let file = dir.join("state.sqlite"); let folder = Path::new("/x/folder"); let inode = u64::MAX - 7; - let mut state = State::empty(&file, WATCH_NAMESPACE); + let mut state = State::empty(&file, WATCH_NAMESPACE).unwrap(); state.set(folder, 0, inode); state.persist().unwrap(); let recorded = State::load(&file, WATCH_NAMESPACE).recorded(folder); - std::fs::remove_dir_all(&dir).ok(); + let _ = std::fs::remove_dir_all(&dir); assert_eq!(recorded, Some((0, inode))); } @@ -50,7 +48,7 @@ fn cleared_state_hides_persisted_rows() { let file = dir.join("state.sqlite"); let path = Path::new("/x/persisted.md"); - let mut seeded = State::empty(&file, NAME_NAMESPACE); + let mut seeded = State::empty(&file, NAME_NAMESPACE).unwrap(); seeded.set(path, 100, 5); seeded.persist().unwrap(); @@ -74,10 +72,8 @@ fn cleared_state_hides_persisted_rows() { ); // A fresh empty state (clear_before_persist) also denies persisted rows. - let empty = State::empty(&file, NAME_NAMESPACE); + let empty = State::empty(&file, NAME_NAMESPACE).unwrap(); assert!(!empty.contains(path)); - - std::fs::remove_dir_all(&dir).ok(); } /// The pages of the two sides end at different paths; whatever the page @@ -85,7 +81,7 @@ fn cleared_state_hides_persisted_rows() { #[test] fn scan_changes_ignore_page_size() { let dir = crate::test_env::scratch_dir("bs-state-scan"); - let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE); + let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE).unwrap(); for (path, mtime) in [("/a", 1), ("/b", 1), ("/d", 1), ("/e", 1), ("/g", 1)] { state.set(Path::new(path), mtime, 1); } @@ -118,13 +114,12 @@ fn scan_changes_ignore_page_size() { } assert_eq!(changes, expected, "page size {limit}"); } - std::fs::remove_dir_all(&dir).ok(); } #[test] fn children_are_one_level_deep() { let dir = crate::test_env::scratch_dir("bs-state-children"); - let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE); + let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE).unwrap(); for path in ["/p/ção", "/p/ção/a", "/p/ção/s", "/p/ção/s/b", "/p/ção-2/c"] { state.set(Path::new(path), 1, 1); } @@ -135,13 +130,12 @@ fn children_are_one_level_deep() { children, [PathBuf::from("/p/ção/a"), PathBuf::from("/p/ção/s")] ); - std::fs::remove_dir_all(&dir).ok(); } #[test] fn removed_tree_spares_its_siblings() { let dir = crate::test_env::scratch_dir("bs-state-tree"); - let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE); + let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE).unwrap(); for path in ["/p/t", "/p/t/a", "/p/t/s/b", "/p/t-2", "/p/t0"] { state.set(Path::new(path), 1, 1); } @@ -168,13 +162,12 @@ fn removed_tree_spares_its_siblings() { .filter(|path| state.contains(Path::new(path))) .collect(); assert_eq!(kept, ["/p/t/a", "/p/t-2", "/p/t0"]); - std::fs::remove_dir_all(&dir).ok(); } #[test] fn retained_prefix_keeps_accented_paths() { let dir = crate::test_env::scratch_dir("bs-state-retain"); - let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE); + let mut state = State::empty(&dir.join("state.sqlite"), NAME_NAMESPACE).unwrap(); for path in [ "/run/media/joão/USB", "/run/media/joão/USB/a.txt", @@ -193,13 +186,13 @@ fn retained_prefix_keeps_accented_paths() { changes, vec![ScanChange::Gone(PathBuf::from("/run/media/joão/USB-2/b"))] ); - std::fs::remove_dir_all(&dir).ok(); } #[test] fn entries_after_merges_pending_rows() { let dir = crate::test_env::scratch_dir("bs-state-paths"); - let mut state = State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + let mut state = + State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE).unwrap(); state.set(Path::new("/a/kept.md"), 1, 1); state.set(Path::new("/b/removed.md"), 1, 1); state.persist().unwrap(); @@ -221,18 +214,56 @@ fn entries_after_merges_pending_rows() { assert_eq!(after, vec![(PathBuf::from("/c/added.md"), 2, 2)]); assert_eq!(state.len(), 2); assert!(!state.is_empty()); +} - std::fs::remove_dir_all(&dir).ok(); +#[test] +fn entries_after_pages_pending_rows() { + let dir = crate::test_env::scratch_dir("bs-state-page-pending"); + let mut state = + State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE).unwrap(); + for path in ["/a", "/b", "/c", "/d/x", "/e"] { + state.set(Path::new(path), 1, 1); + } + state.persist().unwrap(); + state.remove(Path::new("/a")); + state.remove_tree(Path::new("/d")); + state.set(Path::new("/z"), 2, 2); + + // Pages of 2 walked by their last key, as the watcher and the CLI page. + let mut pages = Vec::new(); + let mut after: Option = None; + loop { + let page = state.entries_after(after.as_deref(), 2).unwrap(); + let full = page.len() == 2; + after = page + .last() + .map(|(path, _, _)| path.to_string_lossy().into_owned()); + pages.push( + page.into_iter() + .map(|(path, _, _)| path) + .collect::>(), + ); + if !full { + break; + } + } + let expected: Vec> = [vec!["/b", "/c"], vec!["/e", "/z"], vec![]] + .into_iter() + .map(|page| page.into_iter().map(PathBuf::from).collect()) + .collect(); + assert_eq!(pages, expected); } #[test] fn stale_entries_stream_pending_work() { let dir = crate::test_env::scratch_dir("bs-state-stale"); - let mut names = State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + let mut names = + State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE).unwrap(); let mut content = State::empty( &dir.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); names.set(Path::new("/a/extracted.md"), 100, 5); names.set(Path::new("/b/changed.md"), 200, 9); @@ -261,14 +292,13 @@ fn stale_entries_stream_pending_work() { resumed, vec![(PathBuf::from("/c/never-extracted.md"), 300, 7)] ); - - std::fs::remove_dir_all(&dir).ok(); } #[test] fn len_tracks_pending_overlaps_and_removals() { let dir = crate::test_env::scratch_dir("bs-state-len"); - let mut state = State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + let mut state = + State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE).unwrap(); state.set(Path::new("/p/a.md"), 1, 1); state.set(Path::new("/p/b.md"), 1, 1); state.persist().unwrap(); @@ -299,8 +329,6 @@ fn len_tracks_pending_overlaps_and_removals() { state.unseen_paths_after(None, 5).unwrap().is_empty(), "a cleared state has no deletions to stream" ); - - std::fs::remove_dir_all(&dir).ok(); } #[test] @@ -308,9 +336,8 @@ fn on_disk_state_uses_wal_journal() { // tune_connection_for_low_memory switches to WAL; the default rollback // journal would double write amplification on every persist. let dir = crate::test_env::scratch_dir("bs-state-wal"); - let state = State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + let state = State::empty(&dir.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE).unwrap(); assert_eq!(state.journal_mode(), "wal"); - std::fs::remove_dir_all(&dir).ok(); } /// A catalogue database holding `rows` in the name namespace, and a reader of it. @@ -320,7 +347,7 @@ fn catalogue_of( ) -> (crate::test_env::ScratchDir, CatalogueReader) { let dir = crate::test_env::scratch_dir(&format!("bs-catalogue-{label}")); let db = dir.join("state.sqlite"); - let mut names = State::empty(&db, NAME_NAMESPACE); + let mut names = State::empty(&db, NAME_NAMESPACE).unwrap(); for (path, mtime, size) in rows { names.set(Path::new(path), *mtime, *size); } @@ -347,7 +374,7 @@ fn newest_first_with_exact_total() { ], ); // The content namespace shares the table and must not leak in. - let mut content = State::empty(&dir.join("state.sqlite"), CONTENT_NAMESPACE); + let mut content = State::empty(&dir.join("state.sqlite"), CONTENT_NAMESPACE).unwrap(); content.set(Path::new("/p/content-only.jpg"), 999, 1); content.persist().unwrap(); @@ -383,12 +410,11 @@ fn newest_first_with_exact_total() { assert_eq!(page(4, 2), (5, vec!["/p/old.jpg".to_string()])); assert_eq!(page(9, 2), (5, Vec::new()), "past the end"); assert_eq!(page(0, 0), (5, Vec::new()), "a count alone"); - std::fs::remove_dir_all(&dir).ok(); } #[test] fn under_stops_at_the_folder_boundary() { - let (dir, reader) = catalogue_of( + let (_dir, reader) = catalogue_of( "under", &[ ("/home/a", 1, 0), @@ -419,12 +445,11 @@ fn under_stops_at_the_folder_boundary() { "under {root:?}" ); } - std::fs::remove_dir_all(&dir).ok(); } #[test] fn ext_matches_ending_in_any_case() { - let (dir, reader) = catalogue_of( + let (_dir, reader) = catalogue_of( "ext", &[ ("/p/a.JPG", 1, 1), @@ -452,12 +477,11 @@ fn ext_matches_ending_in_any_case() { newest_paths(&reader, &ext(&["tar.gz", "png"])), ["/p/c.png"] ); - std::fs::remove_dir_all(&dir).ok(); } #[test] fn ranges_compare_recorded_values() { - let (dir, reader) = catalogue_of( + let (_dir, reader) = catalogue_of( "range", &[ ("/p/a", 100, 10), @@ -483,7 +507,6 @@ fn ranges_compare_recorded_values() { ..Default::default() }; assert_eq!(newest_paths(&reader, &both), ["/p/huge", "/p/c"]); - std::fs::remove_dir_all(&dir).ok(); } #[test] @@ -495,7 +518,7 @@ fn missing_catalogue_lists_nothing() { .unwrap(), (0, Vec::new()) ); - std::fs::remove_dir_all(&dir).ok(); + let _ = std::fs::remove_dir_all(&dir); let missing = CatalogueReader::new(&dir.join("state.sqlite")); assert_eq!( missing @@ -533,5 +556,4 @@ fn newest_page_uses_mtime_index() { .any(|step| step.contains("file_state_name_by_mtime")), "{steps:?}" ); - std::fs::remove_dir_all(&dir).ok(); } diff --git a/apps/big-search/src/cjk_tokenizer.rs b/apps/big-search/src/cjk_tokenizer.rs index 5fca33d..275fdbd 100644 --- a/apps/big-search/src/cjk_tokenizer.rs +++ b/apps/big-search/src/cjk_tokenizer.rs @@ -119,7 +119,7 @@ fn tokenize(text: &str) -> Vec { /// separator or letter is decided from its byte, and a word is copied into the /// token as one slice. pub struct CjkTokenStream<'a> { - /// The text composed as [`crate::extract::compose`] says: a decomposed + /// The text composed as [`crate::fold::compose`] says: a decomposed /// Hangul syllable or halfwidth kana must be one character before it can /// be part of a bigram. Offsets point into this text. text: std::borrow::Cow<'a, str>, @@ -278,7 +278,7 @@ impl Tokenizer for CjkFriendlyTokenizer { fn token_stream<'a>(&'a mut self, text: &'a str) -> Self::TokenStream<'a> { CjkTokenStream { - text: crate::extract::compose(text), + text: crate::fold::compose(text), cursor: 0, run: None, unigrams: self.unigrams, @@ -349,7 +349,7 @@ mod tests { "relato\u{301}rio \u{301}solto ca\u{327}a\u{303}o", ]; for text in corpus { - let expected = tokenize(&crate::extract::compose(text)); + let expected = tokenize(&crate::fold::compose(text)); let got = streamed(text); assert_eq!(got.len(), expected.len(), "count for {text:?}"); for (got, expected) in got.iter().zip(expected.iter()) { diff --git a/apps/big-search/src/config.rs b/apps/big-search/src/config.rs index c81d5ac..f8d12c7 100644 --- a/apps/big-search/src/config.rs +++ b/apps/big-search/src/config.rs @@ -23,11 +23,16 @@ pub fn data_dir() -> PathBuf { /// complete list of every path in their home, and the content index holds the /// extracted *text* of their documents. SQLite and the walker create their files /// through the process umask, typically `0022`, which leaves `state.sqlite` and -/// `content-signatures.json` readable by every local account. Tantivy creates -/// `index/` as 0700 on its own; nothing else does. +/// `content-signatures.json` readable by every local account, and the +/// index directories are created the same way. /// /// Restricting the directory covers every file inside it, present and future, /// without having to remember a mode at each creation site. +/// +/// # Errors +/// +/// Returns the I/O error of creating the data directory, reading its mode or +/// restricting it. pub fn ensure_private_data_dir() -> std::io::Result<()> { let dir = data_dir(); std::fs::create_dir_all(&dir)?; @@ -127,7 +132,6 @@ mod tests { ensure_private_data_dir().unwrap(); let mode = std::fs::metadata(data_dir()).unwrap().permissions().mode(); assert_eq!(mode & 0o777, 0o700); - std::fs::remove_dir_all(&base).ok(); } #[test] diff --git a/apps/big-search/src/config_cmd.rs b/apps/big-search/src/config_cmd.rs index f86435f..4788bd9 100644 --- a/apps/big-search/src/config_cmd.rs +++ b/apps/big-search/src/config_cmd.rs @@ -49,7 +49,7 @@ pub(super) fn cmd_config(tokens: &[String]) -> Result<()> { pub(super) fn print_config_help() { let title = bold("big-search config"); println!( - "{title}\n\n{}\n config show\n config path\n config set names-only|content|metadata|follow-symlinks true|false\n config set content-index-mode auto|basic|freqs (also content-mode)\n config set extract-max-mb N (0 = automatic)\n config set text-max-mb|pdf-max-mb N (0 = no limit)\n config set office-max-mb N (0 = automatic; also content-max-mb)\n config set pdf-timeout-secs N\n config set content-cooldown-secs N (also cooldown-secs)\n config set symlink-policy personal-local|local-exact\n config preset names-only|low-memory|balanced|complete\n\n{}\n names-only smallest index: names and paths only\n low-memory content on, Basic postings, conservative caps\n balanced automatic: Basic below 6 GiB of RAM, Freqs above\n complete Freqs and a larger extraction cap\n", + "{title}\n\n{}\n config show\n config path\n config set names-only|content|metadata|follow-symlinks true|false\n config set content-index-mode auto|basic|freqs (also content-mode)\n config set extract-max-mb N (0 = automatic)\n config set text-max-mb|pdf-max-mb N (0 = no limit)\n config set office-max-mb N (0 = automatic; also content-max-mb)\n config set pdf-timeout-secs N\n config set content-cooldown-secs N (also cooldown-secs)\n config set symlink-policy personal-local|local-exact\n config preset names-only|low-memory|balanced|complete\n\n{}\n names-only smallest index: names and paths only\n low-memory content on, Basic postings, conservative caps\n balanced automatic: Basic when the service may use below 6 GiB, Freqs above\n complete Freqs and a larger extraction cap\n", cyan("Usage:"), cyan("Profiles:"), ); @@ -75,7 +75,7 @@ fn print_unknown_choices() { // shape: declares a view: one line per effective setting. pub(super) fn cmd_config_show() -> Result<()> { let requested = settings::content_index_mode().as_str(); - let resolved = settings::resolved_content_index_mode().as_str(); + let effective = content_index_detail(); let ram = settings::total_memory_bytes() .map(format_bytes) .unwrap_or_else(|| "unknown".to_string()); @@ -93,13 +93,14 @@ pub(super) fn cmd_config_show() -> Result<()> { let capacity = settings::effective_memory_bytes() .map(format_bytes) .unwrap_or_else(|| "unknown (conservative limits)".to_owned()); - println!("{} {capacity}", bold("Memory sized for:")); + println!( + "{} {capacity} here; the service sizes by its own memory limit", + bold("Memory sized for:") + ); println!("{} {profile}", bold("Effective profile:")); println!( - "{} requested={}, effective={}", + "{} requested={requested}, effective={effective}", bold("Content index mode:"), - requested, - resolved, ); println!( "{} {}", @@ -130,6 +131,30 @@ pub(super) fn cmd_config_show() -> Result<()> { Ok(()) } +/// The posting detail the content index on disk holds, which `auto` keeps +/// whatever this shell's memory would choose; when there is none to reuse, +/// the detail a new one would get. +fn content_index_detail() -> String { + let dir = config::content_index_dir(); + if !dir.join("meta.json").exists() { + return new_content_index_detail(); + } + match index::open_read_only(&dir) { + Ok(content_index) => match index::stored_content_mode(&content_index) { + Some(mode) => format!("{}, from the content index on disk", mode.as_str()), + None => new_content_index_detail(), + }, + Err(error) => format!("unknown, the content index is unreadable: {error:#}"), + } +} + +fn new_content_index_detail() -> String { + format!( + "{} for a new content index", + settings::resolved_content_index_mode().as_str() + ) +} + pub(super) fn format_bytes(bytes: u64) -> String { if bytes >= (1 << 30) { format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) diff --git a/apps/big-search/src/content.rs b/apps/big-search/src/content.rs index bd4d9d3..3b7be99 100644 --- a/apps/big-search/src/content.rs +++ b/apps/big-search/src/content.rs @@ -48,6 +48,10 @@ const NON_CANDIDATE_TOMBSTONE_BATCH: usize = 4096; /// ("tombstones"), removing them from the pending join. Changing the indexing /// policy later (e.g. enabling metadata) requires `big-search rebuild`, which /// clears this state. +/// +/// # Errors +/// +/// Returns an error when the content state cannot be written. pub fn record_skipped_candidates(entries: &[(PathBuf, i64, u64)]) -> Result<()> { if entries.is_empty() { return Ok(()); @@ -76,6 +80,11 @@ pub type CatalogCursor = Option; /// see them, and they answer content searches with files that are gone. /// /// Walks every live document, so this is a startup repair, not a per-pass step. +/// +/// # Errors +/// +/// Returns an error when the content index or its state cannot be read, or the deletions +/// cannot be committed. pub fn prune_unreferenced_content_docs(index: &Index) -> Result { let index_dir = crate::config::content_index_dir(); if crate::index::is_unreferenced_pruned(&index_dir) { @@ -142,6 +151,11 @@ pub const ORPHAN_PRUNE_STEADY_LIMIT: usize = 8192; /// it would answer searches until a full rebuild. Commits are batched because a /// commit is the expensive part, and a keyset cursor (not the deletions /// themselves) advances the scan, so nothing has to be flushed to make progress. +/// +/// # Errors +/// +/// Returns an error when the content state cannot be read or written, or the deletions +/// cannot be committed. pub fn prune_orphaned_content(index: &Index, limit: usize) -> Result<(usize, bool)> { const FLUSH_EVERY: usize = 16 * ORPHAN_PRUNE_BATCH; @@ -211,7 +225,7 @@ pub(crate) fn default_workers() -> usize { ) } -/// One worker on a small machine, two otherwise; a request of 1 to 4 wins. +/// One worker on a small machine, two otherwise; a request wins, up to 4. fn pool_width(cores: usize, low_memory: bool, requested: Option<&str>) -> usize { let default = if low_memory || cores <= 2 { 1 } else { 2 }; requested @@ -232,6 +246,11 @@ fn content_channel_capacity() -> usize { /// Index all pending content/metadata by streaming the name catalogue from /// SQLite in bounded batches. This avoids constructing `Vec` for the /// full catalogue during a reindex or daemon backfill. +/// +/// # Errors +/// +/// Returns an error when the catalogue or the content state cannot be read, or the content +/// index cannot be written. pub fn index_pending_catalog(index: &Index) -> Result { if !crate::settings::content_index_enabled() { return Ok(0); @@ -254,12 +273,13 @@ pub fn index_pending_catalog(index: &Index) -> Result { } break; } - indexed_total = indexed_total.saturating_add(index_content_limited_with_writer( + let read = index_content_limited_with_writer( &mut writer, &f, batch.files, Some(catalog_content_batch_limit()), - )?); + )?; + indexed_total = indexed_total.saturating_add(read.indexed); if !batch.has_more { break; } @@ -270,6 +290,12 @@ pub fn index_pending_catalog(index: &Index) -> Result { Ok(indexed_total) } +/// Extracts and indexes the content of `files`, at most `limit` of them when +/// given, and returns how many were indexed. +/// +/// # Errors +/// +/// Returns an error when the content index or its state cannot be written. pub fn index_content_limited( index: &Index, files: Vec, @@ -280,21 +306,33 @@ pub fn index_content_limited( } let f = content_fields(index)?; let mut writer = crate::index::content_writer(index).context("content writer")?; - let indexed = index_content_limited_with_writer(&mut writer, &f, files, limit)?; + let read = index_content_limited_with_writer(&mut writer, &f, files, limit)?; writer .wait_merging_threads() .context("wait content merges")?; - Ok(indexed) + Ok(read.indexed) +} + +/// What one extraction batch did. +pub(crate) struct BatchRead { + pub(crate) indexed: u64, + /// Files another process held busy: they get no content row, so they stay + /// pending until a later pass reads them. + pub(crate) busy: usize, } -pub fn index_content_limited_with_writer( +pub(crate) fn index_content_limited_with_writer( writer: &mut IndexWriter, f: &ContentFields, files: Vec, limit: Option, -) -> Result { +) -> Result { + let nothing_read = BatchRead { + indexed: 0, + busy: 0, + }; if !crate::settings::content_index_enabled() { - return Ok(0); + return Ok(nothing_read); } let mut content_state = catalogue::State::load( &crate::config::state_db_path(), @@ -304,7 +342,7 @@ pub fn index_content_limited_with_writer( pending_batch_with_byte_limit(files, &content_state, limit.unwrap_or(usize::MAX), u64::MAX) .files; if files.is_empty() { - return Ok(0); + return Ok(nothing_read); } let queue = Arc::new(Mutex::new(files.into_iter())); @@ -322,14 +360,17 @@ pub fn index_content_limited_with_writer( let signatures = signatures.clone(); let tx = tx.clone(); workers.push(std::thread::spawn(move || { - run_extraction_worker(&queue, signatures.as_deref(), &tx); + run_extraction_worker(&queue, signatures.as_deref(), &tx) })); } drop(tx); // close channel once all workers finish let indexed = write_content_results(writer, f, rx, &mut content_state)?; + let mut busy = 0; for w in workers { - let _ = w.join(); + // A worker that panicked outside the extractors' catch_unwind takes + // its count with it, as it already took the file it was reading. + busy += w.join().unwrap_or(0); } if let Some(signatures) = signatures { let mut signatures = signatures.lock().expect("signature lock"); @@ -341,17 +382,19 @@ pub fn index_content_limited_with_writer( signatures.persist()?; } content_state.persist()?; - Ok(indexed) + Ok(BatchRead { indexed, busy }) } /// One extraction worker: drains the shared queue at background priority and -/// sends one result per file it could stat. +/// sends one result per file it could stat and another process does not hold +/// busy; returns how many it found busy. fn run_extraction_worker( queue: &Mutex>, signatures: Option<&Mutex>, tx: &mpsc::SyncSender, -) { +) -> usize { throttle::lower_priority(); + let mut busy = 0; loop { let next = { let mut q = queue.lock().expect("queue lock"); @@ -359,40 +402,33 @@ fn run_extraction_worker( }; let Some(path) = next else { break }; throttle::yield_for_pressure(); - // One stat answers both questions: the selection pass already - // stat'ed this file, and asking again for mtime/size and then a - // third time for the symlink check was pure repetition. let Ok(metadata) = std::fs::symlink_metadata(&path) else { continue; }; let (mtime, size) = catalogue::meta_pair(&metadata); - if metadata.is_symlink() { - let _ = tx.send(ContentResult { - path, - mtime, - size, - body: None, - }); - continue; - } - if let Some(signatures) = signatures - && matches!( - signatures - .lock() - .expect("signature lock") - .claim(&path, size), - ContentClaim::Duplicate - ) - { - let _ = tx.send(ContentResult { - path, - mtime, - size, - body: None, - }); - continue; - } - let body = extract_body(&path); + // Only a regular file is read: a link would duplicate its target's body. + // The descriptor is held through the extraction: while it is open no + // other process can take a write lease, so no reader below skips the file. + let body = match extract::open_regular_with(&path, libc::O_NOFOLLOW) { + Ok(_lease_bar) => { + let duplicate = signatures.is_some_and(|signatures| { + matches!( + signatures + .lock() + .expect("signature lock") + .claim(&path, size), + ContentClaim::Duplicate + ) + }); + if duplicate { None } else { extract_body(&path) } + } + // No result: the file stays pending and a later pass reads it. + Err(extract::Unopened::Busy) => { + busy += 1; + continue; + } + Err(extract::Unopened::Refused) => None, + }; let _ = tx.send(ContentResult { path, mtime, @@ -400,6 +436,7 @@ fn run_extraction_worker( body, }); } + busy } /// The indexed body of one file: its text and/or media metadata, as the @@ -472,8 +509,12 @@ fn dedupe_content_enabled() -> bool { } /// One pending backfill batch selected from the complete name catalogue without -/// loading the catalogue into RAM (a fresh pass; see [`pending_catalog_batch_after`]). +/// loading the catalogue into RAM (a fresh pass; see `pending_catalog_batch_after`). /// `min_change_age` defers files changed more recently than that (cooldown). +/// +/// # Errors +/// +/// Returns an error when the catalogue or the content state cannot be read. pub fn pending_catalog_batch( limit: usize, min_change_age: Duration, @@ -488,7 +529,7 @@ pub fn pending_catalog_batch( /// cursor for the next call (`None` when this pass reached the catalogue end). /// Files whose catalogued mtime is younger than `min_change_age` are deferred, /// not extracted; pass `Duration::ZERO` to bypass the cooldown. -pub fn pending_catalog_batch_after( +pub(crate) fn pending_catalog_batch_after( cursor: CatalogCursor, limit: usize, min_change_age: Duration, @@ -516,8 +557,12 @@ fn catalog_content_batch_limit() -> usize { .unwrap_or(DEFAULT_CATALOG_CONTENT_BATCH) } -/// Forget what the content pass knows about one path, so the next pass reads it -/// again although neither its size nor its modification time changed. +/// The `(mtime, size)` a content row is given so the next pass reads its file +/// again: no file has it, so the row matches no catalogue entry. +const STALE_CONTENT: (i64, u64) = (i64::MIN, 0); + +/// Make the content pass read one path again although neither its size nor its +/// modification time changed. /// /// This is the whole shape of a tag write. A tag lives in the `user.xdg.tags` /// extended attribute, and writing an extended attribute leaves size and @@ -526,15 +571,28 @@ fn catalog_content_batch_limit() -> usize { /// the content index keeps its own record, and the tag token lives there. /// Without this, the forced reindex commits a name-index document with nothing /// new in it, the content pass declines the work, and the tag is never findable. -pub fn forget_content_state(path: &Path) -> Result<()> { +/// +/// The row stays, only marked stale: it is what [`prune_orphaned_content`] +/// finds the document by when the path leaves the catalogue before the pass +/// reads it again. +pub(crate) fn mark_content_stale(path: &Path) -> Result<()> { let mut content_state = catalogue::State::load( &crate::config::state_db_path(), crate::catalogue::CONTENT_NAMESPACE, ); - content_state.remove(path); + if !content_state.contains(path) { + return Ok(()); + } + let (mtime, size) = STALE_CONTENT; + content_state.set(path, mtime, size); content_state.persist() } +/// Forgets every content state row, so every file is extracted again. +/// +/// # Errors +/// +/// Returns an error when the content state cannot be cleared. pub fn clear_content_state() -> Result<()> { // These rows are the only thing referencing the content documents, so // dropping them is exactly what strands documents. Re-arm the sweep. @@ -648,8 +706,8 @@ impl CatalogSelection { fn take(&mut self, path: PathBuf, mtime: i64, size: u64) -> bool { let path_key = path.to_string_lossy().into_owned(); // Three ways a catalogue entry is settled without extracting it: the - // policy never wants it, it is already gone, or it is a directory. - // All get a tombstone. + // policy never wants it, it is already gone, or it is not a regular + // file. All get a tombstone. // // The vanished case has to be caught here, not in the worker: there // `catalogue::meta` fails and the path is skipped with no result, so no @@ -659,16 +717,14 @@ impl CatalogSelection { // Only this side still holds the catalogue's mtime/size, which is // what the pending join compares against. // - // Directories reach this point because `meta::is_meta_candidate` + // The scan catalogues every file type, and `meta::is_meta_candidate` // answers `sniff_type` (on by default) for anything without an - // extension, and never asks whether the path is a file. A directory - // has no body and no media metadata, but its mtime changes whenever - // an entry is added or removed inside it, so `$HOME` itself would - // sit inside the edit cooldown and every content search would end - // with "1 file being indexed, try again shortly". + // extension. A directory's mtime changes whenever an entry inside it + // does, so `$HOME` itself would sit inside the edit cooldown; a FIFO + // blocks the worker that opens it, and with it the whole pass. let settled = match std::fs::symlink_metadata(&path) { - Err(_) => true, // gone before the pass reached it - Ok(md) => md.is_dir(), // nothing to extract from a directory + Err(_) => true, // gone before the pass reached it + Ok(md) => !md.is_file(), }; if !is_extraction_candidate(&path) || settled { self.after = Some(path_key); diff --git a/apps/big-search/src/content/tests.rs b/apps/big-search/src/content/tests.rs index 71cf0e3..e2438a9 100644 --- a/apps/big-search/src/content/tests.rs +++ b/apps/big-search/src/content/tests.rs @@ -12,7 +12,8 @@ fn pending_batch_reports_more_work() { let content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); let batch = pending_batch_with_byte_limit( vec![first.clone(), second.clone()], &content_state, @@ -25,8 +26,6 @@ fn pending_batch_reports_more_work() { let batch = pending_batch_with_byte_limit(vec![second.clone()], &content_state, 2, u64::MAX); assert_eq!(batch.files, vec![second]); assert!(!batch.has_more); - - std::fs::remove_dir_all(&base).ok(); } /// A tag write changes an extended attribute and nothing else, so only @@ -41,7 +40,8 @@ fn forgotten_row_is_read_again() { let mut content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); content_state.set(¬e, mtime, size); assert!( pending_batch_with_byte_limit(vec![note.clone()], &content_state, 10, u64::MAX) @@ -56,8 +56,6 @@ fn forgotten_row_is_read_again() { vec![note], "forgetting the row is what makes the same bytes worth reading again" ); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -71,13 +69,12 @@ fn pending_batch_stops_at_byte_budget() { let content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); let batch = pending_batch_with_byte_limit(vec![first.clone(), second], &content_state, 50, 1024 * 1024); assert_eq!(batch.files, vec![first]); assert!(batch.has_more); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -93,7 +90,8 @@ fn pending_batch_prioritizes_low_cost_files() { let content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); let batch = pending_batch_with_byte_limit( vec![large_pdf, small_note.clone()], &content_state, @@ -102,8 +100,6 @@ fn pending_batch_prioritizes_low_cost_files() { ); assert_eq!(batch.files, vec![small_note]); assert!(batch.has_more); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -122,7 +118,8 @@ fn catalog_batch_defers_recent_edits() { std::fs::write(&editing, b"conteudo").unwrap(); let mut catalog = - catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE) + .unwrap(); catalog.set(&quiet, now - 3_600, 10); // untouched for 1h catalog.set(&editing, now - 10, 20); // saved 10s ago catalog.persist().unwrap(); @@ -141,8 +138,6 @@ fn catalog_batch_defers_recent_edits() { .unwrap(); assert_eq!(warm.files.len(), 2); assert_eq!(warm.deferred, 0); - - std::fs::remove_dir_all(&base).ok(); } /// A deleted file must stop answering content searches. @@ -202,8 +197,6 @@ fn deleted_files_stop_answering_content_searches() { // Idempotent: nothing left to prune on a second run. assert_eq!(prune_orphaned_content(&index, 100).unwrap(), (0, false)); - - std::fs::remove_dir_all(&base).ok(); } /// The sweep must not become a one-shot: clearing content state is exactly @@ -227,8 +220,6 @@ fn clearing_state_rearms_unreferenced_sweep() { !crate::index::is_unreferenced_pruned(&dir), "limpar o estado de conteudo tem de re-armar a varredura" ); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -243,16 +234,21 @@ fn skipped_entries_become_tombstones() { let vanished = base.join("apagado.md"); // Extension-less, so a sniff candidate, but nothing to extract. let folder = base.join("uma-pasta"); + // A text name on a FIFO: opening it would block the worker. + let pipe = base.join("fila.txt"); std::fs::write(&movie, b"binario").unwrap(); std::fs::write(¬e, b"texto").unwrap(); std::fs::create_dir_all(&folder).unwrap(); + crate::test_env::make_fifo(&pipe); let mut catalog = - catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE) + .unwrap(); catalog.set(&movie, 100, 50); // never an extraction candidate catalog.set(¬e, 100, 10); catalog.set(&vanished, 100, 10); catalog.set(&folder, 100, 4096); + catalog.set(&pipe, 100, 0); catalog.persist().unwrap(); let (batch, _) = @@ -264,10 +260,11 @@ fn skipped_entries_become_tombstones() { batch.non_candidates, vec![ (vanished.clone(), 100, 10), + (pipe.clone(), 100, 0), (movie.clone(), 100, 50), (folder.clone(), 100, 4096), ], - "deleted file, policy-skipped file and directory are all tombstoned" + "deleted file, FIFO, policy-skipped file and directory are all tombstoned" ); // Record the tombstones + the extracted file in the content namespace: @@ -275,7 +272,8 @@ fn skipped_entries_become_tombstones() { let mut content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); for (path, mtime, size) in &batch.non_candidates { content_state.set(path, *mtime, *size); } @@ -288,8 +286,6 @@ fn skipped_entries_become_tombstones() { assert!(next.files.is_empty()); assert!(next.non_candidates.is_empty()); assert!(!next.has_more); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -312,12 +308,66 @@ fn symlinks_skip_content_extraction() { // Through the pipeline: a link must not duplicate its target's body. let index = crate::index::open_content_or_create(&base.join("idx")).unwrap(); - index_content_limited(&index, vec![target.clone(), link.clone()], None).unwrap(); + index_content_limited(&index, vec![target.clone(), link], None).unwrap(); let hits = crate::query::search_content(&index.reader().unwrap(), "target", 10).unwrap(); assert_eq!(hits.len(), 1, "only the real file is extracted"); assert_eq!(hits[0].path, target.to_string_lossy()); +} + +#[test] +fn extraction_passes_over_fifo() { + let _lock = ENV_LOCK.lock().unwrap(); + let base = crate::test_env::scratch_dir("lsearch-content-fifo"); + let note = base.join("note.md"); + let pipe = base.join("pipe.txt"); + let _env = [ + EnvVarGuard::set("XDG_DATA_HOME", base.join("data").to_str().unwrap()), + EnvVarGuard::set("XDG_CONFIG_HOME", base.join("config").to_str().unwrap()), + ]; + std::fs::write(¬e, b"reachable body").unwrap(); + crate::test_env::make_fifo(&pipe); + + // A file listed by a watcher event skips the selection's settling. + let index = crate::index::open_content_or_create(&base.join("idx")).unwrap(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let worker_index = index.clone(); + std::thread::spawn(move || { + let indexed = index_content_limited(&worker_index, vec![pipe, note], None); + let _ = done_tx.send(indexed.map_err(|e| format!("{e:#}"))); + }); + let indexed = done_rx + .recv_timeout(Duration::from_secs(30)) + .expect("extraction waits on the FIFO"); + assert_eq!(indexed, Ok(1)); + let hits = crate::query::search_content(&index.reader().unwrap(), "reachable", 10).unwrap(); + assert_eq!(hits.len(), 1); +} + +/// A file another process holds a write lease on is left pending, not recorded +/// unread: the pass after the lease is gone indexes it. +#[test] +fn leased_file_waits_for_next_pass() { + let _lock = ENV_LOCK.lock().unwrap(); + let base = crate::test_env::scratch_dir("lsearch-content-lease"); + let shared = base.join("shared.md"); + let _env = [ + EnvVarGuard::set("XDG_DATA_HOME", base.join("data").to_str().unwrap()), + EnvVarGuard::set("XDG_CONFIG_HOME", base.join("config").to_str().unwrap()), + ]; + std::fs::write(&shared, b"leased body").unwrap(); + let index = crate::index::open_content_or_create(&base.join("idx")).unwrap(); - std::fs::remove_dir_all(&base).ok(); + let mut holder = crate::test_env::hold_write_lease(&shared); + let under_lease = index_content_limited(&index, vec![shared.clone()], None); + holder.kill().unwrap(); + holder.wait().unwrap(); + assert_eq!(under_lease.unwrap(), 0); + assert_eq!( + index_content_limited(&index, vec![shared], None).unwrap(), + 1 + ); + let hits = crate::query::search_content(&index.reader().unwrap(), "leased", 10).unwrap(); + assert_eq!(hits.len(), 1); } #[test] @@ -401,7 +451,8 @@ fn catalog_byte_budget_is_exclusive() { std::fs::write(path, b"x").unwrap(); } let mut catalog = - catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE); + catalogue::State::empty(&base.join("state.sqlite"), crate::catalogue::NAME_NAMESPACE) + .unwrap(); catalog.set(&a, 1_000, mib); catalog.set(&b, 1_000, mib); catalog.set(&c, 1_000, mib); @@ -418,8 +469,6 @@ fn catalog_byte_budget_is_exclusive() { pending_catalog_batch_with_byte_limit(&catalog, None, 10, 1, Duration::ZERO).unwrap(); assert_eq!(one.files, vec![a.clone()]); assert!(one.has_more); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -435,7 +484,8 @@ fn pending_byte_budget_is_exclusive() { let content_state = catalogue::State::empty( &base.join("state.sqlite"), crate::catalogue::CONTENT_NAMESPACE, - ); + ) + .unwrap(); let files = vec![first.clone(), second.clone(), third.clone()]; let batch = pending_batch_with_byte_limit(files.clone(), &content_state, 50, 2 * mib as u64); @@ -445,8 +495,6 @@ fn pending_byte_budget_is_exclusive() { let all = pending_batch_with_byte_limit(files, &content_state, 50, 8 * mib as u64); assert_eq!(all.files, vec![first, second, third]); assert!(!all.has_more); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -508,8 +556,6 @@ fn catalog_pass_indexes_every_batch() { index_content_limited(&index, extra.to_vec(), None).unwrap(), 2 ); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -525,7 +571,7 @@ fn body_upsert_keeps_one_document() { writer.commit().unwrap(); } let reader = content_index.reader().unwrap(); - assert_eq!(crate::query::count(&reader).unwrap(), 1); + assert_eq!(crate::query::count(&reader), 1); assert_eq!( crate::query::search_content(&reader, "new", 10) .unwrap() @@ -537,6 +583,4 @@ fn body_upsert_keeps_one_document() { .unwrap() .is_empty() ); - - std::fs::remove_dir_all(&base).ok(); } diff --git a/apps/big-search/src/content_dedupe.rs b/apps/big-search/src/content_dedupe.rs index fd216a8..c05ad09 100644 --- a/apps/big-search/src/content_dedupe.rs +++ b/apps/big-search/src/content_dedupe.rs @@ -208,13 +208,17 @@ impl ContentSignatures { } } +#[expect( + clippy::disallowed_methods, + reason = "legacy: migrate to history::identity, since the signatures persist st_dev" +)] fn physical_content_identity(path: &Path, size: u64) -> Option { if size == 0 { return None; } - let file = std::fs::File::open(path).ok()?; + let file = crate::extract::open_regular(path)?; let metadata = file.metadata().ok()?; - if !metadata.is_file() || metadata.len() != size { + if metadata.len() != size { return None; } if metadata.nlink() > 1 { @@ -380,8 +384,6 @@ mod tests { signatures.claim_identity(&second, identity(), |_| identity()), ContentClaim::Duplicate ); - - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -429,7 +431,6 @@ mod tests { signatures.claim_identity(&first, identity(), |_| identity()), ContentClaim::Duplicate ); - std::fs::remove_dir_all(&base).ok(); } #[test] @@ -449,8 +450,23 @@ mod tests { signatures.claim_identity(&second, None, |_| unreachable!()), ContentClaim::Unique ); + } - std::fs::remove_dir_all(&base).ok(); + /// A FIFO renamed in after the worker's check has no identity, and no wait + /// for a writer under the signature lock. + #[test] + fn fifo_has_no_identity_without_waiting() { + let base = crate::test_env::scratch_dir("content-dedupe-fifo"); + let fifo = base.join("a.bin"); + crate::test_env::make_fifo(&fifo); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = done_tx.send(physical_content_identity(&fifo, 4096)); + }); + let identity = done_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("physical_content_identity waits on the FIFO"); + assert_eq!(identity, None); } #[test] @@ -459,7 +475,7 @@ mod tests { .unwrap() .join("target") .join(format!("lsearch-content-reflink-{}", std::process::id())); - std::fs::remove_dir_all(&base).ok(); + let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(&base).unwrap(); let first = base.join("first.bin"); let second = base.join("second.bin"); @@ -475,14 +491,16 @@ mod tests { state.to_le_bytes() }) .collect(); - std::fs::write(&first, bytes).unwrap(); + let mut written = std::fs::File::create(&first).unwrap(); + written.write_all(&bytes).unwrap(); // Force extent allocation: a freshly written file may still be in // delalloc, which FIEMAP reports as an unsafe flag → identity None and // a flaky assert depending on writeback timing. - std::fs::File::open(&first).unwrap().sync_all().unwrap(); + written.sync_all().unwrap(); + drop(written); if crate::history::clone_file(&first, &second).is_err() { - std::fs::remove_dir_all(&base).ok(); + let _ = std::fs::remove_dir_all(&base); eprintln!("skipped: this filesystem cannot clone files"); return; } @@ -490,7 +508,7 @@ mod tests { let size = std::fs::metadata(&first).unwrap().len(); let first_identity = physical_content_identity(&first, size); let second_identity = physical_content_identity(&second, size); - std::fs::remove_dir_all(&base).ok(); + let _ = std::fs::remove_dir_all(&base); // Extents with unsafe FIEMAP flags (encrypted, inline) have no identity // by design; then neither clone may have one. if first_identity.is_none() { diff --git a/apps/big-search/src/extract.rs b/apps/big-search/src/extract.rs index 0001caa..51c4e04 100644 --- a/apps/big-search/src/extract.rs +++ b/apps/big-search/src/extract.rs @@ -5,10 +5,72 @@ mod epub; pub(crate) use crate::extract_pdf::read_pdf; +use crate::fold::{fold_lower, fold_lower_into}; use epub::read_epub; use std::io::Read; use std::path::Path; +/// `path` opened for reading when it is a regular file, a link followed: the +/// readers' one way to a file's bytes. A `stat` taken before cannot see a FIFO +/// renamed into place since, and a plain open of one waits for a writer. +pub(crate) fn open_regular(path: &Path) -> Option { + open_regular_with(path, 0).ok() +} + +/// Why [`open_regular_with`] gave no file. +pub(crate) enum Unopened { + /// Not a regular file, or not readable: read it again once it changes. + Refused, + /// Under another process's write lease, or no descriptor free: a later pass may read it. + Busy, +} + +impl From for Unopened { + fn from(error: std::io::Error) -> Self { + match error.raw_os_error() { + Some(libc::EWOULDBLOCK | libc::EMFILE | libc::ENFILE) => Self::Busy, + _ => Self::Refused, + } + } +} + +/// Set once a reopen has found no `/proc/self/fd`. +static PROC_FD_MISSING_REPORTED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// [`open_regular`] with `flags` added to the first open, such as `O_NOFOLLOW`. +pub(crate) fn open_regular_with( + path: &Path, + flags: libc::c_int, +) -> Result { + use std::os::fd::AsRawFd as _; + use std::os::unix::fs::OpenOptionsExt as _; + // `O_PATH` runs no FIFO or device open. The non-blocking reopen fails at once + // under a write lease and, while open, bars one, so the blocking reopen beside + // it cannot wait. + let handle = std::fs::OpenOptions::new() + .read(true) + .custom_flags(flags | libc::O_PATH) + .open(path)?; + if !handle.metadata()?.is_file() { + return Err(Unopened::Refused); + } + let reopen_path = format!("/proc/self/fd/{}", handle.as_raw_fd()); + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(&reopen_path) + .and_then(|_lease_guard| std::fs::File::open(&reopen_path)) + .map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound + && !PROC_FD_MISSING_REPORTED.swap(true, std::sync::atomic::Ordering::Relaxed) + { + log::warn!("documents are skipped unread: /proc/self/fd is unavailable ({error})"); + } + error.into() + }) +} + /// Adaptive cap on extracted text per file, sized by the machine's memory to /// bound index and memory cost. `BIG_SEARCH_EXTRACT_MAX_MB` or config /// `[defaults].extract_max_mb` can override the automatic value. @@ -78,10 +140,7 @@ fn read_doc(path: &Path) -> Option<(String, Option)> { return None; } let mut magic = [0u8; 8]; - std::fs::File::open(path) - .ok()? - .read_exact(&mut magic) - .ok()?; + open_regular(path)?.read_exact(&mut magic).ok()?; if magic == [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1] { crate::extract_pdf::read_word(path).map(|text| (text, None)) } else if magic.starts_with(b"{\\rtf") { @@ -108,8 +167,7 @@ fn read_capped_bytes(path: &Path) -> Option> { let cap = max_extract_bytes(); // Sized up front: a text file is read whole, and growth copies it. let mut buf = Vec::with_capacity(size.min(cap as u64) as usize); - std::fs::File::open(path) - .ok()? + open_regular(path)? .take(cap as u64) .read_to_end(&mut buf) .ok()?; @@ -397,7 +455,7 @@ fn read_office(path: &Path, ext: &str) -> Option { if exceeds_input_cap(path) { return None; } - let file = std::fs::File::open(path).ok()?; + let file = open_regular(path)?; office_text_from_reader(std::io::BufReader::new(file), ext) } @@ -434,7 +492,7 @@ pub(crate) fn capped_zip( pub(crate) fn open_archive( path: &Path, ) -> Option>> { - capped_zip(std::io::BufReader::new(std::fs::File::open(path).ok()?)) + capped_zip(std::io::BufReader::new(open_regular(path)?)) } /// Slides, worksheets, speaker notes, headers or footers read from one archive, @@ -521,108 +579,6 @@ pub fn office_text_from_reader( } } -/// Lowercase and fold `s` the way every comparison of names, pages and -/// content words does, so a person types a word the way they would write it -/// by hand: -/// -/// - the text is first composed as `compose` says; -/// - accents and other marks go, whether the text carries them precomposed -/// ("relatório") or decomposed, as names unpacked from macOS archives do -/// ("relato\u{301}rio"); so does the dot that "İ" lowercases with; -/// - Latin letters fold through tantivy's `AsciiFoldingFilter`, the table the -/// content analyzer uses: "ß" is "ss", "Ł" is "l", "Æ" is "ae"; -/// - the other scripts fold as `fold_script_into` says. -/// -/// ASCII text is only lowercased. -#[must_use] -pub fn fold_lower(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - fold_lower_into(s, &mut out); - out -} - -/// The same, into a buffer the caller reuses: page after page, that is one -/// allocation instead of one per page. -pub fn fold_lower_into(s: &str, out: &mut String) { - if s.is_ascii() { - out.extend(s.chars().map(|c| c.to_ascii_lowercase())); - return; - } - let lowered: String = compose(s).chars().flat_map(char::to_lowercase).collect(); - let mut folded = String::with_capacity(lowered.len()); - fold_script_into(&lowered, &mut folded); - ASCII_FOLDING.with(|analyzer| { - let mut analyzer = analyzer.borrow_mut(); - let mut stream = analyzer.token_stream(&folded); - if stream.advance() { - out.push_str(&stream.token().text); - } - }); -} - -/// `text` in NFKC, the form every comparison and every tokenizer starts from: -/// Korean syllables decomposed into jamo and kana with a separate voicing mark -/// (as macOS writes names), halfwidth katakana, Arabic presentation forms, -/// compatibility ideographs, fullwidth Latin and ligatures ("fi") become the -/// characters people type. Text already in that form, nearly all of it, is not -/// copied. -/// -/// A copy stops at [`max_extract_bytes`]: one character can expand eighteenfold -/// ("ﷺ"), and the extraction cap counts bytes before normalization. -pub(crate) fn compose(text: &str) -> std::borrow::Cow<'_, str> { - use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfkc_quick}; - if text.is_ascii() || is_nfkc_quick(text.chars()) == IsNormalized::Yes { - return std::borrow::Cow::Borrowed(text); - } - let cap = max_extract_bytes(); - let mut out = String::with_capacity(text.len().min(cap)); - for c in text.nfkc() { - if out.len() + c.len_utf8() > cap { - break; - } - out.push(c); - } - std::borrow::Cow::Owned(out) -} - -/// The folding of lowercase text that `AsciiFoldingFilter` leaves to others: -/// combining marks dropped; Russian "ё" written "е", as it mostly is; Greek -/// without its accents and with final "ς" as "σ"; Arabic alef without hamza, -/// "ى" and Persian "ی" as "ي", Persian "ک" as "ك", "ة" as "ه" (each typed for -/// the other, by keyboard or by habit), and no vowel signs or tatweel; -/// traditional Chinese characters as their simplified forms ("會議" is "会议"). -pub(crate) fn fold_script_into(lowered: &str, out: &mut String) { - for c in lowered.chars() { - match c { - '\u{0300}'..='\u{036F}' | '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' => {} - 'ё' => out.push('е'), - 'ς' => out.push('σ'), - 'ά' => out.push('α'), - 'έ' => out.push('ε'), - 'ή' => out.push('η'), - 'ί' | 'ϊ' | 'ΐ' => out.push('ι'), - 'ό' => out.push('ο'), - 'ύ' | 'ϋ' | 'ΰ' => out.push('υ'), - 'ώ' => out.push('ω'), - 'أ' | 'إ' | 'آ' | 'ٱ' => out.push('ا'), - 'ى' | 'ی' => out.push('ي'), - 'ک' => out.push('ك'), - 'ة' => out.push('ه'), - c => out.push(crate::simplified_chinese::simplified(c)), - } - } -} - -thread_local! { - /// The whole text as one token through `AsciiFoldingFilter`. - static ASCII_FOLDING: std::cell::RefCell = - std::cell::RefCell::new( - tantivy::tokenizer::TextAnalyzer::builder(tantivy::tokenizer::RawTokenizer::default()) - .filter(tantivy::tokenizer::AsciiFoldingFilter) - .build(), - ); -} - /// 1-based page (PDF) / slide (PPTX) numbers whose text contains *all* `terms`. /// Empty for formats without fixed pages (docx/odt flow, txt, …). /// diff --git a/apps/big-search/src/extract/tests.rs b/apps/big-search/src/extract/tests.rs index 12677e5..865dc1e 100644 --- a/apps/big-search/src/extract/tests.rs +++ b/apps/big-search/src/extract/tests.rs @@ -1,6 +1,60 @@ use super::*; use std::io::Write; +/// The content worker checks a path is a regular file before the readers open +/// it; a FIFO renamed into place between the two gets no text instead of a wait. +#[test] +fn readers_pass_over_fifo() { + let dir = temporary_extract_dir("fifo"); + for name in [ + "a.txt", "a.html", "a.docx", "a.epub", "a.eml", "a.rtf", "a.doc", + ] { + let path = dir.join(name); + crate::test_env::make_fifo(&path); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let reader_path = path.clone(); + std::thread::spawn(move || { + let _ = done_tx.send(content(&reader_path)); + }); + let text = done_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap_or_else(|_| panic!("{name}: the reader waits on the FIFO")); + assert_eq!(text, None, "{name}"); + } + let file = dir.join("b.txt"); + std::fs::write(&file, "beta").unwrap(); + let link = dir.join("link.txt"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + for opened in [&file, &link] { + let mut text = String::new(); + open_regular(opened) + .unwrap() + .read_to_string(&mut text) + .unwrap(); + assert_eq!(text, "beta", "{}", opened.display()); + } + assert!(open_regular_with(&link, libc::O_NOFOLLOW).is_err()); + assert!(open_regular(&dir).is_none()); +} + +/// A write lease held by another process (a Samba oplock, an NFS delegation) +/// skips the file at once instead of waiting `lease-break-time` for its break. +#[test] +fn readers_pass_over_write_lease() { + let dir = temporary_extract_dir("lease"); + let path = dir.join("shared.txt"); + std::fs::write(&path, "beta").unwrap(); + let mut holder = crate::test_env::hold_write_lease(&path); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = done_tx.send(open_regular(&path).is_none()); + }); + let skipped = done_rx.recv_timeout(std::time::Duration::from_secs(10)); + holder.kill().unwrap(); + holder.wait().unwrap(); + assert_eq!(skipped, Ok(true), "the reader waits on the lease break"); +} + #[test] fn pages_and_markdown_name_titles() { assert_eq!( @@ -55,7 +109,6 @@ fn html_page_indexed_as_text() { assert_eq!(page.declared_title.as_deref(), Some("Ata")); assert_eq!(page.prominent, ["Reunião"]); assert!(page.text.contains("Relatório")); - std::fs::remove_dir_all(&dir).ok(); } #[test] @@ -63,19 +116,6 @@ fn unclosed_script_hides_the_rest() { assert_eq!(html_text("

kept