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
Provenance
- Commit
7fe4bfa- Tree
085610e- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
GitHub <noreply@github.com>- Parent 1
1a6638b- Parent 2
a4bb734
4 files changed+174 added−86 removed
modified:src/exec/job.rs+2 added-1 removed
1 use std::path::PathBuf;2-use std::sync::mpsc::Receiver;2 use std::sync::{Arc, Mutex};3 4+use crossbeam_channel::Receiver;5+6 use crate::error::print_error;7 use crate::exit_codes::{merge_exitcodes, ExitCode};8 use crate::walk::WorkerResult;9 69 unmodified linesmodified:src/walk.rs+160 added-85 removed
1 use std::ffi::OsStr;2 use std::fs::{FileType, Metadata};3 use std::io;4+use std::mem;5 use std::path::{Path, PathBuf};6 use std::sync::atomic::{AtomicBool, Ordering};6-use std::sync::mpsc::{channel, Receiver, Sender};7 use std::sync::{Arc, Mutex};8 use std::thread;9-use std::time;9+use std::time::{Duration, Instant};10 use std::{borrow::Cow, io::Write};11 12 use anyhow::{anyhow, Result};13+use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};14 use ignore::overrides::OverrideBuilder;15 use ignore::{self, WalkBuilder};16 use once_cell::unsync::OnceCell;17 use regex::bytes::Regex;5 unmodified lines23 use crate::filesystem;24 use crate::output;25 26 /// The receiver thread can either be buffering results or directly streaming to the console.27+#[derive(PartialEq)]28 enum ReceiverMode {29 /// Receiver is still buffering in order to sort the results, if the search finishes fast30 /// enough.31 Buffering,10 unmodified lines42 43 /// Maximum size of the output buffer before flushing results to the console44 pub const MAX_BUFFER_LENGTH: usize = 1000;45 /// Default duration until output buffering switches to streaming.44-pub const DEFAULT_MAX_BUFFER_TIME: time::Duration = time::Duration::from_millis(100);46+pub const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);47 48 /// 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 executing3 unmodified lines54 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();59 60 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());61 62 for pattern in &config.exclude_patterns {98 unmodified lines161 Ok(exit_code)162 }163 }164 165+/// Wrapper for the receiver thread's buffering behavior.166+struct 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+}184+185+impl<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;195+196+ 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+ }207+208+ /// 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+ }216+217+ /// 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+ }230+231+ /// 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+ }238+239+ 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+ }251+252+ 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+ }271+272+ Ok(())273+ }274+275+ /// 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+ }279+280+ /// Switch ourselves into streaming mode.281+ fn stream(&mut self) -> Result<(), ExitCode> {282+ self.mode = ReceiverMode::Streaming;283+284+ let buffer = mem::take(&mut self.buffer);285+ for path in buffer {286+ self.print(&path);287+ }288+289+ self.flush()290+ }291+292+ /// Stop looping.293+ fn stop(&mut self) -> Result<(), ExitCode> {294+ if self.mode == ReceiverMode::Buffering {295+ self.buffer.sort();296+ self.stream()?;297+ }298+299+ if self.config.quiet {300+ Err(ExitCode::HasResults(self.num_results > 0))301+ } else {302+ Err(ExitCode::Success)303+ }304+ }305+306+ /// 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+}315+316 fn spawn_receiver(317 config: &Arc<Config>,318 wants_to_quit: &Arc<AtomicBool>,319 rx: Receiver<WorkerResult>,50 unmodified lines370 .collect::<Vec<_>>();371 merge_exitcodes(exit_codes)372 }373 } else {221- let start = time::Instant::now();222-223- // Start in buffering mode224- let mut mode = ReceiverMode::Buffering;225-226- // 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);228-374 let stdout = io::stdout();375 let stdout = stdout.lock();231- let mut stdout = io::BufWriter::new(stdout);376+ let stdout = io::BufWriter::new(stdout);377 233- 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- }242-243- match mode {244- ReceiverMode::Buffering => {245- buffer.push(path);246-247- // 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- }277-278- 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- }292-293- // 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- }299-300- 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 linesmodified:Cargo.lock+11 added
98 unmodified lines99 "vec_map",100 ]101 102 [[package]]103+name = "crossbeam-channel"104+version = "0.5.1"105+source = "registry+https://github.com/rust-lang/crates.io-index"106+checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"107+dependencies = [108+ "cfg-if",109+ "crossbeam-utils",110+]111+112+[[package]]113 name = "crossbeam-utils"114 version = "0.8.5"115 source = "registry+https://github.com/rust-lang/crates.io-index"116 checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"47 unmodified lines164 "anyhow",165 "atty",166 "chrono",167 "clap",168+ "crossbeam-channel",169 "ctrlc",170 "diff",171 "dirs-next",172 "filetime",497 unmodified linesmodified:Cargo.toml+1 added
47 unmodified lines48495051525354555623 unmodified lines47 unmodified linesdirs-next = "2.0"normpath = "0.3"chrono = "0.4"once_cell = "1.8.0"crossbeam-channel = "0.5.1"
[dependencies.clap]version = "2.34.0"features = ["suggestions", "color", "wrap_help"]23 unmodified lines