1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use super::super::{op, DebouncedEvent};

use std::ops::DerefMut;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use std::{collections::VecDeque, sync::MutexGuard};

use debounce::{OperationsBuffer, OperationsBufferInner};

#[derive(PartialEq, Eq)]
struct ScheduledEvent {
    id: u64,
    when: Instant,
    path: PathBuf,
}

#[derive(Default)]
struct WorkerSharedState {
    is_stopped: bool,
    events: VecDeque<ScheduledEvent>,
}

struct ScheduleWorker {
    state: Arc<(Mutex<WorkerSharedState>, Condvar)>,
    tx: mpsc::Sender<DebouncedEvent>,
    operations_buffer: OperationsBuffer,
}

impl ScheduleWorker {
    fn fire_due_events<'a>(
        &'a self,
        now: Instant,
        state: MutexGuard<'a, WorkerSharedState>,
    ) -> (Option<Instant>, MutexGuard<'a, WorkerSharedState>) {
        // simple deadlock avoidance loop.
        let mut state = Some(state);
        let (mut state, mut op_buf) = loop {
            let state = state.take().unwrap_or_else(|| self.state.0.lock().unwrap());

            // To avoid deadlock, we do a `try_lock`, and on `WouldBlock`, we unlock the
            // events Mutex, and retry after yielding.
            match self.operations_buffer.try_lock() {
                Ok(op_buf) => break (state, op_buf),
                Err(::std::sync::TryLockError::Poisoned { .. }) => return (None, state),
                Err(::std::sync::TryLockError::WouldBlock) => {
                    // drop the lock before yielding to give other threads a chance to complete
                    // their work.
                    drop(state);
                    ::std::thread::yield_now();
                }
            }
        };
        while let Some(event) = state.events.pop_front() {
            if event.when <= now {
                self.fire_event(event, &mut op_buf)
            } else {
                // not due yet, put it back
                let next_when = event.when;
                state.events.push_front(event);
                return (Some(next_when), state);
            }
        }
        (None, state)
    }

    fn fire_event(
        &self,
        ev: ScheduledEvent,
        op_buf: &mut impl DerefMut<Target = OperationsBufferInner>,
    ) {
        let ScheduledEvent { path, .. } = ev;
        if let Some((op, from_path, _)) = op_buf.remove(&path) {
            let is_partial_rename = from_path.is_none();
            if let Some(from_path) = from_path {
                self.tx
                    .send(DebouncedEvent::Rename(from_path, path.clone()))
                    .unwrap();
            }
            let message = match op {
                Some(op::Op::CREATE) => Some(DebouncedEvent::Create(path)),
                Some(op::Op::WRITE) => Some(DebouncedEvent::Write(path)),
                Some(op::Op::CHMOD) => Some(DebouncedEvent::Chmod(path)),
                Some(op::Op::REMOVE) => Some(DebouncedEvent::Remove(path)),
                Some(op::Op::RENAME) if is_partial_rename => {
                    if path.exists() {
                        Some(DebouncedEvent::Create(path))
                    } else {
                        Some(DebouncedEvent::Remove(path))
                    }
                }
                _ => None,
            };
            if let Some(m) = message {
                let _ = self.tx.send(m);
            }
        } else {
            // TODO error!("path not found in operations_buffer: {}", path.display())
        }
    }

    fn run(&mut self) {
        let mut state = self.state.0.lock().unwrap();
        loop {
            let now = Instant::now();
            let (next_when, state_out) = self.fire_due_events(now, state);
            state = state_out;

            if state.is_stopped {
                break;
            }

            state = if let Some(next_when) = next_when {
                // wait for stop notification or timeout to send next event
                self.state.1.wait_timeout(state, next_when - now).unwrap().0
            } else {
                // no pending events
                // wait for new event, to check when it should be send and then wait to send it
                self.state.1.wait(state).unwrap()
            };
        }
    }
}

pub struct WatchTimer {
    counter: u64,
    state: Arc<(Mutex<WorkerSharedState>, Condvar)>,
    delay: Duration,
}

impl WatchTimer {
    pub fn new(
        tx: mpsc::Sender<DebouncedEvent>,
        operations_buffer: OperationsBuffer,
        delay: Duration,
    ) -> WatchTimer {
        let state = Arc::new((Mutex::new(WorkerSharedState::default()), Condvar::new()));

        let worker_state = state.clone();
        thread::spawn(move || {
            ScheduleWorker {
                state: worker_state,
                tx,
                operations_buffer,
            }
            .run();
        });

        WatchTimer {
            counter: 0,
            state,
            delay,
        }
    }

    pub fn schedule(&mut self, path: PathBuf) -> u64 {
        self.counter = self.counter.wrapping_add(1);

        {
            let mut state = self.state.0.lock().unwrap();
            state.events.push_back(ScheduledEvent {
                id: self.counter,
                when: Instant::now() + self.delay,
                path,
            });
        }
        self.state.1.notify_one();

        self.counter
    }

    pub fn ignore(&self, id: u64) {
        let mut state = self.state.0.lock().unwrap();
        let index = state.events.iter().rposition(|e| e.id == id);
        if let Some(index) = index {
            state.events.remove(index);
        }
    }
}

impl Drop for WatchTimer {
    fn drop(&mut self) {
        {
            let mut state = self.state.0.lock().unwrap();
            state.is_stopped = true;
        }
        self.state.1.notify_one();
    }
}