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
use crate::commons::identifier::{Derivable, KeyIdentifier};
use futures::{future::BoxFuture, prelude::*};
use log::debug;

use super::super::{error::Error, MessageConfig, MessageSender, TaskCommandContent};
use std::time::Duration;

use rand::Rng;

pub struct Algorithm {}

impl Algorithm {
    fn get_targets(all_targets: Vec<KeyIdentifier>, replication_factor: f64) -> Vec<KeyIdentifier> {
        let number_to_select =
            1.max((all_targets.len() as f64 * replication_factor).floor() as u32);
        get_n_distinct_random_data(number_to_select, all_targets)
    }

    pub fn make_indefinite_future<T: 'static + TaskCommandContent>(
        sender: MessageSender,
        config: MessageConfig,
        request: T,
        targets: Vec<KeyIdentifier>,
    ) -> BoxFuture<'static, Result<(), Error>> {
        async move {
            let mut interval =
                tokio::time::interval(Duration::from_millis(config.timeout() as u64));
            loop {
                // The message to be sent is obtained
                interval.tick().await;
                // Targets are selected
                let targets_selected =
                    Algorithm::get_targets(targets.clone(), config.replication_factor());
                for target in targets_selected {
                    debug!("Message sent to {}", target.to_str());
                    sender
                        .send_message(target, request.clone())
                        .await
                        .map_err(|_| Error::SenderChannelError)?;
                }
            }
        }
        .boxed()
    }

    pub fn make_future<T: 'static + TaskCommandContent>(
        request: T,
        targets: Vec<KeyIdentifier>,
        sender: MessageSender,
        config: MessageConfig,
    ) -> BoxFuture<'static, Result<(), Error>> {
        async move {
            // Targets are selected
            let targets_selected = Algorithm::get_targets(targets, config.replication_factor());
            for target in targets_selected {
                let result_sending = sender.send_message(target, request.clone()).await;
                result_sending.map_err(|_| Error::SenderChannelError)?;
            }
            Ok(())
        }
        .boxed()
    }
}

fn get_n_distinct_random_data<D>(quantity: u32, mut data: Vec<D>) -> Vec<D> {
    if quantity as usize >= data.len() {
        return data;
    }
    let mut result: Vec<D> = Vec::new();
    let mut counter = 0u32;
    let mut rng = rand::thread_rng();
    while counter < quantity {
        let index = rng.gen_range(0..data.len());
        let value = data.remove(index);
        result.push(value);
        counter += 1;
    }
    result
}

#[cfg(test)]
mod test {

    use super::get_n_distinct_random_data;

    #[test]
    fn test_random_select() {
        let first = vec![1, 2, 3, 4, 5];
        let empty: Vec<i32> = vec![];
        assert_eq!(get_n_distinct_random_data(0, first.clone()), empty);
        assert_eq!(
            get_n_distinct_random_data(10, first.clone()),
            vec![1, 2, 3, 4, 5]
        );
        assert_eq!(get_n_distinct_random_data(3, first.clone()).len(), 3);
    }
}