-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathevaluator.rs
81 lines (66 loc) · 2.23 KB
/
evaluator.rs
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
use std::thread;
use crossbeam_channel::{Receiver, SendError, Sender};
use crate::{Error, Evaluation, Model};
/// Evaluates a model in a background thread
pub struct Evaluator {
trigger_tx: Sender<TriggerEvaluation>,
event_rx: Receiver<ModelEvent>,
}
impl Evaluator {
/// Create an `Evaluator` from a model
pub fn from_model(model: Model) -> Self {
let (event_tx, event_rx) = crossbeam_channel::bounded(0);
let (trigger_tx, trigger_rx) = crossbeam_channel::bounded(0);
thread::spawn(move || {
while matches!(trigger_rx.recv(), Ok(TriggerEvaluation)) {
if let Err(SendError(_)) =
event_tx.send(ModelEvent::ChangeDetected)
{
break;
}
let evaluation = match model.evaluate() {
Ok(evaluation) => evaluation,
Err(err) => {
if let Err(SendError(_)) =
event_tx.send(ModelEvent::Error(err))
{
break;
}
continue;
}
};
if let Err(SendError(_)) =
event_tx.send(ModelEvent::Evaluation(evaluation))
{
break;
};
}
// The channel is disconnected, which means this instance of
// `Evaluator`, as well as all `Sender`s created from it, have been
// dropped. We're done.
});
Self {
trigger_tx,
event_rx,
}
}
/// Access a channel for triggering evaluations
pub fn trigger(&self) -> Sender<TriggerEvaluation> {
self.trigger_tx.clone()
}
/// Access a channel for receiving status updates
pub fn events(&self) -> Receiver<ModelEvent> {
self.event_rx.clone()
}
}
/// Command received by [`Evaluator`] through its channel
pub struct TriggerEvaluation;
/// An event emitted by [`Evaluator`]
pub enum ModelEvent {
/// A change in the model has been detected
ChangeDetected,
/// The model has been evaluated
Evaluation(Evaluation),
/// An error
Error(Error),
}