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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! 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::sync::mpsc::TryRecvError;
use std::time::Instant;
use std::{
    sync::mpsc::{sync_channel, Receiver, 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>>,
        config: PoolConfig,
    ) -> JoinHandle<()> {
        let thread_builder = thread::Builder::new().name("endorsement-pool".into());
        thread_builder
            .spawn(move || {
                let this = Self {
                    receiver,
                    endorsement_pool,
                };
                this.run(config)
            })
            .expect("failed to spawn thread : endorsement-pool")
    }

    /// Runs the thread
    fn run(self, config: PoolConfig) {
        let buffer_swap_interval = config.endorsement_pool_swap_interval.to_duration();
        let mut endorsement_pool_buffer = self.endorsement_pool.read().clone();
        let mut modified = false;
        let mut last_buffer_swap = Instant::now();
        loop {
            // try to get pending messages to process
            let mut cmd = match self.receiver.try_recv() {
                Err(TryRecvError::Disconnected) => break,
                Err(TryRecvError::Empty) => None,
                Ok(Command::Stop) => break,
                Ok(c) => Some(c),
            };

            // Swap buffers asap if there are no messages to process.
            // This avoids waiting when we have cpu time now for swapping.
            if cmd.is_none() {
                if modified {
                    self.endorsement_pool
                        .write()
                        .replace_with(&endorsement_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = Instant::now();
            }

            // wait for new command if none found
            if cmd.is_none() {
                cmd = match self.receiver.recv_timeout(buffer_swap_interval) {
                    Err(RecvTimeoutError::Disconnected) => break,
                    Err(RecvTimeoutError::Timeout) => None,
                    Ok(Command::Stop) => break,
                    Ok(c) => Some(c),
                }
            }

            match cmd {
                Some(Command::AddItems(endorsements)) => {
                    endorsement_pool_buffer.add_endorsements(endorsements);
                    modified = true;
                }
                Some(Command::NotifyFinalCsPeriods(final_cs_periods)) => {
                    endorsement_pool_buffer.notify_final_cs_periods(&final_cs_periods);
                    modified = true;
                }
                Some(_) => {
                    warn!("EndorsementPoolThread received an unexpected command");
                }
                None => {}
            }

            // On a regular basis, swap buffers if we haven't for a while.
            // This is useful under heavy congestion. Otherwise we swap as soon as the queue is empty.
            if Instant::now().saturating_duration_since(last_buffer_swap) >= buffer_swap_interval {
                if modified {
                    self.endorsement_pool
                        .write()
                        .replace_with(&endorsement_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = Instant::now();
            }
        }
    }
}

/// 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 buffer_swap_interval = config.operation_pool_swap_interval.to_duration();
        let mut operation_pool_buffer = self.operation_pool.read().clone();
        let mut start_time = Instant::now();
        let tick = config.operation_pool_refresh_interval.to_duration();
        let mut modified = false;
        let mut last_buffer_swap = Instant::now();
        loop {
            // refresh if needed
            let duration = (start_time + tick).saturating_duration_since(Instant::now());
            if duration.is_zero() {
                operation_pool_buffer.refresh();
                start_time = Instant::now();
                modified = true;
            }

            // try to get pending messages to process
            let mut cmd = match self.receiver.try_recv() {
                Err(TryRecvError::Disconnected) => break,
                Err(TryRecvError::Empty) => None,
                Ok(Command::Stop) => break,
                Ok(c) => Some(c),
            };

            // swap buffers asap if there are no messages to process
            if cmd.is_none() {
                if modified {
                    self.operation_pool
                        .write()
                        .replace_with(&operation_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = Instant::now();
            }

            // wait for new command if none found
            if cmd.is_none() {
                cmd = match self
                    .receiver
                    .recv_timeout(std::cmp::min(buffer_swap_interval, duration))
                {
                    Err(RecvTimeoutError::Disconnected) => break,
                    Err(RecvTimeoutError::Timeout) => None,
                    Ok(Command::Stop) => break,
                    Ok(c) => Some(c),
                };
            }

            match cmd {
                Some(Command::AddItems(operations)) => {
                    operation_pool_buffer.add_operations(operations);
                    modified = true;
                }
                Some(Command::NotifyFinalCsPeriods(final_cs_periods)) => {
                    operation_pool_buffer.notify_final_cs_periods(&final_cs_periods);
                    modified = true;
                }
                Some(_) => {
                    warn!("OperationPoolThread received an unexpected command");
                }
                None => {}
            };

            // On a regular basis, swap buffers if we haven't for a while.
            // This is useful under heavy congestion. Otherwise we swap as soon as the queue is empty.
            if last_buffer_swap.elapsed() >= buffer_swap_interval {
                if modified {
                    self.operation_pool
                        .write()
                        .replace_with(&operation_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = 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>>,
        config: PoolConfig,
    ) -> JoinHandle<()> {
        let thread_builder = thread::Builder::new().name("denunciation-pool".into());
        thread_builder
            .spawn(move || {
                let this = Self {
                    receiver,
                    denunciation_pool,
                };
                this.run(config)
            })
            .expect("failed to spawn thread: denunciation-pool")
    }

    /// Run the thread.
    fn run(self, config: PoolConfig) {
        let buffer_swap_interval = config.denunciation_pool_swap_interval.to_duration();
        let mut denunciation_pool_buffer = self.denunciation_pool.read().clone();
        let mut start_time = Instant::now();
        let tick = config.denunciation_pool_refresh_interval.to_duration();
        let mut modified = false;
        let mut last_buffer_swap = Instant::now();
        loop {
            // refresh if needed
            let duration = (start_time + tick).saturating_duration_since(Instant::now());
            if duration.is_zero() {
                denunciation_pool_buffer.refresh_execution_cache();
                start_time = Instant::now();
                modified = true;
            }

            // try to get pending messages to process
            let mut cmd = match self.receiver.try_recv() {
                Err(TryRecvError::Disconnected) => break,
                Err(TryRecvError::Empty) => None,
                Ok(Command::Stop) => break,
                Ok(c) => Some(c),
            };

            // Swap buffers asap if there are no messages to process.
            // This avoids waiting when we have cpu time now for swapping.
            if cmd.is_none() {
                if modified {
                    self.denunciation_pool
                        .write()
                        .replace_with(&denunciation_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = Instant::now();
            }

            // wait for new command if none found
            if cmd.is_none() {
                cmd = match self
                    .receiver
                    .recv_timeout(std::cmp::min(buffer_swap_interval, duration))
                {
                    Err(RecvTimeoutError::Disconnected) => break,
                    Err(RecvTimeoutError::Timeout) => None,
                    Ok(Command::Stop) => break,
                    Ok(c) => Some(c),
                };
            }

            match cmd {
                Some(Command::AddDenunciationPrecursor(de_p)) => {
                    denunciation_pool_buffer.add_denunciation_precursor(de_p);
                    modified = true;
                }
                Some(Command::AddItems(endorsements)) => {
                    denunciation_pool_buffer.add_endorsements(endorsements);
                    modified = true;
                }
                Some(Command::NotifyFinalCsPeriods(final_cs_periods)) => {
                    denunciation_pool_buffer.notify_final_cs_periods(&final_cs_periods);
                    modified = true;
                }
                Some(_) => {
                    warn!("DenunciationPoolThread received an unexpected command");
                }
                None => {}
            }

            // On a regular basis, swap buffers if we haven't for a while.
            // This is useful under heavy congestion. Otherwise we swap as soon as the queue is empty.
            if Instant::now().saturating_duration_since(last_buffer_swap) >= buffer_swap_interval {
                if modified {
                    self.denunciation_pool
                        .write()
                        .replace_with(&denunciation_pool_buffer);
                    modified = false;
                }
                last_buffer_swap = Instant::now();
            }
        }
    }
}

/// 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, config);
    let denunciations_thread_handle =
        DenunciationPoolThread::spawn(denunciations_input_receiver, denunciation_pool, config);

    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))
}