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