walk: Encapsulate the buffering behavior in a struct
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The new ReceiverBuffer struct allows us to factor out the receiver implementation into a number of helper methods. The new implementation uses rx.{recv,recv_timeout} instead of a for loop, which enables us to switch to streaming mode at the right time without waiting for more results. Fixes #868.
authored by Tavian Barnes · committed by Tavian Barnes · parent f219da4 · Browse files · 1 file·+163 added−84 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+163 added−84 removed
- other:+163 added−84 removed
Provenance
- Commit
16ae03c- Tree
ed283fa- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
Tavian Barnes <tavianator@tavianator.com>- Parent
f219da4
1 file changed+163 added−84 removed
modified:src/walk.rs+163 added-84 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::mpsc::{channel, Receiver, RecvTimeoutError, Sender};8 use std::sync::{Arc, Mutex};9 use std::thread;9-use std::time;10+use std::time::{Duration, Instant};11 use std::{borrow::Cow, io::Write};12 13 use anyhow::{anyhow, Result};14 use ignore::overrides::OverrideBuilder;8 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 executing110 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+ let now = Instant::now();223+ self.deadline224+ .checked_duration_since(now)225+ .ok_or(RecvTimeoutError::Timeout)226+ .and_then(|t| self.rx.recv_timeout(t))227+ }228+ ReceiverMode::Streaming => {229+ // Wait however long it takes for a result230+ Ok(self.rx.recv()?)231+ }232+ }233+ }234+235+ /// Wait for a result or state change.236+ fn poll(&mut self) -> Result<(), ExitCode> {237+ match self.recv() {238+ Ok(WorkerResult::Entry(path)) => {239+ if self.config.quiet {240+ return Err(ExitCode::HasResults(true));241+ }242+243+ match self.mode {244+ ReceiverMode::Buffering => {245+ self.buffer.push(path);246+ if self.buffer.len() > MAX_BUFFER_LENGTH {247+ self.stream()?;248+ }249+ }250+ ReceiverMode::Streaming => {251+ self.print(&path);252+ self.flush()?;253+ }254+ }255+256+ self.num_results += 1;257+ if let Some(max_results) = self.config.max_results {258+ if self.num_results >= max_results {259+ return self.stop();260+ }261+ }262+ }263+ Ok(WorkerResult::Error(err)) => {264+ if self.config.show_filesystem_errors {265+ print_error(err.to_string());266+ }267+ }268+ Err(RecvTimeoutError::Timeout) => {269+ self.stream()?;270+ }271+ Err(RecvTimeoutError::Disconnected) => {272+ return self.stop();273+ }274+ }275+276+ Ok(())277+ }278+279+ /// Output a path.280+ fn print(&mut self, path: &Path) {281+ output::print_entry(&mut self.stdout, path, &self.config, &self.wants_to_quit)282+ }283+284+ /// Switch ourselves into streaming mode.285+ fn stream(&mut self) -> Result<(), ExitCode> {286+ self.mode = ReceiverMode::Streaming;287+288+ let buffer = mem::take(&mut self.buffer);289+ for path in buffer {290+ self.print(&path);291+ }292+293+ self.flush()294+ }295+296+ /// Stop looping.297+ fn stop(&mut self) -> Result<(), ExitCode> {298+ if self.mode == ReceiverMode::Buffering {299+ self.buffer.sort();300+ self.stream()?;301+ }302+303+ if self.config.quiet {304+ Err(ExitCode::HasResults(self.num_results > 0))305+ } else {306+ Err(ExitCode::Success)307+ }308+ }309+310+ /// Flush stdout if necessary.311+ fn flush(&mut self) -> Result<(), ExitCode> {312+ if self.config.interactive_terminal && self.stdout.flush().is_err() {313+ // Probably a broken pipe. Exit gracefully.314+ return Err(ExitCode::GeneralError);315+ }316+ Ok(())317+ }318+}319+320 fn spawn_receiver(321 config: &Arc<Config>,322 wants_to_quit: &Arc<AtomicBool>,323 rx: Receiver<WorkerResult>,50 unmodified lines374 .collect::<Vec<_>>();375 merge_exitcodes(exit_codes)376 }377 } 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-378 let stdout = io::stdout();379 let stdout = stdout.lock();231- let mut stdout = io::BufWriter::new(stdout);380+ let stdout = io::BufWriter::new(stdout);381 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- }382+ let mut rxbuffer = ReceiverBuffer::new(config, wants_to_quit, rx, stdout);383+ rxbuffer.process()384 }385 })386 }387 221 unmodified lines