Skip to content
Myr

Merge pull request #895 from tavianator/receiver-buffer

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tavian Barnes · committed by GitHub · parents 1a6638b, a4bb734 · Browse files · 4 files+174 added−86 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • walk: Encapsulate the buffering behavior in a struct

Diff stats

4 files+174 added−86 removed

  • other:+174 added−86 removed

4 files+174 added−86 removed

modified:src/exec/job.rs+2 added-1 removed
1use std::path::PathBuf;2use std::sync::mpsc::Receiver;2use std::sync::{Arc, Mutex};34use crossbeam_channel::Receiver;56use crate::error::print_error;7use crate::exit_codes::{merge_exitcodes, ExitCode};8use crate::walk::WorkerResult;9
69 unmodified lines
modified:src/walk.rs+160 added-85 removed
1use std::ffi::OsStr;2use std::fs::{FileType, Metadata};3use std::io;4use std::mem;5use std::path::{Path, PathBuf};6use std::sync::atomic::{AtomicBool, Ordering};6use std::sync::mpsc::{channel, Receiver, Sender};7use std::sync::{Arc, Mutex};8use std::thread;9use std::time;9use std::time::{Duration, Instant};10use std::{borrow::Cow, io::Write};1112use anyhow::{anyhow, Result};13use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};14use ignore::overrides::OverrideBuilder;15use ignore::{self, WalkBuilder};16use once_cell::unsync::OnceCell;17use regex::bytes::Regex;
5 unmodified lines
23use crate::filesystem;24use crate::output;2526/// The receiver thread can either be buffering results or directly streaming to the console.27#[derive(PartialEq)]28enum ReceiverMode {29 /// Receiver is still buffering in order to sort the results, if the search finishes fast30 /// enough.31 Buffering,
10 unmodified lines
4243/// Maximum size of the output buffer before flushing results to the console44pub const MAX_BUFFER_LENGTH: usize = 1000;45/// Default duration until output buffering switches to streaming.44pub const DEFAULT_MAX_BUFFER_TIME: time::Duration = time::Duration::from_millis(100);46pub const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);4748/// Recursively scan the given search path for files / pathnames matching the pattern.49///50/// If the `--exec` argument was supplied, this will create a thread pool for executing
3 unmodified lines
54 let mut path_iter = path_vec.iter();55 let first_path_buf = path_iter56 .next()57 .expect("Error: Path vector can not be empty");56 let (tx, rx) = channel();58 let (tx, rx) = unbounded();5960 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());6162 for pattern in &config.exclude_patterns {
98 unmodified lines
161 Ok(exit_code)162 }163}164165/// Wrapper for the receiver thread's buffering behavior.166struct ReceiverBuffer<W> {167 /// The configuration.168 config: Arc<Config>,169 /// The ^C notifier.170 wants_to_quit: Arc<AtomicBool>,171 /// Receiver for worker results.172 rx: Receiver<WorkerResult>,173 /// Standard output.174 stdout: W,175 /// The current buffer mode.176 mode: ReceiverMode,177 /// The deadline to switch to streaming mode.178 deadline: Instant,179 /// The buffer of quickly received paths.180 buffer: Vec<PathBuf>,181 /// Result count.182 num_results: usize,183}184185impl<W: Write> ReceiverBuffer<W> {186 /// Create a new receiver buffer.187 fn new(188 config: Arc<Config>,189 wants_to_quit: Arc<AtomicBool>,190 rx: Receiver<WorkerResult>,191 stdout: W,192 ) -> Self {193 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);194 let deadline = Instant::now() + max_buffer_time;195196 Self {197 config,198 wants_to_quit,199 rx,200 stdout,201 mode: ReceiverMode::Buffering,202 deadline,203 buffer: Vec::with_capacity(MAX_BUFFER_LENGTH),204 num_results: 0,205 }206 }207208 /// Process results until finished.209 fn process(&mut self) -> ExitCode {210 loop {211 if let Err(ec) = self.poll() {212 return ec;213 }214 }215 }216217 /// Receive the next worker result.218 fn recv(&self) -> Result<WorkerResult, RecvTimeoutError> {219 match self.mode {220 ReceiverMode::Buffering => {221 // Wait at most until we should switch to streaming222 self.rx.recv_deadline(self.deadline)223 }224 ReceiverMode::Streaming => {225 // Wait however long it takes for a result226 Ok(self.rx.recv()?)227 }228 }229 }230231 /// Wait for a result or state change.232 fn poll(&mut self) -> Result<(), ExitCode> {233 match self.recv() {234 Ok(WorkerResult::Entry(path)) => {235 if self.config.quiet {236 return Err(ExitCode::HasResults(true));237 }238239 match self.mode {240 ReceiverMode::Buffering => {241 self.buffer.push(path);242 if self.buffer.len() > MAX_BUFFER_LENGTH {243 self.stream()?;244 }245 }246 ReceiverMode::Streaming => {247 self.print(&path);248 self.flush()?;249 }250 }251252 self.num_results += 1;253 if let Some(max_results) = self.config.max_results {254 if self.num_results >= max_results {255 return self.stop();256 }257 }258 }259 Ok(WorkerResult::Error(err)) => {260 if self.config.show_filesystem_errors {261 print_error(err.to_string());262 }263 }264 Err(RecvTimeoutError::Timeout) => {265 self.stream()?;266 }267 Err(RecvTimeoutError::Disconnected) => {268 return self.stop();269 }270 }271272 Ok(())273 }274275 /// Output a path.276 fn print(&mut self, path: &Path) {277 output::print_entry(&mut self.stdout, path, &self.config, &self.wants_to_quit)278 }279280 /// Switch ourselves into streaming mode.281 fn stream(&mut self) -> Result<(), ExitCode> {282 self.mode = ReceiverMode::Streaming;283284 let buffer = mem::take(&mut self.buffer);285 for path in buffer {286 self.print(&path);287 }288289 self.flush()290 }291292 /// Stop looping.293 fn stop(&mut self) -> Result<(), ExitCode> {294 if self.mode == ReceiverMode::Buffering {295 self.buffer.sort();296 self.stream()?;297 }298299 if self.config.quiet {300 Err(ExitCode::HasResults(self.num_results > 0))301 } else {302 Err(ExitCode::Success)303 }304 }305306 /// Flush stdout if necessary.307 fn flush(&mut self) -> Result<(), ExitCode> {308 if self.config.interactive_terminal && self.stdout.flush().is_err() {309 // Probably a broken pipe. Exit gracefully.310 return Err(ExitCode::GeneralError);311 }312 Ok(())313 }314}315316fn spawn_receiver(317 config: &Arc<Config>,318 wants_to_quit: &Arc<AtomicBool>,319 rx: Receiver<WorkerResult>,
50 unmodified lines
370 .collect::<Vec<_>>();371 merge_exitcodes(exit_codes)372 }373 } else {221 let start = time::Instant::now();222223 // Start in buffering mode224 let mut mode = ReceiverMode::Buffering;225226 // Maximum time to wait before we start streaming to the console.227 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);228374 let stdout = io::stdout();375 let stdout = stdout.lock();231 let mut stdout = io::BufWriter::new(stdout);376 let stdout = io::BufWriter::new(stdout);377233 let mut num_results = 0;234 let is_interactive = config.interactive_terminal;235 let mut buffer = Vec::with_capacity(MAX_BUFFER_LENGTH);236 for worker_result in rx {237 match worker_result {238 WorkerResult::Entry(path) => {239 if config.quiet {240 return ExitCode::HasResults(true);241 }242243 match mode {244 ReceiverMode::Buffering => {245 buffer.push(path);246247 // Have we reached the maximum buffer size or maximum buffering time?248 if buffer.len() > MAX_BUFFER_LENGTH249 || start.elapsed() > max_buffer_time250 {251 // Flush the buffer252 for path in &buffer {253 output::print_entry(254 &mut stdout,255 path,256 &config,257 &wants_to_quit,258 );259 }260 buffer.clear();261 if is_interactive && stdout.flush().is_err() {262 // Probably a broken pipe. Exit gracefully.263 return ExitCode::GeneralError;264 }265 // Start streaming266 mode = ReceiverMode::Streaming;267 }268 }269 ReceiverMode::Streaming => {270 output::print_entry(&mut stdout, &path, &config, &wants_to_quit);271 if is_interactive && stdout.flush().is_err() {272 // Probably a broken pipe. Exit gracefully.273 return ExitCode::GeneralError;274 }275 }276 }277278 num_results += 1;279 if let Some(max_results) = config.max_results {280 if num_results >= max_results {281 break;282 }283 }284 }285 WorkerResult::Error(err) => {286 if show_filesystem_errors {287 print_error(err.to_string());288 }289 }290 }291 }292293 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed294 // anything to the console, yet. In this case, sort the results and print them:295 buffer.sort();296 for value in buffer {297 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);298 }299300 if config.quiet {301 ExitCode::HasResults(false)302 } else {303 ExitCode::Success304 }378 let mut rxbuffer = ReceiverBuffer::new(config, wants_to_quit, rx, stdout);379 rxbuffer.process()380 }381 })382}383
221 unmodified lines
modified:Cargo.lock+11 added
98 unmodified lines
99 "vec_map",100]101102[[package]]103name = "crossbeam-channel"104version = "0.5.1"105source = "registry+https://github.com/rust-lang/crates.io-index"106checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"107dependencies = [108 "cfg-if",109 "crossbeam-utils",110]111112[[package]]113name = "crossbeam-utils"114version = "0.8.5"115source = "registry+https://github.com/rust-lang/crates.io-index"116checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"
47 unmodified lines
164 "anyhow",165 "atty",166 "chrono",167 "clap",168 "crossbeam-channel",169 "ctrlc",170 "diff",171 "dirs-next",172 "filetime",
497 unmodified lines
modified:Cargo.toml+1 added