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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
use std::fmt::{Display, Formatter};
use std::io::Error;
use std::thread;
use std::sync::mpsc::{channel, sync_channel, Sender, SyncSender, Receiver, SendError, RecvError};
use crate::EventType::{*};
use std::sync::{Arc, Mutex, Condvar};
use log::trace;

pub type Runnable = Box<dyn Send + Sync + FnOnce() -> ()>;
pub type Callable<T> = Box<dyn Send + Sync + FnOnce() -> T>;

#[derive(Debug)]
pub enum ExecutorServiceError {
  ParameterError(String),
  IOError(std::io::Error),
  ProcessingError,
  ResultReceptionError,
}

impl<T> From<SendError<T>> for ExecutorServiceError {
  fn from(_: SendError<T>) -> Self {
    ExecutorServiceError::ProcessingError
  }
}

impl From<RecvError> for ExecutorServiceError {
  fn from(_: RecvError) -> Self {
    ExecutorServiceError::ResultReceptionError
  }
}

impl From<std::io::Error> for ExecutorServiceError {
  fn from(value: Error) -> Self {
    ExecutorServiceError::IOError(value)
  }
}

impl Display for ExecutorServiceError {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      ExecutorServiceError::ParameterError(message) => write!(f, "{:}: {:}", "ParameterError", message.as_str()),
      ExecutorServiceError::IOError(io_error) => write!(f, "{:}: {:}", "IOError", io_error),
      ExecutorServiceError::ResultReceptionError => write!(f, "{:}", "ResultReceptionError"),
      ExecutorServiceError::ProcessingError => write!(f, "{:}", "ProcessingError"),
    }
  }
}

impl std::error::Error for ExecutorServiceError{}

pub struct Future<T> {
  result_receiver: Receiver<T>,
}

impl<T> Future<T> {
  pub fn get(&self) -> Result<T, ExecutorServiceError> {
    Ok(self.result_receiver.recv()?)
  }
}

enum EventType {
  Execute(Runnable),
  ExecuteInner(Sender<EventType>, Runnable),
  Quit,
}

impl Display for EventType {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "EventType::{:}",
           match self {
             Execute(_) => "Execute",
             ExecuteInner(..) => "ExecuteInner",
             Quit => "Quit",
           }
    )
  }
}

///
/// The executor service that allows tasks to be submitted/executed
/// on the underlying thread pool.
/// ```
/// use executor_service::Executors;
/// use std::thread::sleep;
/// use core::time::Duration;
///
/// let mut executor_service = Executors::new_fixed_thread_pool(2).expect("Failed to create the thread pool");
///
/// let some_param = "Mr White";
/// let res = executor_service.submit_sync(Box::new(move || {
///
///   sleep(Duration::from_secs(5));
///   println!("Hello {:}", some_param);
///   println!("Long lasting computation finished");
///   2
/// })).expect("Failed to submit function");
///
/// println!("Result: {:#?}", res);
/// assert_eq!(res, 2);
///```
pub struct ExecutorService {
  dispatcher: SyncSender<EventType>,
}

impl ExecutorService {
  ///
  /// Execute a function on the thread pool asynchronously with no return.
  /// ```
  /// use executor_service::Executors;
  /// use std::thread::sleep;
  /// use core::time::Duration;
  /// use std::thread;
  ///
  /// let mut executor_service = Executors::new_fixed_thread_pool(2).expect("Failed to create the thread pool");
  ///
  /// let some_param = "Mr White";
  /// let res = executor_service.execute(Box::new(move || {
  ///   sleep(Duration::from_secs(1));
  ///   println!("Hello from thread {:}", thread::current().name().unwrap());
  /// })).expect("Failed to execute function");
  ///
  /// sleep(Duration::from_secs(3));
  ///```
  ///
  pub fn execute(&mut self, fun: Runnable) -> Result<(), ExecutorServiceError> {
    Ok(self.dispatcher.send(Execute(fun))?)
  }

  ///
  /// Submit a function and wait for its result synchronously
  /// ```
  /// use executor_service::Executors;
  /// use std::thread::sleep;
  /// use core::time::Duration;
  ///
  /// let mut executor_service = Executors::new_fixed_thread_pool(2).expect("Failed to create the thread pool");
  ///
  /// let some_param = "Mr White";
  /// let res = executor_service.submit_sync(Box::new(move || {
  ///
  ///   sleep(Duration::from_secs(5));
  ///   println!("Hello {:}", some_param);
  ///   println!("Long lasting computation finished");
  ///   2
  /// })).expect("Failed to submit function");
  ///
  /// println!("Result: {:#?}", res);
  /// assert_eq!(res, 2);
  ///```
  pub fn submit_sync<T: Sync + Send + 'static>(&mut self, fun: Callable<T>) -> Result<T, ExecutorServiceError> {
    let (s, r) = sync_channel(1);
    self.dispatcher.send(Execute(Box::new(move || {
      let t = fun();
      s.send(t).unwrap();
    })))?;
    Ok(r.recv()?)
  }

  ///
  /// Submit a function and get a Future object to obtain the result
  /// asynchronously when needed.
  /// ```
  /// use executor_service::Executors;
  /// use std::thread::sleep;
  /// use core::time::Duration;
  ///
  /// let mut executor_service = Executors::new_fixed_thread_pool(2).expect("Failed to create the thread pool");
  ///
  /// let some_param = "Mr White";
  /// let future = executor_service.submit_async(Box::new(move || {
  ///
  ///   sleep(Duration::from_secs(3));
  ///   println!("Hello {:}", some_param);
  ///   println!("Long lasting computation finished");
  ///   "Some string result".to_string()
  /// })).expect("Failed to submit function");
  ///
  /// //Wait a bit more to see the future work.
  /// println!("Main thread wait for 5 seconds");
  /// sleep(Duration::from_secs(5));
  /// let res = future.get().expect("Couldn't get a result");
  /// println!("Result is {:}", &res);
  /// assert_eq!(&res, "Some string result");
  ///```
  pub fn submit_async<T: Sync + Send + 'static>(&mut self, fun: Callable<T>) -> Result<Future<T>, ExecutorServiceError> {
    let (s, r) = sync_channel(1);
    self.dispatcher.send(Execute(Box::new(move || {
      let t = fun();
      s.send(t).unwrap();
    })))?;

    Ok(Future {
      result_receiver: r
    })
  }
}

impl Drop for ExecutorService {
  fn drop(&mut self) {
    self.dispatcher.send(EventType::Quit).unwrap();
  }
}


pub struct Executors;

impl Executors {
  ///
  /// Creates a thread pool with a fixed size. All threads are initialized at first.
  ///
  /// `REMARKS`: The maximum value for `thread_count` is currently 100
  /// If you go beyond that, the function will fail, producing an `ExecutorServiceError::ParameterError`
  ///
  pub fn new_fixed_thread_pool(thread_count: u32) -> Result<ExecutorService, ExecutorServiceError> {
    if thread_count > 100 {
      return Err(ExecutorServiceError::ProcessingError)
    }
    let available = Arc::new(Mutex::new(vec![]));

    let (sender, receiver) = sync_channel::<EventType>(1);

    let pair = Arc::new(Condvar::new());

    for i in 0..thread_count {
      let (s, r) = channel::<EventType>();

      if let Ok(mut lock) = available.lock() {
        lock.push(s);
      }

      let vec_clone = available.clone();
      let cv_clone = pair.clone();
      thread::Builder::new()
        .name(format!("Thread-{:}", i)).spawn(move || {
        loop {
          //trace!("{:} Waiting for job", thread::current().name().unwrap());
          let fun = r.recv().unwrap();
          //trace!("{:} Received func", thread::current().name().unwrap());
          match fun {
            ExecuteInner(sender, fun) => {
              fun();
              //trace!("{:} Send result", thread::current().name().unwrap());
              if let Ok(mut lock) = vec_clone.lock() {
                lock.push(sender);
                //trace!("Notify waiters for finish");
                cv_clone.notify_all();
              }
            }
            Quit => {
              trace!("{:} Received exit", thread::current().name().unwrap());
              break;
            }
            _ => {}
          }
        }
        //trace!("{:} Loop done", thread::current().name().unwrap())
      })?;
    }

    thread::Builder::new()
      .name("Dispatcher".into())
      .spawn(move || {
        loop {
          match receiver.recv().unwrap() {
            Execute(func) => {
              if let Ok(lock) = available.lock() {
                if lock.is_empty() {
                  let _ = pair.wait(lock);
                }
              };

              if let Ok(mut lock) = available.lock() {
                //trace!("Available: {:}", lock.len());
                let the_sender = lock.pop().unwrap();
                //trace!("Available: {:}", lock.len());
                the_sender.send(ExecuteInner(the_sender.clone(), func)).unwrap();
              };
            }
            Quit => {
              //trace!("Dispatcher received Quit");
              if let Ok(lock) = available.lock() {
                for x in &*lock {
                  trace!("AV Send quit");
                  let _ = x.send(EventType::Quit);
                }
              }

              break;
            }
            _ => {}
          }
        }
        trace!("Dispatcher exit");
      })?;

    Ok(ExecutorService {
      dispatcher: sender
    })
  }
}


#[cfg(test)]
mod tests {
  use std::time::Duration;
  use super::*;
  use std::thread::sleep;
  use std::thread;
  use std::sync::mpsc::sync_channel;
  use env_logger::{Builder, Env};
  use log::{debug, info};

  #[cfg(test)]
  #[ctor::ctor]
  fn init_env_logger() {
    Builder::from_env(Env::default().default_filter_or("trace")).init();
  }

  #[test]
  fn test_execute() -> Result<(), ExecutorServiceError> {
    let max = 100;
    let mut executor_service = Executors::new_fixed_thread_pool(10)?;

    let (sender, receiver) = sync_channel(max);
    for i in 0..max {
      let moved_i = i;

      let sender2 = sender.clone();

      executor_service.execute(Box::new(move || {
        sleep(Duration::from_millis(10));
        info!("Hello from {:} {:}", thread::current().name().unwrap(), moved_i);
        sender2.send(1).expect("Send failed");
      }))?;
    }

    let mut latch_count = max;

    loop {
      let _ = &receiver.recv().unwrap();
      latch_count -= 1;

      if latch_count == 0 {
        break; //all threads are done
      }
    };

    Ok(())
  }

  #[test]
  fn test_submit_sync() -> Result<(), ExecutorServiceError> {
    let mut executor_service = Executors::new_fixed_thread_pool(2)?;

    let some_param = "Mr White";
    let res = executor_service.submit_sync(Box::new(move || {
      info!("Long lasting computation");
      sleep(Duration::from_secs(5));
      debug!("Hello {:}", some_param);
      info!("Long lasting computation finished");
      2
    }))?;

    trace!("Result: {:#?}", res);
    assert_eq!(res, 2);
    Ok(())
  }

  #[test]
  fn test_submit_async() -> Result<(), ExecutorServiceError> {
    let mut executor_service = Executors::new_fixed_thread_pool(2)?;

    let some_param = "Mr White";
    let res: Future<String> = executor_service.submit_async(Box::new(move || {
      info!("Long lasting computation");
      sleep(Duration::from_secs(5));
      debug!("Hello {:}", some_param);
      info!("Long lasting computation finished");
      "A string as a result".to_string()
    }))?;

    //Wait a bit more to see the future work.
    info!("Main thread wait for 7 seconds");
    sleep(Duration::from_secs(7));
    info!("Main thread resumes after 7 seconds, consuming the future");
    let the_string = res.get()?;
    trace!("Result: {:#?}", &the_string);
    assert_eq!(&the_string, "A string as a result");
    Ok(())
  }
}