Skip to content
Myr

walk: Send WorkerResults in batches

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

authored by Tavian Barnes · committed by Tavian Barnes · parent 5903dec · Browse files · 3 files+137 added−52 removed
This commit

State

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

Diff stats

3 files+137 added−52 removed

  • other:+137 added−52 removed

3 files+137 added−52 removed

modified:src/exec/job.rs+16 added-15 removed
1use std::sync::Mutex;23use crossbeam_channel::Receiver;43use crate::config::Config;6use crate::dir_entry::DirEntry;4use crate::error::print_error;5use crate::exit_codes::{merge_exitcodes, ExitCode};6use crate::walk::WorkerResult;7
2 unmodified lines
10/// 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.13pub 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;2125 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 };3536 // 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}4852pub fn batch(rx: Receiver<WorkerResult>, cmd: &CommandSet, config: &Config) -> ExitCode {53 let paths = rx49pub 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 lines
modified:src/dir_entry.rs+2 added
6 unmodified lines
78use crate::config::Config;9use crate::filesystem::strip_current_dir;1011#[derive(Debug)]12enum DirEntryInner {13 Normal(ignore::DirEntry),14 BrokenSymlink(PathBuf),15}1617#[derive(Debug)]18pub struct DirEntry {19 inner: DirEntryInner,20 metadata: OnceCell<Option<Metadata>>,21 style: OnceCell<Option<Style>>,
134 unmodified lines
modified:src/walk.rs+119 added-37 removed
2 unmodified lines
3use std::io::{self, Write};4use std::mem;5use std::path::PathBuf;6use std::sync::atomic::{AtomicBool, Ordering};7use std::sync::{Arc, Mutex};7use std::sync::{Arc, Mutex, MutexGuard};8use std::thread;9use std::time::{Duration, Instant};1011use anyhow::{anyhow, Result};12use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};12use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, SendError, Sender};13use etcetera::BaseStrategy;14use ignore::overrides::{Override, OverrideBuilder};15use ignore::{self, WalkBuilder, WalkParallel, WalkState};16use regex::bytes::Regex;
18 unmodified lines
35}3637/// The Worker threads can result in a valid entry having PathBuf or an error.38#[allow(clippy::large_enum_variant)]39#[derive(Debug)]40pub 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}4647/// A batch of WorkerResults to send over a channel.48#[derive(Clone)]49struct Batch {50 items: Arc<Mutex<Option<Vec<WorkerResult>>>>,51}5253impl Batch {54 fn new() -> Self {55 Self {56 items: Arc::new(Mutex::new(Some(vec![]))),57 }58 }5960 fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {61 self.items.lock().unwrap()62 }63}6465impl IntoIterator for Batch {66 type Item = WorkerResult;67 type IntoIter = std::vec::IntoIter<WorkerResult>;6869 fn into_iter(self) -> Self::IntoIter {70 self.lock().take().unwrap().into_iter()71 }72}7374/// Wrapper that sends batches of items at once over a channel.75struct BatchSender {76 batch: Batch,77 tx: Sender<Batch>,78}7980impl BatchSender {81 fn new(tx: Sender<Batch>) -> Self {82 Self {83 batch: Batch::new(),84 tx,85 }86 }8788 /// Check if we need to flush a batch.89 fn needs_flush(batch: Option<&Vec<WorkerResult>>) -> bool {90 match batch {91 // Limit the batch size to provide some backpressure92 Some(vec) => vec.len() >= 0x400,93 // Batch was already taken by the receiver, so make a new one94 None => true,95 }96 }9798 /// Add an item to a batch.99 fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {100 let mut batch = self.batch.lock();101102 if Self::needs_flush(batch.as_ref()) {103 drop(batch);104 self.batch = Batch::new();105 batch = self.batch.lock();106 }107108 let items = batch.as_mut().unwrap();109 items.push(item);110111 if items.len() == 1 {112 // New batch, send it over the channel113 self.tx114 .send(self.batch.clone())115 .map_err(|_| SendError(()))?;116 }117118 Ok(())119 }120}121122/// Maximum size of the output buffer before flushing results to the console123const MAX_BUFFER_LENGTH: usize = 1000;124/// Default duration until output buffering switches to streaming.125const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);
6 unmodified lines
132 quit_flag: &'a AtomicBool,133 /// The ^C notifier.134 interrupt_flag: &'a AtomicBool,135 /// Receiver for worker results.60 rx: Receiver<WorkerResult>,136 rx: Receiver<Batch>,137 /// Standard output.138 stdout: W,139 /// The current buffer mode.140 mode: ReceiverMode,
6 unmodified lines
147}148149impl<'a, W: Write> ReceiverBuffer<'a, W> {150 /// Create a new receiver buffer.75 fn new(state: &'a WorkerState, rx: Receiver<WorkerResult>, stdout: W) -> Self {151 fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {152 let config = &state.config;153 let quit_flag = state.quit_flag.as_ref();154 let interrupt_flag = state.interrupt_flag.as_ref();155 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);
22 unmodified lines
178 }179 }180181 /// Receive the next worker result.106 fn recv(&self) -> Result<WorkerResult, RecvTimeoutError> {182 fn recv(&self) -> Result<Batch, RecvTimeoutError> {183 match self.mode {184 ReceiverMode::Buffering => {185 // Wait at most until we should switch to streaming186 self.rx.recv_deadline(self.deadline)
7 unmodified lines
194195 /// Wait for a result or state change.196 fn poll(&mut self) -> Result<(), ExitCode> {197 match self.recv() {198 Ok(batch) => {199 for result in batch {200 match result {122 Ok(WorkerResult::Entry(dir_entry)) => {123 if self.config.quiet {124 return Err(ExitCode::HasResults(true));125 }201 WorkerResult::Entry(dir_entry) => {202 if self.config.quiet {203 return Err(ExitCode::HasResults(true));204 }205127 match self.mode {128 ReceiverMode::Buffering => {129 self.buffer.push(dir_entry);130 if self.buffer.len() > MAX_BUFFER_LENGTH {131 self.stream()?;206 match self.mode {207 ReceiverMode::Buffering => {208 self.buffer.push(dir_entry);209 if self.buffer.len() > MAX_BUFFER_LENGTH {210 self.stream()?;211 }212 }213 ReceiverMode::Streaming => {214 self.print(&dir_entry)?;215 self.flush()?;216 }217 }218219 self.num_results += 1;220 if let Some(max_results) = self.config.max_results {221 if self.num_results >= max_results {222 return self.stop();223 }224 }225 }226 WorkerResult::Error(err) => {227 if self.config.show_filesystem_errors {228 print_error(err.to_string());229 }230 }231 }134 ReceiverMode::Streaming => {135 self.print(&dir_entry)?;136 self.flush()?;137 }232 }139140 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 }233 }147 Ok(WorkerResult::Error(err)) => {148 if self.config.show_filesystem_errors {149 print_error(err.to_string());150 }151 }234 Err(RecvTimeoutError::Timeout) => {235 self.stream()?;236 }237 Err(RecvTimeoutError::Disconnected) => {
162 unmodified lines
400 }401402 /// Run the receiver work, either on this thread or a pool of background403 /// threads (for --exec).322 fn receive(&self, rx: Receiver<WorkerResult>) -> ExitCode {404 fn receive(&self, rx: Receiver<Batch>) -> ExitCode {405 let config = &self.config;406407 // This will be set to `Some` if the `--exec` argument was supplied.408 if let Some(ref cmd) = config.command {409 if cmd.in_batch_mode() {328 exec::batch(rx, cmd, &config)410 exec::batch(rx.into_iter().flatten(), cmd, &config)411 } else {412 let out_perm = Mutex::new(());413414 thread::scope(|scope| {
3 unmodified lines
418 for _ in 0..threads {419 let rx = rx.clone();420421 // Spawn a job thread that will listen for and execute inputs.340 let handle = scope.spawn(|| exec::job(rx, cmd, &out_perm, &config));422 let handle = scope423 .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, &config));424425 // Push the handle of the spawned thread into the vector for later joining.426 handles.push(handle);427 }
9 unmodified lines
437 }438 }439440 /// Spawn the sender threads.358 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<WorkerResult>) {441 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {442 walker.run(|| {443 let patterns = &self.patterns;444 let config = &self.config;445 let quit_flag = self.quit_flag.as_ref();363 let tx = tx.clone();446 let mut tx = BatchSender::new(tx.clone());447448 Box::new(move |entry| {449 if quit_flag.load(Ordering::Relaxed) {450 return WalkState::Quit;
176 unmodified lines
627 })628 .unwrap();629 }630548 // Channel capacity was chosen empircally to perform similarly to an unbounded channel549 let (tx, rx) = bounded(0x4000 * config.threads);631 let (tx, rx) = bounded(config.threads);632633 let exit_code = thread::scope(|scope| {634 // Spawn the receiver thread(s)635 let receiver = scope.spawn(|| self.receive(rx));
23 unmodified lines