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
use tokio_util::sync::CancellationToken;

use super::{
    errors::ValidationError, validation::Validation, ValidationCommand, ValidationResponse,
};
use crate::database::{DatabaseCollection, DB};
use crate::message::MessageTaskCommand;
use crate::protocol::protocol_message_manager::TapleMessages;
use crate::Notification;
use crate::{
    commons::{
        channel::{ChannelData, MpscChannel, SenderEnd},
        self_signature_manager::SelfSignatureManager,
    },
    governance::GovernanceAPI,
};

#[derive(Clone, Debug)]
#[allow(dead_code)]
pub struct ValidationAPI {
    sender: SenderEnd<ValidationCommand, ValidationResponse>,
}

#[allow(dead_code)]
impl ValidationAPI {
    pub fn new(sender: SenderEnd<ValidationCommand, ValidationResponse>) -> Self {
        Self { sender }
    }
}

pub struct ValidationManager<C: DatabaseCollection> {
    /// Communication channel for incoming petitions
    input_channel: MpscChannel<ValidationCommand, ValidationResponse>,
    /// Validation functions
    inner_validation: Validation<C>,
    token: CancellationToken,
    notification_tx: tokio::sync::mpsc::Sender<Notification>,
}

impl<C: DatabaseCollection> ValidationManager<C> {
    pub fn new(
        input_channel: MpscChannel<ValidationCommand, ValidationResponse>,
        gov_api: GovernanceAPI,
        database: DB<C>,
        signature_manager: SelfSignatureManager,
        token: CancellationToken,
        notification_tx: tokio::sync::mpsc::Sender<Notification>,
        message_channel: SenderEnd<MessageTaskCommand<TapleMessages>, ()>,
    ) -> Self {
        Self {
            input_channel,
            inner_validation: Validation::new(
                gov_api,
                database,
                signature_manager,
                message_channel,
            ),
            token,
            notification_tx,
        }
    }

    pub async fn run(mut self) {
        loop {
            tokio::select! {
                command = self.input_channel.receive() => {
                    match command {
                        Some(command) => {
                            let result = self.process_command(command).await;
                            if result.is_err() {
                                log::error!("{}", result.unwrap_err());
                                break;
                            }
                        }
                        None => {
                            break;
                        },
                    }
                },
                _ = self.token.cancelled() => {
                    log::debug!("Shutdown received");
                    break;
                }
            }
        }
        self.token.cancel();
        log::info!("Ended");
    }

    async fn process_command(
        &mut self,
        command: ChannelData<ValidationCommand, ValidationResponse>,
    ) -> Result<(), ValidationError> {
        let (sender, data) = match command {
            ChannelData::AskData(data) => {
                let (sender, data) = data.get();
                (Some(sender), data)
            }
            ChannelData::TellData(data) => {
                let data = data.get();
                (None, data)
            }
        };
        let response = {
            match data {
                ValidationCommand::ValidationEvent {
                    validation_event,
                    sender,
                } => {
                    let result = self
                        .inner_validation
                        .validation_event(validation_event, sender)
                        .await;
                    match result {
                        Err(ValidationError::ChannelError(_)) => return result.map(|_| ()),
                        _ => ValidationResponse::ValidationEventResponse(result),
                    }
                }
                ValidationCommand::AskForValidation(_) => {
                    log::error!("Ask for Validation in Validation Manager");
                    return Ok(());
                }
            }
        };
        if sender.is_some() {
            sender.unwrap().send(response).expect("Sender Dropped");
        }
        Ok(())
    }
}