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
//! Copyright (c) 2022 MASSA LABS <info@massa.net>

//! Write worker for the pools, allowing asynchronous writes.

use crate::controller_impl::{Command, PoolManagerImpl};
use crate::denunciation_pool::DenunciationPool;
use crate::operation_pool::OperationPool;
use crate::{controller_impl::PoolControllerImpl, endorsement_pool::EndorsementPool};
use massa_pool_exports::PoolConfig;
use massa_pool_exports::{PoolChannels, PoolController, PoolManager};
use massa_storage::Storage;
use massa_wallet::Wallet;
use parking_lot::RwLock;
use std::time::Instant;
use std::{
    sync::mpsc::{sync_channel, Receiver, RecvError, RecvTimeoutError},
    sync::Arc,
    thread,
    thread::JoinHandle,
};
use tracing::warn;

/// Endorsement pool write thread instance
pub(crate) struct EndorsementPoolThread {
    /// Command reception channel
    receiver: Receiver<Command>,
    /// Shared reference to the pool
    endorsement_pool: Arc<RwLock<EndorsementPool>>,
}

impl EndorsementPoolThread {
    /// Spawns a pool writer thread, returning a join handle.
    pub(crate) fn spawn(
        receiver: Receiver<Command>,
        endorsement_pool: Arc<RwLock<EndorsementPool>>,
    ) -> JoinHandle<()> {
        let thread_builder = thread::Builder::new().name("endorsement-pool".into());
        thread_builder
            .spawn(|| {
                let this = Self {
                    receiver,
                    endorsement_pool,
                };
                this.run()
            })
            .expect("failed to spawn thread : endorsement-pool")
    }

    /// Runs the thread
    fn run(self) {
        loop {
            match self.receiver.recv() {
                Err(RecvError) => break,
                Ok(Command::Stop) => {
                    break;
                }
                Ok(Command::AddItems(endorsements)) => {
                    self.endorsement_pool.write().add_endorsements(endorsements)
                }
                Ok(Command::NotifyFinalCsPeriods(final_cs_periods)) => self
                    .endorsement_pool
                    .write()
                    .notify_final_cs_periods(&final_cs_periods),
                _ => {
                    warn!("EndorsementPoolThread received an unexpected command");
                    continue;
                }
            }
        }
    }
}

/// Operation pool writer thread.
pub(crate) struct OperationPoolThread {
    /// Command reception channel
    receiver: Receiver<Command>,
    /// Shared reference to the operation pool
    operation_pool: Arc<RwLock<OperationPool>>,
}

impl OperationPoolThread {
    /// Spawns a pool writer thread, returning a join handle.
    pub(crate) fn spawn(
        receiver: Receiver<Command>,
        operation_pool: Arc<RwLock<OperationPool>>,
        config: PoolConfig,
    ) -> JoinHandle<()> {
        let thread_builder = thread::Builder::new().name("operation-pool".into());
        thread_builder
            .spawn(move || {
                let this = Self {
                    receiver,
                    operation_pool,
                };
                this.run(config)
            })
            .expect("failed to spawn thread: operation-pool")
    }

    /// Run the thread.
    fn run(self, config: PoolConfig) {
        let mut start_time = Instant::now();
        let tick = config.operation_pool_refresh_interval.to_duration();
        loop {
            let duration = (start_time + tick).saturating_duration_since(Instant::now());
            if !duration.is_zero() {
                match self.receiver.recv_timeout(duration) {
                    Err(RecvTimeoutError::Disconnected) | Ok(Command::Stop) => break,
                    Ok(Command::AddItems(operations)) => {
                        self.operation_pool.write().add_operations(operations)
                    }
                    Ok(Command::NotifyFinalCsPeriods(final_cs_periods)) => self
                        .operation_pool
                        .write()
                        .notify_final_cs_periods(&final_cs_periods),
                    Ok(_) => {
                        warn!("OperationPoolThread received an unexpected command");
                        continue;
                    }
                    Err(RecvTimeoutError::Timeout) => {}
                };
            } else {
                self.operation_pool.write().refresh();
                start_time = Instant::now();
            }
        }
    }
}

/// Denunciation pool writer thread.
pub(crate) struct DenunciationPoolThread {
    /// Command reception channel
    receiver: Receiver<Command>,
    /// Shared reference to the denunciation pool
    denunciation_pool: Arc<RwLock<DenunciationPool>>,
}

impl DenunciationPoolThread {
    /// Spawns a pool writer thread, returning a join handle.
    pub(crate) fn spawn(
        receiver: Receiver<Command>,
        denunciation_pool: Arc<RwLock<DenunciationPool>>,
    ) -> JoinHandle<()> {
        let thread_builder = thread::Builder::new().name("denunciation-pool".into());
        thread_builder
            .spawn(|| {
                let this = Self {
                    receiver,
                    denunciation_pool,
                };
                this.run()
            })
            .expect("failed to spawn thread : denunciation-pool")
    }

    /// Run the thread.
    fn run(self) {
        loop {
            match self.receiver.recv() {
                Err(RecvError) => {
                    break;
                }
                Ok(Command::Stop) => {
                    break;
                }
                Ok(Command::AddDenunciationPrecursor(de_p)) => self
                    .denunciation_pool
                    .write()
                    .add_denunciation_precursor(de_p),
                Ok(Command::AddItems(endorsements)) => self
                    .denunciation_pool
                    .write()
                    .add_endorsements(endorsements),
                Ok(Command::NotifyFinalCsPeriods(final_cs_periods)) => self
                    .denunciation_pool
                    .write()
                    .notify_final_cs_periods(&final_cs_periods),
            };
        }
    }
}

/// Start pool manager and controller
#[allow(clippy::type_complexity)]
pub fn start_pool_controller(
    config: PoolConfig,
    storage: &Storage,
    channels: PoolChannels,
    wallet: Arc<RwLock<Wallet>>,
) -> (Box<dyn PoolManager>, Box<dyn PoolController>) {
    let (operations_input_sender, operations_input_receiver) =
        sync_channel(config.operations_channel_size);
    let (endorsements_input_sender, endorsements_input_receiver) =
        sync_channel(config.endorsements_channel_size);
    let (denunciations_input_sender, denunciations_input_receiver) =
        sync_channel(config.denunciations_channel_size);
    let operation_pool = Arc::new(RwLock::new(OperationPool::init(
        config,
        storage,
        channels.clone(),
        wallet.clone(),
    )));
    let endorsement_pool = Arc::new(RwLock::new(EndorsementPool::init(
        config,
        storage,
        channels.clone(),
        wallet,
    )));
    let denunciation_pool = Arc::new(RwLock::new(DenunciationPool::init(config, channels)));
    let controller = PoolControllerImpl {
        _config: config,
        operation_pool: operation_pool.clone(),
        endorsement_pool: endorsement_pool.clone(),
        denunciation_pool: denunciation_pool.clone(),
        operations_input_sender: operations_input_sender.clone(),
        endorsements_input_sender: endorsements_input_sender.clone(),
        denunciations_input_sender: denunciations_input_sender.clone(),
        last_cs_final_periods: vec![0u64; usize::from(config.thread_count)],
    };

    let operations_thread_handle =
        OperationPoolThread::spawn(operations_input_receiver, operation_pool, config);
    let endorsements_thread_handle =
        EndorsementPoolThread::spawn(endorsements_input_receiver, endorsement_pool);
    let denunciations_thread_handle =
        DenunciationPoolThread::spawn(denunciations_input_receiver, denunciation_pool);

    let manager = PoolManagerImpl {
        operations_thread_handle: Some(operations_thread_handle),
        endorsements_thread_handle: Some(endorsements_thread_handle),
        denunciations_thread_handle: Some(denunciations_thread_handle),
        operations_input_sender,
        endorsements_input_sender,
        denunciations_input_sender,
    };
    (Box::new(manager), Box::new(controller))
}