Merge pull request #1422 from tavianator/batch
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 5903dec, b8a5f95 · Browse files · 3 files·+147 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- walk: Send WorkerResults in batches
Diff stats
3 files+147 added−52 removed
- other:+147 added−52 removed
Provenance
- Commit
84f032e- Tree
c59a891- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
GitHub <noreply@github.com>- Parent 1
5903dec- Parent 2
b8a5f95
3 files changed+147 added−52 removed
modified:src/exec/job.rs+16 added-15 removed
1 use std::sync::Mutex;2 3-use crossbeam_channel::Receiver;4-3 use crate::config::Config;6-use crate::dir_entry::DirEntry;4 use crate::error::print_error;5 use crate::exit_codes::{merge_exitcodes, ExitCode};6 use crate::walk::WorkerResult;7 2 unmodified lines10 /// An event loop that listens for inputs from the `rx` receiver. Each received input will11 /// generate a command with the supplied command template. The generated command will then12 /// be executed, and this process will continue until the receiver's sender has closed.13 pub fn job(17- rx: Receiver<WorkerResult>,14+ results: impl IntoIterator<Item = WorkerResult>,15 cmd: &CommandSet,16 out_perm: &Mutex<()>,17 config: &Config,18 ) -> ExitCode {19 // Output should be buffered when only running a single thread20 let buffer_output: bool = config.threads > 1;21 25- let mut results: Vec<ExitCode> = Vec::new();26- loop {22+ let mut ret = ExitCode::Success;23+ for result in results {24 // Obtain the next result from the receiver, else if the channel25 // has closed, exit from the loop29- let dir_entry: DirEntry = match rx.recv() {30- Ok(WorkerResult::Entry(dir_entry)) => dir_entry,31- Ok(WorkerResult::Error(err)) => {26+ let dir_entry = match result {27+ WorkerResult::Entry(dir_entry) => dir_entry,28+ WorkerResult::Error(err) => {29 if config.show_filesystem_errors {30 print_error(err.to_string());31 }32 continue;33 }37- Err(_) => break,34 };35 36 // Generate a command, execute it and store its exit code.41- results.push(cmd.execute(37+ let code = cmd.execute(38 dir_entry.stripped_path(config),39 config.path_separator.as_deref(),40 out_perm,41 buffer_output,46- ))42+ );43+ ret = merge_exitcodes([ret, code]);44 }45 // Returns error in case of any error.49- merge_exitcodes(results)46+ ret47 }48 52-pub fn batch(rx: Receiver<WorkerResult>, cmd: &CommandSet, config: &Config) -> ExitCode {53- let paths = rx49+pub fn batch(50+ results: impl IntoIterator<Item = WorkerResult>,51+ cmd: &CommandSet,52+ config: &Config,53+) -> ExitCode {54+ let paths = results55 .into_iter()56 .filter_map(|worker_result| match worker_result {57 WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),58 WorkerResult::Error(err) => {9 unmodified linesmodified:src/dir_entry.rs+2 added
6 unmodified lines7 8 use crate::config::Config;9 use crate::filesystem::strip_current_dir;10 11+#[derive(Debug)]12 enum DirEntryInner {13 Normal(ignore::DirEntry),14 BrokenSymlink(PathBuf),15 }16 17+#[derive(Debug)]18 pub struct DirEntry {19 inner: DirEntryInner,20 metadata: OnceCell<Option<Metadata>>,21 style: OnceCell<Option<Style>>,134 unmodified linesmodified:src/walk.rs+129 added-37 removed
2 unmodified lines3 use std::io::{self, Write};4 use std::mem;5 use std::path::PathBuf;6 use std::sync::atomic::{AtomicBool, Ordering};7-use std::sync::{Arc, Mutex};7+use std::sync::{Arc, Mutex, MutexGuard};8 use std::thread;9 use std::time::{Duration, Instant};10 11 use anyhow::{anyhow, Result};12-use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};12+use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, SendError, Sender};13 use etcetera::BaseStrategy;14 use ignore::overrides::{Override, OverrideBuilder};15 use ignore::{self, WalkBuilder, WalkParallel, WalkState};16 use regex::bytes::Regex;18 unmodified lines35 }36 37 /// The Worker threads can result in a valid entry having PathBuf or an error.38 #[allow(clippy::large_enum_variant)]39+#[derive(Debug)]40 pub enum WorkerResult {41 // Errors should be rare, so it's probably better to allow large_enum_variant than42 // to box the Entry variant43 Entry(DirEntry),44 Error(ignore::Error),45 }46 47+/// A batch of WorkerResults to send over a channel.48+#[derive(Clone)]49+struct Batch {50+ items: Arc<Mutex<Option<Vec<WorkerResult>>>>,51+}52+53+impl Batch {54+ fn new() -> Self {55+ Self {56+ items: Arc::new(Mutex::new(Some(vec![]))),57+ }58+ }59+60+ fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {61+ self.items.lock().unwrap()62+ }63+}64+65+impl IntoIterator for Batch {66+ type Item = WorkerResult;67+ type IntoIter = std::vec::IntoIter<WorkerResult>;68+69+ fn into_iter(self) -> Self::IntoIter {70+ self.lock().take().unwrap().into_iter()71+ }72+}73+74+/// Wrapper that sends batches of items at once over a channel.75+struct BatchSender {76+ batch: Batch,77+ tx: Sender<Batch>,78+ limit: usize,79+}80+81+impl BatchSender {82+ fn new(tx: Sender<Batch>, limit: usize) -> Self {83+ Self {84+ batch: Batch::new(),85+ tx,86+ limit,87+ }88+ }89+90+ /// Check if we need to flush a batch.91+ fn needs_flush(&self, batch: Option<&Vec<WorkerResult>>) -> bool {92+ match batch {93+ // Limit the batch size to provide some backpressure94+ Some(vec) => vec.len() >= self.limit,95+ // Batch was already taken by the receiver, so make a new one96+ None => true,97+ }98+ }99+100+ /// Add an item to a batch.101+ fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {102+ let mut batch = self.batch.lock();103+104+ if self.needs_flush(batch.as_ref()) {105+ drop(batch);106+ self.batch = Batch::new();107+ batch = self.batch.lock();108+ }109+110+ let items = batch.as_mut().unwrap();111+ items.push(item);112+113+ if items.len() == 1 {114+ // New batch, send it over the channel115+ self.tx116+ .send(self.batch.clone())117+ .map_err(|_| SendError(()))?;118+ }119+120+ Ok(())121+ }122+}123+124 /// Maximum size of the output buffer before flushing results to the console125 const MAX_BUFFER_LENGTH: usize = 1000;126 /// Default duration until output buffering switches to streaming.127 const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);6 unmodified lines134 quit_flag: &'a AtomicBool,135 /// The ^C notifier.136 interrupt_flag: &'a AtomicBool,137 /// Receiver for worker results.60- rx: Receiver<WorkerResult>,138+ rx: Receiver<Batch>,139 /// Standard output.140 stdout: W,141 /// The current buffer mode.142 mode: ReceiverMode,6 unmodified lines149 }150 151 impl<'a, W: Write> ReceiverBuffer<'a, W> {152 /// Create a new receiver buffer.75- fn new(state: &'a WorkerState, rx: Receiver<WorkerResult>, stdout: W) -> Self {153+ fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {154 let config = &state.config;155 let quit_flag = state.quit_flag.as_ref();156 let interrupt_flag = state.interrupt_flag.as_ref();157 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);22 unmodified lines180 }181 }182 183 /// Receive the next worker result.106- fn recv(&self) -> Result<WorkerResult, RecvTimeoutError> {184+ fn recv(&self) -> Result<Batch, RecvTimeoutError> {185 match self.mode {186 ReceiverMode::Buffering => {187 // Wait at most until we should switch to streaming188 self.rx.recv_deadline(self.deadline)7 unmodified lines196 197 /// Wait for a result or state change.198 fn poll(&mut self) -> Result<(), ExitCode> {199 match self.recv() {200+ Ok(batch) => {201+ for result in batch {202+ match result {122- Ok(WorkerResult::Entry(dir_entry)) => {123- if self.config.quiet {124- return Err(ExitCode::HasResults(true));125- }203+ WorkerResult::Entry(dir_entry) => {204+ if self.config.quiet {205+ return Err(ExitCode::HasResults(true));206+ }207 127- match self.mode {128- ReceiverMode::Buffering => {129- self.buffer.push(dir_entry);130- if self.buffer.len() > MAX_BUFFER_LENGTH {131- self.stream()?;208+ match self.mode {209+ ReceiverMode::Buffering => {210+ self.buffer.push(dir_entry);211+ if self.buffer.len() > MAX_BUFFER_LENGTH {212+ self.stream()?;213+ }214+ }215+ ReceiverMode::Streaming => {216+ self.print(&dir_entry)?;217+ self.flush()?;218+ }219+ }220+221+ self.num_results += 1;222+ if let Some(max_results) = self.config.max_results {223+ if self.num_results >= max_results {224+ return self.stop();225+ }226+ }227 }228+ WorkerResult::Error(err) => {229+ if self.config.show_filesystem_errors {230+ print_error(err.to_string());231+ }232+ }233 }134- ReceiverMode::Streaming => {135- self.print(&dir_entry)?;136- self.flush()?;137- }234 }139-140- self.num_results += 1;141- if let Some(max_results) = self.config.max_results {142- if self.num_results >= max_results {143- return self.stop();144- }145- }235 }147- Ok(WorkerResult::Error(err)) => {148- if self.config.show_filesystem_errors {149- print_error(err.to_string());150- }151- }236 Err(RecvTimeoutError::Timeout) => {237 self.stream()?;238 }239 Err(RecvTimeoutError::Disconnected) => {162 unmodified lines402 }403 404 /// Run the receiver work, either on this thread or a pool of background405 /// threads (for --exec).322- fn receive(&self, rx: Receiver<WorkerResult>) -> ExitCode {406+ fn receive(&self, rx: Receiver<Batch>) -> ExitCode {407 let config = &self.config;408 409 // This will be set to `Some` if the `--exec` argument was supplied.410 if let Some(ref cmd) = config.command {411 if cmd.in_batch_mode() {328- exec::batch(rx, cmd, &config)412+ exec::batch(rx.into_iter().flatten(), cmd, &config)413 } else {414 let out_perm = Mutex::new(());415 416 thread::scope(|scope| {3 unmodified lines420 for _ in 0..threads {421 let rx = rx.clone();422 423 // Spawn a job thread that will listen for and execute inputs.340- let handle = scope.spawn(|| exec::job(rx, cmd, &out_perm, &config));424+ let handle = scope425+ .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, &config));426 427 // Push the handle of the spawned thread into the vector for later joining.428 handles.push(handle);429 }9 unmodified lines439 }440 }441 442 /// Spawn the sender threads.358- fn spawn_senders(&self, walker: WalkParallel, tx: Sender<WorkerResult>) {443+ fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {444 walker.run(|| {445 let patterns = &self.patterns;446 let config = &self.config;447 let quit_flag = self.quit_flag.as_ref();363- let tx = tx.clone();448 449+ let mut limit = 0x100;450+ if let Some(cmd) = &config.command {451+ if !cmd.in_batch_mode() && config.threads > 1 {452+ // Evenly distribute work between multiple receivers453+ limit = 1;454+ }455+ }456+ let mut tx = BatchSender::new(tx.clone(), limit);457+458 Box::new(move |entry| {459 if quit_flag.load(Ordering::Relaxed) {460 return WalkState::Quit;461 }175 unmodified lines637 })638 .unwrap();639 }640 548- // Channel capacity was chosen empircally to perform similarly to an unbounded channel549- let (tx, rx) = bounded(0x4000 * config.threads);641+ let (tx, rx) = bounded(2 * config.threads);642 643 let exit_code = thread::scope(|scope| {644 // Spawn the receiver thread(s)645 let receiver = scope.spawn(|| self.receive(rx));23 unmodified lines