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
use crate::tea::Tea;
use crate::ingredient::{Ingredient, Steep, Pour};

use std::sync::{mpsc, Arc, Mutex, RwLock};
use std::thread;
use std::time::Instant;

/// Types of instructions that can be sent to Brewers.
enum OrderTea {
    NewOrder(Order),
    Terminate
}

/// Wrapper to allow sent function in Box to be invokable.
trait FnBox {
    /// Method to call inner function.
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce()> FnBox for F {
    /// Calls inner function in box.
    fn call_box(self: Box<F>) {
        (*self)()
    }
}

/// Type representing the brew function to be implemented on Tea batch with Recipe.
type Order = Box<dyn FnBox + Send + 'static>;

/// Struct holding the Array of Brewers and sender to push Tea Orders out to them.
pub struct Brewery {
    brewers: Vec<Brewer>,
    sender: mpsc::Sender<OrderTea>,
    start_time: Instant,
}

impl Brewery {
    ///
    /// Creates new Brewery with Brewers and sender/receiver pair for passing jobs to them.
    ///
    /// # Arguments
    ///
    /// * `size` - number of brewers to instantiate
    /// * `start_time` - program start time to expose runtime metrics
    pub fn new(size: usize, start_time: Instant) -> Brewery {
        assert!(size > 0);

        let (sender, plain_rx) = mpsc::channel();
        let rx = Arc::new(Mutex::new(plain_rx));

        let mut brewers = Vec::with_capacity(size);
        for id in 0 .. size {
            brewers.push(Brewer::new(id, Arc::clone(&rx)));
        }

        Brewery {
            brewers,
            sender,
            start_time,
        }
    }

    ///
    /// Send function (job) with batch of Tea with Recipe to Brewers.
    ///
    /// # Arguments
    ///
    /// * `f` - function to send off to Brewers
    pub fn take_order<F>(&self, f: F)
        where F: FnOnce() + Send + 'static
    {
        let order = Box::new(f);

        self.sender
            .send(OrderTea::NewOrder(order))
            .unwrap();
    }

    ///
    /// Get info method to display number of Brewers assigned to Brewery.
    pub fn get_brewer_info(&self) {
        println!("Number of brewers: {}", &self.brewers.len());
    }

}

impl Drop for Brewery {
    fn drop(&mut self) {
        // After all jobs are sent terminate message is sent to close out worker pool.
        println!("Sending terminate message to all brewers.");

        for _ in &mut self.brewers {
            self.sender.send(OrderTea::Terminate).unwrap();
        }

        // Run any jobs that have not yet been completed before killing worker.
        for brewer in &mut self.brewers {
            println!("\tLetting go brewer {}", brewer.id);

            if let Some(thread) = brewer.thread.take() {
                thread.join().unwrap();
            }
        }

        // Print out run time metrics.
        println!("Elapsed time: {} ms", self.start_time.elapsed().as_millis());
    }
}

///
/// Worker that runs the Recipe and brews the batch of Tea.
struct Brewer {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Brewer {
    ///
    /// Create Brewer worker with receiver to fetch and process Order jobs.
    ///
    /// # Arguments
    ///
    /// * `id` - brewer number assigned.
    /// * `reciever` - receiver clone to receive jobs on.
    pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<OrderTea>>>) -> Brewer {
        let thread = thread::spawn(move || {
            loop {
                let make_tea = receiver.lock()
                    .unwrap()
                    .recv()
                    .unwrap();

                match make_tea {
                    OrderTea::NewOrder(order) => {
                        // TODO: Change this to DEBUG logs/
                        //println!("Brewer {} received order! Executing...", id);
                        order.call_box();
                    },
                    OrderTea::Terminate => {
                        println!("Brewer {} was let go...", id);
                        break;
                    }
                }
            }
        });

        Brewer { 
            id, 
            thread: Some(thread),
        }
    }
}

///
/// This function is passed to the brewer via a thread for it to process the batch of Tea.
///
/// # Arguments
///
/// * `tea_batch` - Array of Tea structs to be processed
/// * `recipe` - read only clone of recipe containing all steps
pub fn make_tea(mut tea_batch: Vec<Box<dyn Tea + Send>>, recipe: Arc<RwLock<Vec<Box<dyn Ingredient + Send + Sync>>>>) {
    let recipe = recipe.read().unwrap();
    // TODO: In the future, Fill will become a valid step in the recipe. For simplicity, this is
    // excluded at this stage in the project.
    // TODO: In the future, Tranfuse will become a valid step in the recipe. The Ingredient does not currently
    // exist, and additional logic may need to be introduced to handle how things are combined.
    for step in recipe.iter() {
        if let Some(steep) = step.as_any().downcast_ref::<Steep>() {
            tea_batch = steep.exec(tea_batch);
        } else if let Some(pour) = step.as_any().downcast_ref::<Pour>() {
            tea_batch = pour.exec(tea_batch);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Brewery;
    use crate::tea::Tea;
    use std::time::Instant;
    use std::any::Any;

    #[derive(Debug, PartialEq, Default)]
    struct TestTea {
        x: i32,
    }

    impl Tea for TestTea {
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[test]
    fn create_brewery_with_brewers() {
        let brewery = Brewery::new(4, Instant::now());
        assert_eq!(brewery.brewers.len(), 4);
    }

    #[test]
    #[should_panic]
    fn create_brewery_with_no_brewers() {
        let _brewery = Brewery::new(0, Instant::now());
    }

    //TODO figure out how to properly test threads
    //#[test]
    //fn brewery_sends_job_done_channel() {
    //    let brewery = Brewery::new(4, Instant::now());
    //    let tea = TestTea::new(Box::new(TestTea::default()));
    //    brewery.take_order(|| {
    //        make_tea(tea, recipe);
    //    });
    //}
}