search.rs
⎇
Raw
1//! `GET /api/search` — index-free name and content search, streamed as SSE.
2//!
3//! No index, by design: every search walks the selected root with
4//! [`ignore::WalkParallel`] (fd/ripgrep's parallel walker, with all its
5//! filters off: hidden and gitignored entries are searched too) and matches
6//! on the fly.
7//!
8//! * **Name** (scope `name`/`both`): every word of the query must occur
9//! (case-insensitive) in the entry's own name — the last path component,
10//! not the whole relative path — so "invoice 2025" matches
11//! `invoice_2025-11_final.pdf` but a file is not a hit merely for sitting
12//! inside a directory whose name matches.
13//! * **Content** (scope `content`/`both`): the whole query as a literal,
14//! case-insensitive, ripgrep-style scan via the `grep` crates (ripgrep's
15//! engine). Binary files are skipped by NUL detection, files over
16//! [`SEARCH_MAX_FILE_BYTES`] are skipped and counted.
17//!
18//! Both scopes run in one walk, so `both` reads the tree once and its file
19//! and match events interleave.
20//!
21//! Results are one JSON object per SSE event, in the order found; the stream
22//! always ends with a `done` event. The search stops when the client goes
23//! away: axum drops the response body stream, the channel receiver is
24//! dropped with it, and the walkers bail at the next `is_closed` check —
25//! no per-search budgets or timeouts.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicUsize, Ordering};
30use std::time::Instant;
31
32use api_types::SearchEvent;
33use axum::extract::{Query as AxumQuery, State};
34use axum::http::StatusCode;
35use axum::response::sse::{Event, Sse};
36use axum::response::{IntoResponse, Response};
37use futures_util::StreamExt;
38use grep::regex::RegexMatcherBuilder;
39use grep::searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
40use ignore::{DirEntry, WalkBuilder, WalkState};
41use serde::Deserialize;
42
43use crate::api::common::{AuthUser, blocking};
44use crate::db::RootRow;
45use crate::error::{ApiError, AppState};
46
47/// Concurrent searches. A search owns a pool of walker threads, so the two
48/// caps together bound the threads a burst of searches can create.
49static SEARCH_SLOTS: std::sync::LazyLock<Arc<tokio::sync::Semaphore>> =
50 std::sync::LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(4)));
51
52/// Walker threads per search: the machine's parallelism, capped at 8. The
53/// walk is IO-bound, so more threads buy nothing past that.
54fn walker_threads() -> usize {
55 std::thread::available_parallelism()
56 .map(|n| n.get())
57 .unwrap_or(4)
58 .min(8)
59}
60
61/// Content search skips files larger than this. There is no search budget
62/// (the client can stop at any time), but a multi-gigabyte text file would
63/// stall its worker indefinitely — ripgrep has no such cap, we do.
64const SEARCH_MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
65/// A matched line is truncated to this many bytes on the wire.
66const SEARCH_MAX_LINE_BYTES: usize = 500;
67/// Total matched lines emitted per search. A one-character query can match
68/// tens of thousands of lines; unbounded streaming would flood the client.
69const SEARCH_MAX_MATCH_EVENTS: usize = 50_000;
70/// Matched lines emitted per file (mirrors the client's render cap).
71const SEARCH_MAX_LINES_PER_FILE: usize = 500;
72
73/// The field names are the shared [`api_types::P_Q`] / [`api_types::P_SCOPE`]
74/// / [`api_types::P_ROOT`] / [`api_types::P_PATH`] constants. `#[serde(rename)]`
75/// only takes a literal, so that link cannot be written here;
76/// `tests::query_fields_are_the_shared_constants` pins it instead.
77#[derive(Debug, Deserialize)]
78pub(super) struct SearchQuery {
79 q: Option<String>,
80 /// `name` (default), `content` or `both`.
81 #[serde(default)]
82 scope: Option<String>,
83 /// The root to search; omitted = the caller's first root.
84 #[serde(default)]
85 root: Option<i64>,
86 /// Folder inside the root to start in; omitted = the whole root.
87 #[serde(default)]
88 path: Option<String>,
89}
90
91pub(super) async fn search(
92 State(state): State<Arc<AppState>>,
93 auth: AuthUser,
94 AxumQuery(query): AxumQuery<SearchQuery>,
95) -> Result<Response, ApiError> {
96 // Search is a session-user feature: a share visitor has no search UI and
97 // must not probe files outside the shared item.
98 if auth.share.is_some() {
99 return Err(ApiError::localized(
100 StatusCode::FORBIDDEN,
101 "search requires a signed-in session",
102 "err_search_forbidden",
103 ));
104 }
105 let q = query
106 .q
107 .as_deref()
108 .map(str::trim)
109 .filter(|q| !q.is_empty())
110 .ok_or_else(|| {
111 ApiError::localized(
112 StatusCode::BAD_REQUEST,
113 "search requires a non-empty query",
114 "err_search_empty_query",
115 )
116 })?;
117
118 let scope = query.scope.as_deref().unwrap_or("name");
119 let want_name = matches!(scope, "name" | "both");
120 let want_content = matches!(scope, "content" | "both");
121 if !(want_name || want_content) {
122 return Err(ApiError::localized(
123 StatusCode::BAD_REQUEST,
124 "scope must be name, content or both",
125 "err_search_bad_scope",
126 ));
127 }
128
129 // Only a root the caller actually has.
130 let root = match query.root {
131 Some(id) => auth.roots.iter().find(|r| r.id == id),
132 None => auth.roots.first(),
133 }
134 .cloned()
135 .ok_or_else(|| {
136 ApiError::localized(
137 StatusCode::FORBIDDEN,
138 "root not accessible",
139 "err_root_forbidden",
140 )
141 })?;
142
143 // The start folder must exist inside the root. Only validated here: the
144 // walk joins the un-canonicalized paths itself, so every result keeps
145 // the root's prefix and stays root-relative.
146 let start_rel = query
147 .path
148 .as_deref()
149 .unwrap_or("")
150 .trim_matches('/')
151 .to_string();
152 let (server_root, root_path, start) =
153 (state.root.clone(), root.path.clone(), start_rel.clone());
154 blocking(move || crate::fs::resolve_dir(&server_root, &root_path, &start)).await?;
155
156 // One slot per running search, held until the walk ends. Each search owns
157 // a pool of walker threads, so unbounded concurrency would swamp the box.
158 // No queueing: a waiting request would hang without any response.
159 let slot = SEARCH_SLOTS.clone().try_acquire_owned().map_err(|_| {
160 ApiError::new(
161 StatusCode::SERVICE_UNAVAILABLE,
162 "too many searches are running",
163 )
164 })?;
165
166 let events = search_stream(
167 q.to_string(),
168 want_name,
169 want_content,
170 root,
171 start_rel,
172 state.root.clone(),
173 slot,
174 );
175 // `Sse` does the `data: <json>\n\n` framing and the content-type and
176 // cache headers; nginx and friends still need telling not to buffer.
177 let sse = Sse::new(events.map(|ev| Event::default().json_data(&ev)));
178 Ok(([("x-accel-buffering", "no")], sse).into_response())
179}
180
181/// Shared state of the search, behind one `Arc` that every walk visitor
182/// clones a handle to. The counters are atomics so they can be updated from
183/// the walker threads lock-free.
184struct SearchState {
185 tx: tokio::sync::mpsc::Sender<SearchEvent>,
186 words: Vec<String>,
187 root: RootRow,
188 /// Where the walk starts, relative to the root ("" = the root itself).
189 start_rel: String,
190 server_root: PathBuf,
191 started: Instant,
192 /// Directory entries visited.
193 scanned: AtomicUsize,
194 /// Files skipped for content search (over the size cap).
195 skipped: AtomicUsize,
196 names: AtomicUsize,
197 matches: AtomicUsize,
198}
199
200/// The search itself: one walk over the root, matching names and grepping
201/// contents as it goes, sending events as they are found. Runs on a plain
202/// thread — `WalkParallel` manages its own worker pool — while the SSE body
203/// stream polls the receiver.
204///
205/// Stopping: when the client goes away, axum drops the body stream, which
206/// drops the receiver. Every `is_closed` check in the walkers then yields
207/// `WalkState::Quit` at the next entry, so the walk unwinds promptly.
208fn search_stream(
209 q: String,
210 want_name: bool,
211 want_content: bool,
212 root: RootRow,
213 start_rel: String,
214 server_root: PathBuf,
215 slot: tokio::sync::OwnedSemaphorePermit,
216) -> impl futures_util::Stream<Item = SearchEvent> + Send {
217 let (tx, rx) = tokio::sync::mpsc::channel::<SearchEvent>(256);
218 let state = Arc::new(SearchState {
219 tx,
220 words: q.split_whitespace().map(|w| w.to_lowercase()).collect(),
221 root,
222 start_rel,
223 server_root,
224 started: Instant::now(),
225 scanned: AtomicUsize::new(0),
226 skipped: AtomicUsize::new(0),
227 names: AtomicUsize::new(0),
228 matches: AtomicUsize::new(0),
229 });
230
231 std::thread::spawn(move || {
232 // Released when the walk is done, not when the client stops reading.
233 let _slot = slot;
234 walk(&state, &q, want_name, want_content);
235 // `stopped`: the receiver went away (client stopped or navigated)
236 // or the match cap was hit, before the walk finished.
237 let stopped = state.tx.is_closed()
238 || state.matches.load(Ordering::Relaxed) >= SEARCH_MAX_MATCH_EVENTS;
239 let _ = state.tx.blocking_send(SearchEvent::Done {
240 stopped,
241 files: state.names.load(Ordering::Relaxed),
242 matches: state.matches.load(Ordering::Relaxed),
243 scanned: state.scanned.load(Ordering::Relaxed),
244 skipped: state.skipped.load(Ordering::Relaxed),
245 elapsed_ms: state.started.elapsed().as_millis() as u64,
246 });
247 });
248
249 tokio_stream::wrappers::ReceiverStream::new(rx)
250}
251
252/// True when every query word occurs in `name`. Both are already lowercased.
253///
254/// `name` is the entry's own name, never its path — see the module docs.
255fn name_matches(words: &[String], name: &str) -> bool {
256 words.iter().all(|w| name.contains(w.as_str()))
257}
258
259/// Walks the root in parallel, matching each entry against the wanted
260/// scopes. The visitor is cloned once per worker thread, and returns
261/// [`WalkState::Quit`] to stop the whole walk (client went away).
262fn walk(st: &Arc<SearchState>, q: &str, want_name: bool, want_content: bool) {
263 let abs = st.server_root.join(&st.root.path);
264 let start = abs.join(&st.start_rel);
265 if !start.is_dir() {
266 // Root or start folder removed out from under us: nothing to search.
267 return;
268 }
269 WalkBuilder::new(&start)
270 // A file browser shows everything, so search must too: no hidden
271 // or `.gitignore`/`.ignore` filtering. Symlinks stay unfollowed.
272 .standard_filters(false)
273 .threads(walker_threads())
274 .build_parallel()
275 .run(|| {
276 let abs = abs.clone();
277 Box::new(move |result| match result {
278 Ok(entry) => visit(st, q, want_name, want_content, &entry, &abs),
279 Err(_) => WalkState::Continue, // unreadable entry: skip like fd
280 })
281 });
282}
283
284/// One walked entry: emit a name hit, grep it, or both.
285fn visit(
286 st: &Arc<SearchState>,
287 q: &str,
288 want_name: bool,
289 want_content: bool,
290 entry: &DirEntry,
291 abs: &Path,
292) -> WalkState {
293 if st.tx.is_closed() {
294 return WalkState::Quit;
295 }
296 st.scanned.fetch_add(1, Ordering::Relaxed);
297 // The start folder itself (depth 0) is not a result. Paths stay
298 // relative to the root, not to the start folder, so the client opens
299 // them the same way as any listing entry.
300 if entry.depth() == 0 {
301 return WalkState::Continue;
302 }
303 let Some(rel) = entry.path().strip_prefix(abs).ok() else {
304 return WalkState::Continue;
305 };
306 // Original case, unlike the name used for matching: this path is what
307 // the client opens the entry by.
308 let rel = rel.to_string_lossy().replace('\\', "/");
309 let is_dir = entry.file_type().is_some_and(|t| t.is_dir());
310
311 if want_name {
312 // Matched against the entry's own name, not its path: matching the
313 // path makes every descendant of a matching directory a hit too
314 // ("e" matching `search-test/` dragged in all 400 files under it),
315 // which buries the entries the user actually named.
316 let name = entry.file_name().to_string_lossy().to_lowercase();
317 if name_matches(&st.words, &name) {
318 st.names.fetch_add(1, Ordering::Relaxed);
319 let size = if is_dir {
320 0
321 } else {
322 entry.metadata().map(|m| m.len()).unwrap_or(0)
323 };
324 let ev = SearchEvent::File {
325 root_id: st.root.id,
326 path: rel.clone(),
327 size,
328 is_dir,
329 // Same sniff a directory listing does, so the client needs no
330 // extension table of its own. One open() per name hit, on the
331 // walker thread that already stat'ed the entry.
332 kind: crate::fs::detect_kind(entry.path(), is_dir),
333 };
334 // blocking_send: the channel cap provides backpressure against a
335 // slow client. Err means the receiver is gone: stop the search.
336 if st.tx.blocking_send(ev).is_err() {
337 return WalkState::Quit;
338 }
339 }
340 }
341
342 if want_content && entry.file_type().is_some_and(|t| t.is_file()) {
343 if entry.metadata().map(|m| m.len()).unwrap_or(0) > SEARCH_MAX_FILE_BYTES {
344 st.skipped.fetch_add(1, Ordering::Relaxed);
345 return WalkState::Continue;
346 }
347 search_one_file(q, entry.path(), rel, st);
348 if st.tx.is_closed() || st.matches.load(Ordering::Relaxed) >= SEARCH_MAX_MATCH_EVENTS {
349 return WalkState::Quit;
350 }
351 }
352 WalkState::Continue
353}
354
355/// Grep one file with a fresh literal matcher. The matcher is built per file
356/// rather than shared: `RegexMatcher` is not `Sync`, so it cannot cross the
357/// walk's thread boundary; a case-insensitive literal compiles in
358/// microseconds, negligible next to the file read it protects.
359fn search_one_file(q: &str, path: &Path, rel: String, st: &SearchState) {
360 let matcher = match RegexMatcherBuilder::new()
361 .case_insensitive(true)
362 .build_literals(&[q])
363 {
364 Ok(m) => m,
365 Err(_) => return,
366 };
367 let mut searcher = SearcherBuilder::new().line_number(true).build();
368 // ripgrep's default: a NUL byte means "binary, stop".
369 searcher.set_binary_detection(BinaryDetection::quit(0));
370
371 let mut sink = MatchSink { st, lines: 0, rel };
372 // I/O errors (permissions, vanished file): skip like fd does.
373 let _ = searcher.search_path(matcher, path, &mut sink);
374}
375
376/// Pushes each matched line onto the event channel. `blocking_send` is
377/// correct here: it runs on the walk's worker threads, and the channel cap
378/// provides backpressure against a slow client.
379struct MatchSink<'a> {
380 st: &'a SearchState,
381 /// Matched lines emitted for the current file.
382 lines: usize,
383 rel: String,
384}
385
386impl Sink for MatchSink<'_> {
387 type Error = std::io::Error;
388
389 fn matched(&mut self, _searcher: &Searcher, mat: &SinkMatch) -> Result<bool, Self::Error> {
390 if self.st.tx.is_closed() || self.lines >= SEARCH_MAX_LINES_PER_FILE {
391 return Ok(false);
392 }
393 let line = match mat.line_number() {
394 Some(n) => n,
395 None => return Ok(true),
396 };
397 // Single-line matcher: exactly one line per match.
398 let text = match mat.lines().next() {
399 Some(l) => truncate_line(l),
400 None => return Ok(true),
401 };
402 // Cap check before the increment, so the counted number of matches
403 // is exactly the number of matches delivered.
404 if self.st.matches.load(Ordering::Relaxed) >= SEARCH_MAX_MATCH_EVENTS {
405 return Ok(false);
406 }
407 self.lines += 1;
408 self.st.matches.fetch_add(1, Ordering::Relaxed);
409 match self.st.tx.blocking_send(SearchEvent::Match {
410 root_id: self.st.root.id,
411 path: self.rel.clone(),
412 line,
413 text,
414 }) {
415 Ok(()) => Ok(true),
416 // Receiver gone: stop this file; the walker quits on the next
417 // `is_closed` check.
418 Err(_) => Ok(false),
419 }
420 }
421}
422
423/// Strips the line terminator and truncates at [`SEARCH_MAX_LINE_BYTES`].
424///
425/// A character split by the cap decodes to one replacement character, as
426/// does any invalid byte; the cap is therefore a byte cap on the input, not
427/// exactly on the output.
428fn truncate_line(line: &[u8]) -> String {
429 let end = line
430 .iter()
431 .rposition(|b| *b != b'\n' && *b != b'\r')
432 .map_or(0, |i| i + 1);
433 String::from_utf8_lossy(&line[..end.min(SEARCH_MAX_LINE_BYTES)]).into_owned()
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 /// A rename of one of the `P_*` constants without the matching field
441 /// rename would silently stop the server from reading the parameter the
442 /// client sends. This builds the query string from the constants and
443 /// runs the real extractor over it.
444 #[test]
445 fn query_fields_are_the_shared_constants() {
446 use api_types::{P_PATH, P_Q, P_ROOT, P_SCOPE};
447 let uri: axum::http::Uri =
448 format!("/api/search?{P_Q}=invoice&{P_SCOPE}=both&{P_ROOT}=7&{P_PATH}=docs")
449 .parse()
450 .unwrap();
451 let q: SearchQuery = AxumQuery::try_from_uri(&uri).unwrap().0;
452 assert_eq!(q.q.as_deref(), Some("invoice"));
453 assert_eq!(q.scope.as_deref(), Some("both"));
454 assert_eq!(q.root, Some(7));
455 assert_eq!(q.path.as_deref(), Some("docs"));
456 }
457
458 #[test]
459 fn name_match_needs_every_word() {
460 let words = vec!["invoice".to_string(), "2025".to_string()];
461 assert!(name_matches(&words, "invoice_2025-11_final.pdf"));
462 assert!(!name_matches(&words, "invoice_2024.pdf"));
463 }
464
465 #[test]
466 fn name_match_ignores_the_parent_path() {
467 // The caller passes the entry's own name, so a file does not match
468 // just because an ancestor directory does.
469 let words = vec!["test".to_string()];
470 assert!(name_matches(&words, "test-notes.md"));
471 assert!(!name_matches(&words, "f12.txt"));
472 }
473
474 #[test]
475 fn truncation_strips_terminator() {
476 assert_eq!(truncate_line(b"hello\n"), "hello");
477 assert_eq!(truncate_line(b"hello\r\n"), "hello");
478 assert_eq!(truncate_line(b"no newline"), "no newline");
479 assert_eq!(truncate_line(b"\n"), "");
480 }
481
482 #[test]
483 fn truncation_caps_length() {
484 let long = vec![b'x'; 600];
485 let t = truncate_line(&long);
486 assert_eq!(t.len(), SEARCH_MAX_LINE_BYTES);
487 }
488
489 #[test]
490 fn truncation_keeps_utf8_boundary() {
491 // 3-byte chars; the cap must not split one.
492 let long: Vec<u8> = "ä".repeat(200).into_bytes();
493 let t = truncate_line(&long);
494 assert!(t.len() <= SEARCH_MAX_LINE_BYTES);
495 assert!(t.chars().all(|c| c == 'ä'));
496 }
497}
498