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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! Trait that controls the number of threads.
//!
//! The queue is trying to change the number of threads only when new tasks come into it.
//! In the TaskQueue::enqueue method.
use std::time::SystemTime;
use std::time::Duration;
use std::cmp;
use std::rc::Rc;
use std::cell::RefCell;

use super::TaskQueueStats;

pub trait SpawnPolicy {
    /// Returns current number of threads.
    fn get_count(&mut self, stats: TaskQueueStats) -> usize;
}

/// Policy that provide max number of threads for queue.
/// # Examples
/// ``` rust
/// extern crate task_queue;
///
/// let mut queue = task_queue::TaskQueue::new();
/// let boxed_policy = Box::new(task_queue::spawn_policy::StaticSpawnPolicy::new());
/// queue.set_spawn_policy(boxed_policy);
/// ```
pub struct StaticSpawnPolicy;

impl StaticSpawnPolicy {
    /// Create policy that provide max number of threads for queue.
    pub fn new() -> Self {
        StaticSpawnPolicy
    }
}

impl SpawnPolicy for StaticSpawnPolicy {
    fn get_count(&mut self, stats: TaskQueueStats) -> usize {
        stats.threads_max
    }
}

/// Policy that provide dynamic number of threads for queue.
/// # Examples
/// ``` rust
/// extern crate task_queue;
///
/// let mut queue = task_queue::TaskQueue::new();
/// let boxed_policy = Box::new(task_queue::spawn_policy::DynamicSpawnPolicy::new());
/// queue.set_spawn_policy(boxed_policy);
/// ```
pub struct DynamicSpawnPolicy {
    stats: PolicyStats,
    last_change: SystemTime,
    delta: Duration,
}

impl DynamicSpawnPolicy {
    /// Create policy that provide dynamic number of threads for queue.
    /// Policy will trying to change number of threads every 5 minutes.
    pub fn new() -> Self {
        Self::with_delta(Duration::from_secs(60 * 5))
    }

    /// Create policy that provide dynamic number of threads for queue.
    /// Policy will trying to change number of threads no more often delta.
    pub fn with_delta(delta: Duration) -> Self {
        DynamicSpawnPolicy {
            stats: PolicyStats::new(),
            last_change: SystemTime::now(),
            delta: delta,
        }
    }
}

impl SpawnPolicy for DynamicSpawnPolicy {
    fn get_count(&mut self, stats: TaskQueueStats) -> usize {
        self.stats.increment();

        let mut count = stats.threads_count;
        count = cmp::max(stats.threads_min, count);
        count = cmp::min(stats.threads_max, count);

        let current_delta = match self.last_change.elapsed() {
            Ok(d) => d,
            Err(_) => return count
        };

        if current_delta < self.delta {
            return count;
        }

        const TASKS_IN_QUEUE_UP: usize = 10;
        const TASKS_IN_QUEUE_DOWN: usize = 0;
        const TASKS_ADD_FREQ_UP: usize = 5;
        const DELTA_COUNT: usize = 1;

        let calls_per_sec = match self.stats.calls_per_sec() {
            Some(n) => n,
            None => return count,
        };

        let freq_for_up = calls_per_sec > TASKS_ADD_FREQ_UP;
        let tasks_for_up = stats.tasks_count > TASKS_IN_QUEUE_UP;
        let tasks_for_down = stats.tasks_count <= TASKS_IN_QUEUE_DOWN;
        let not_max_threads = count < stats.threads_max;
        let not_min_threads = count > stats.threads_min;

        if freq_for_up && tasks_for_up && not_max_threads {
            self.stats.reset();
            self.last_change = SystemTime::now();
            return count + DELTA_COUNT;
        }

        if tasks_for_down && not_min_threads {
            self.stats.reset();
            self.last_change = SystemTime::now();
            return count - DELTA_COUNT;
        }

        count
    }
}

struct PolicyStats {
    calls_count: usize,
    first_call_at: Option<SystemTime>
}

impl PolicyStats {
    fn new() -> Self {
        PolicyStats {
            calls_count: 0,
            first_call_at: None
        }
    }

    fn increment(&mut self) {
        self.calls_count += 1;

        if let None = self.first_call_at {
            self.first_call_at = Some(SystemTime::now());
        }
    }

    fn reset(&mut self) {
        self.calls_count = 0;
        self.first_call_at = None;
    }

    fn calls_per_sec(&self) -> Option<usize> {
        let first = match self.first_call_at {
            Some(t) => t,
            None => return None
        };

        let elapsed = match first.elapsed() {
            Ok(d) => d,
            Err(_) => return None
        };

        let elapsed_sec = elapsed.as_secs() as usize;
        if elapsed_sec == 0 {
            return None;
        }

        Some(self.calls_count / elapsed_sec)
    }
}

/// Policy that makes it possible control of the threads number manually
/// # Examples
/// ``` rust
/// extern crate task_queue;
///
/// let mut queue = task_queue::TaskQueue::new();
///
/// let mut policy = task_queue::spawn_policy::ManualSpawnPolicy::new();
/// let mut controller = policy.get_controller();
///
/// queue.set_spawn_policy(Box::new(policy));
/// controller.add_thread();
/// ```
pub struct ManualSpawnPolicy {
    threads_count: Rc<RefCell<usize>>
}

impl ManualSpawnPolicy {
    /// Create policy with 10 threads
    pub fn new() -> Self {
        Self::with_threads(10)
    }

    /// Create policy with selected number of threads
    pub fn with_threads(threads: usize) -> Self {
        ManualSpawnPolicy {
            threads_count: Rc::new(RefCell::new(threads))
        }
    }

    /// Returns controller which makes possible control of the threads number
    pub fn get_controller(&mut self) -> ManualSpawnPolicyController {
        ManualSpawnPolicyController {
            threads_count: self.threads_count.clone()
        }
    }
}

/// Controller which makes possible control of the threads number
pub struct ManualSpawnPolicyController {
    threads_count: Rc<RefCell<usize>>
}

impl ManualSpawnPolicyController {
    /// Increase threads counter
    pub fn add_thread(&mut self) {
        *self.threads_count.borrow_mut() += 1;
    }

    /// Decrease threads counter
    pub fn remove_thread(&mut self) {
        *self.threads_count.borrow_mut() -= 1;
    }
}

impl SpawnPolicy for ManualSpawnPolicy {
    fn get_count(&mut self, stats: TaskQueueStats) -> usize {
        let mut count = *self.threads_count.borrow();

        count = cmp::min(count, stats.threads_max);
        count = cmp::max(count, stats.threads_min);

        count
    }
}

#[cfg(test)]
mod test {
    use std::thread;
    use std::time::Duration;

    use super::DynamicSpawnPolicy;
    use super::SpawnPolicy;
    use super::PolicyStats;
    use super::super::TaskQueueStats;

    #[test]
    fn test_policy_stats_increment() {
        let mut stats = PolicyStats::new();

        for _ in 0..20 {
            stats.increment();

            thread::sleep(Duration::from_millis(100));
        }

        let calls = stats.calls_per_sec().expect("Value not exist");
        assert_eq!(calls, 10);
    }

    #[test]
    fn test_dynamic_policy_up() {
        let mut stats = TaskQueueStats::empty();
        stats.threads_count = 5;
        stats.threads_max = 10;
        stats.threads_min = 5;
        stats.tasks_count = 11;

        let mut policy = DynamicSpawnPolicy::with_delta(Duration::from_millis(100));

        for _ in 0..100 {
            stats.threads_count = policy.get_count(stats);
            thread::sleep(Duration::from_millis(100));
        }

        assert_eq!(stats.threads_count, 10);
    }

    #[test]
    fn test_dynamic_policy_down() {
        let mut stats = TaskQueueStats::empty();
        stats.threads_count = 10;
        stats.threads_max = 10;
        stats.threads_min = 5;
        stats.tasks_count = 0;

        let mut policy = DynamicSpawnPolicy::with_delta(Duration::from_millis(100));

        for _ in 0..100 {
            stats.threads_count = policy.get_count(stats);
            thread::sleep(Duration::from_millis(100));
        }

        assert_eq!(stats.threads_count, 5);
    }
}