buntrail-services 0.1.0

Filesystem, Git, terminal, search and connection services.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::contracts::SearchService;
use buntrail_core::contracts::{async_types::*, *};
use futures_core::Stream;
use std::{
    collections::VecDeque,
    io::Read,
    os::fd::AsRawFd,
    path::PathBuf,
    pin::Pin,
    process::{Command, Stdio},
    sync::{
        Arc, Condvar, Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    task::{Context, Poll, Waker},
    time::Duration,
};
pub const DEFAULT_EXCLUSIONS: &[&str] = &[
    "**/node_modules/**",
    "**/vendor/**",
    "**/target/**",
    "**/.build/**",
    "**/dist/**",
    "**/build/**",
    "**/coverage/**",
    "**/.git/**",
];
pub const MAX_MATCHES: u64 = 20_000;
#[derive(Clone)]
pub struct LocalSearchService {
    target: TargetIdentity,
    executable: PathBuf,
    active: Arc<AtomicUsize>,
    files: Arc<crate::files::LocalFileService>,
}
impl LocalSearchService {
    pub fn bundled(files: Arc<crate::files::LocalFileService>) -> Self {
        let executable = std::env::current_exe()
            .ok()
            .and_then(|p| {
                let directory = p.parent()?;
                let adjacent = directory.join("rg");
                if adjacent.is_file() {
                    return Some(adjacent);
                }
                let bundle = directory.parent()?.parent()?;
                (bundle.extension() == Some(std::ffi::OsStr::new("app")))
                    .then(|| directory.join("../Resources/Search/rg"))
            })
            .unwrap_or_else(|| {
                std::env::current_exe()
                    .expect("current executable")
                    .with_file_name("rg")
            });
        Self::with_executable(files, executable)
    }
    /// Use a caller-selected ripgrep executable, without invoking a shell.
    pub fn with_executable(
        files: Arc<crate::files::LocalFileService>,
        executable: PathBuf,
    ) -> Self {
        let target = files.target().clone();
        Self {
            target,
            executable,
            active: Arc::new(AtomicUsize::new(0)),
            files,
        }
    }
    pub fn active_searches(&self) -> usize {
        self.active.load(Ordering::SeqCst)
    }
    pub fn run(
        &self,
        request: SearchRequest,
        cancel: &AtomicBool,
        mut emit: impl FnMut(SearchEvent) -> bool,
    ) {
        if self
            .active
            .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
                (n < 2).then_some(n + 1)
            })
            .is_err()
        {
            emit(SearchEvent::Failed(CoreError::new(
                ErrorCode::Busy,
                "Two searches are still finishing; retry shortly",
            )));
            return;
        }
        struct Permit<'a>(&'a AtomicUsize);
        impl Drop for Permit<'_> {
            fn drop(&mut self) {
                self.0.fetch_sub(1, Ordering::SeqCst);
            }
        }
        let _permit = Permit(&self.active);
        let outcome = self.execute(&request, cancel, &mut emit);
        let outcome = outcome.unwrap_or_else(SearchEvent::Failed);
        emit(
            if cancel.load(Ordering::SeqCst)
                && matches!(outcome, SearchEvent::Complete | SearchEvent::Limited { .. })
            {
                SearchEvent::Cancelled
            } else {
                outcome
            },
        );
    }
    fn execute(
        &self,
        r: &SearchRequest,
        cancel: &AtomicBool,
        emit: &mut impl FnMut(SearchEvent) -> bool,
    ) -> Result<SearchEvent, CoreError> {
        if r.root.target != self.target {
            return Err(CoreError::new(
                ErrorCode::TargetChanged,
                "Search target changed",
            ));
        }
        let options = buntrail_core::search::find::FindOptions {
            expression: r.expression.clone(),
            mode: r.mode.clone(),
            case_sensitive: r.case_sensitive,
            whole_word: r.whole_word,
            scope: None,
        };
        let matcher = buntrail_core::search::find::pattern(&options)?;
        let expression = buntrail_core::search::find::pattern_source(&options)?;
        if r.includes.len() + r.excludes.len() > 256
            || r.includes.iter().chain(&r.excludes).any(|g| g.len() > 4096)
        {
            return Err(CoreError::new(
                ErrorCode::InvalidArgument,
                "Too many or oversized search globs",
            ));
        }
        let root = crate::files::path(&r.root.path)?;
        let mut command = Command::new(&self.executable);
        command.args([
            "--no-config",
            "--json",
            "--line-number",
            "--color=never",
            "--threads=1",
            "--no-mmap",
            "--no-require-git",
        ]);
        command.arg(if r.case_sensitive {
            "--case-sensitive"
        } else {
            "--ignore-case"
        });
        if r.hidden {
            command.arg("--hidden");
        }
        if r.ignored {
            command.arg("--no-ignore");
        } else {
            for g in DEFAULT_EXCLUSIONS {
                command.arg("--glob").arg(format!("!{g}"));
            }
        }
        for g in &r.includes {
            command.arg("--glob").arg(g);
        }
        for g in &r.excludes {
            command.arg("--glob").arg(format!("!{g}"));
        }
        let mut child = command
            .arg("--regexp")
            .arg(&expression)
            .arg("--")
            .arg(root)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|_| {
                CoreError::new(
                    ErrorCode::Unavailable,
                    "Bundled ripgrep could not start; reinstall the application",
                )
            })?;
        let result = (|| {
            let mut out = child.stdout.take().unwrap();
            let mut err = child.stderr.take().unwrap();
            for fd in [out.as_raw_fd(), err.as_raw_fd()] {
                if unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) } < 0 {
                    return Err(crate::files::io_error(std::io::Error::last_os_error()));
                }
            }
            let mut version_cache: Option<(TargetPath, FileVersion)> = None;
            let mut pending = vec![];
            let mut diagnostics = false;
            let mut count = 0;
            let mut files = 0;
            let mut eof = false;
            let mut chunk = [0; 8192];
            loop {
                if cancel.load(Ordering::SeqCst) {
                    return Ok(SearchEvent::Cancelled);
                }
                loop {
                    match err.read(&mut chunk) {
                        Ok(0) => break,
                        Ok(_) => diagnostics = true,
                        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
                        Err(e) => return Err(crate::files::io_error(e)),
                    }
                }
                match out.read(&mut chunk) {
                    Ok(0) => eof = true,
                    Ok(n) => pending.extend_from_slice(&chunk[..n]),
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                    Err(e) => return Err(crate::files::io_error(e)),
                }
                while let Some(end) = pending.iter().position(|b| *b == b'\n') {
                    if end > 256 * 1024 {
                        return Err(super::result_mapper::invalid());
                    }
                    let value: serde_json::Value = serde_json::from_slice(&pending[..end])
                        .map_err(|_| super::result_mapper::invalid())?;
                    pending.drain(..=end);
                    match value["type"].as_str() {
                        Some("match") => {
                            for m in super::result_mapper::matches(&value, &r.root)? {
                                let mut m = m?;
                                let column = m.preview_column_utf8 as usize;
                                if !buntrail_core::search::find::line_match_allowed(
                                    &matcher, &m.preview, column, column,
                                ) {
                                    continue;
                                }
                                if cancel.load(Ordering::SeqCst) {
                                    return Ok(SearchEvent::Cancelled);
                                }
                                if version_cache
                                    .as_ref()
                                    .is_none_or(|(p, _)| *p != m.file.path)
                                {
                                    version_cache = Some((
                                        m.file.path.clone(),
                                        self.files.path_version(m.file.clone())?,
                                    ));
                                }
                                // Independently sampled evidence never certifies the coordinates of rg's read.
                                m.searched_version = version_cache.as_ref().unwrap().1.clone();
                                if count == MAX_MATCHES {
                                    std::fs::metadata(crate::files::path(&r.root.path)?)
                                        .map_err(crate::files::io_error)?;
                                    return Ok(SearchEvent::Limited {
                                        maximum: MAX_MATCHES,
                                    });
                                }
                                if !emit(SearchEvent::Match(Box::new(m))) {
                                    return Ok(SearchEvent::Cancelled);
                                }
                                count += 1;
                            }
                        }
                        Some("end") => {
                            files += 1;
                            if !emit(SearchEvent::Progress {
                                files,
                                matches: count,
                            }) {
                                return Ok(SearchEvent::Cancelled);
                            }
                        }
                        Some("begin" | "summary") => {}
                        _ => return Err(super::result_mapper::invalid()),
                    }
                }
                if pending.len() > 256 * 1024 {
                    return Err(super::result_mapper::invalid());
                }
                if eof && let Some(status) = child.try_wait().map_err(crate::files::io_error)? {
                    if cancel.load(Ordering::SeqCst) {
                        return Ok(SearchEvent::Cancelled);
                    }
                    while let Ok(n) = err.read(&mut chunk) {
                        if n == 0 {
                            break;
                        }
                        diagnostics = true;
                    }
                    if !pending.is_empty() || diagnostics || !matches!(status.code(), Some(0 | 1)) {
                        return Err(CoreError::new(
                            ErrorCode::Io,
                            "Search interrupted or some files could not be read; results are incomplete",
                        ));
                    }
                    std::fs::metadata(crate::files::path(&r.root.path)?).map_err(|_| {
                        CoreError::new(
                            ErrorCode::Io,
                            "Search root disappeared; results are incomplete",
                        )
                    })?;
                    return Ok(SearchEvent::Complete);
                }
                std::thread::sleep(Duration::from_millis(5));
            }
        })();
        // All exits, including parsing failure, backpressure cancellation and target removal, reap the child.
        let _ = child.kill();
        let _ = child.wait();
        result
    }
}
struct State {
    events: VecDeque<SearchEvent>,
    done: bool,
    waker: Option<Waker>,
}
struct Shared {
    state: Mutex<State>,
    space: Condvar,
    cancel: AtomicBool,
}
struct SearchStream(Arc<Shared>);
impl Drop for SearchStream {
    fn drop(&mut self) {
        self.0.cancel.store(true, Ordering::SeqCst);
        self.0.space.notify_all();
    }
}
impl Stream for SearchStream {
    type Item = Result<SearchEvent, CoreError>;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut s = self.0.state.lock().unwrap();
        if let Some(e) = s.events.pop_front() {
            self.0.space.notify_all();
            Poll::Ready(Some(Ok(e)))
        } else if s.done {
            Poll::Ready(None)
        } else {
            s.waker = Some(cx.waker().clone());
            Poll::Pending
        }
    }
}
impl SearchService for LocalSearchService {
    fn search(
        &self,
        r: SearchRequest,
    ) -> ServiceFuture<'_, Result<EventStream<SearchEvent>, CoreError>> {
        Box::pin(async move {
            let shared = Arc::new(Shared {
                state: Mutex::new(State {
                    events: VecDeque::new(),
                    done: false,
                    waker: None,
                }),
                space: Condvar::new(),
                cancel: AtomicBool::new(false),
            });
            let producer = shared.clone();
            let service = self.clone();
            std::thread::Builder::new()
                .name("buntrail-search".into())
                .spawn(move || {
                    service.run(r, &producer.cancel, |e| {
                        let mut s = producer.state.lock().unwrap();
                        while s.events.len() >= 32 && !producer.cancel.load(Ordering::SeqCst) {
                            s = producer.space.wait(s).unwrap();
                        }
                        if producer.cancel.load(Ordering::SeqCst) {
                            return false;
                        }
                        s.events.push_back(e);
                        if let Some(w) = s.waker.take() {
                            w.wake();
                        }
                        true
                    });
                    let mut s = producer.state.lock().unwrap();
                    s.done = true;
                    if let Some(w) = s.waker.take() {
                        w.wake();
                    }
                })
                .map_err(crate::files::io_error)?;
            Ok(Box::pin(SearchStream(shared)) as EventStream<SearchEvent>)
        })
    }
}

#[cfg(test)]
mod standalone_tests {
    use super::*;
    #[test]
    fn explicit_search_executable_is_retained() {
        let directory = tempfile::tempdir().unwrap();
        let files = Arc::new(
            crate::files::LocalFileService::new(
                crate::connections::local::identity().unwrap(),
                directory.path().join("files"),
            )
            .unwrap(),
        );
        let executable = directory.path().join("missing-rg");
        let search = LocalSearchService::with_executable(files, executable.clone());
        assert_eq!(search.executable, executable);
        assert!(Command::new(&search.executable).spawn().is_err());
    }
}