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
use crate::{
block_synchronizer::{
handler::Error::{BlockDeliveryTimeout, BlockNotFound, Internal, PayloadSyncError},
BlockSynchronizeResult, Command, SyncError,
},
BlockHeader,
};
use async_trait::async_trait;
use fastcrypto::Hash;
use futures::future::join_all;
#[cfg(test)]
use mockall::*;
use std::time::Duration;
use storage::CertificateStore;
use thiserror::Error;
use tokio::{sync::mpsc::channel, time::timeout};
use tracing::{debug, error, instrument, trace};
use types::{metered_channel, Certificate, CertificateDigest, PrimaryMessage};
#[cfg(test)]
#[path = "tests/handler_tests.rs"]
mod handler_tests;
#[derive(Debug, Error, Copy, Clone)]
pub enum Error {
#[error("Block with id {block_id} not found")]
BlockNotFound { block_id: CertificateDigest },
#[error("Block with id {block_id} couldn't be retrieved, internal error occurred")]
Internal { block_id: CertificateDigest },
#[error("Timed out while waiting for {block_id} to become available after submitting for processing")]
BlockDeliveryTimeout { block_id: CertificateDigest },
#[error("Payload for block with {block_id} couldn't be synchronized: {error}")]
PayloadSyncError {
block_id: CertificateDigest,
error: SyncError,
},
}
impl Error {
pub fn block_id(&self) -> CertificateDigest {
match *self {
BlockNotFound { block_id }
| Internal { block_id }
| BlockDeliveryTimeout { block_id }
| PayloadSyncError { block_id, .. } => block_id,
}
}
}
#[cfg_attr(test, automock)]
#[async_trait]
pub trait Handler {
async fn get_and_synchronize_block_headers(
&self,
block_ids: Vec<CertificateDigest>,
) -> Vec<Result<Certificate, Error>>;
async fn get_block_headers(
&self,
block_ids: Vec<CertificateDigest>,
) -> Vec<BlockSynchronizeResult<BlockHeader>>;
async fn synchronize_block_payloads(
&self,
certificates: Vec<Certificate>,
) -> Vec<Result<Certificate, Error>>;
}
pub struct BlockSynchronizerHandler {
tx_block_synchronizer: metered_channel::Sender<Command>,
tx_core: metered_channel::Sender<PrimaryMessage>,
certificate_store: CertificateStore,
certificate_deliver_timeout: Duration,
}
impl BlockSynchronizerHandler {
pub fn new(
tx_block_synchronizer: metered_channel::Sender<Command>,
tx_core: metered_channel::Sender<PrimaryMessage>,
certificate_store: CertificateStore,
certificate_deliver_timeout: Duration,
) -> Self {
Self {
tx_block_synchronizer,
tx_core,
certificate_store,
certificate_deliver_timeout,
}
}
async fn wait_all(&self, certificates: Vec<Certificate>) -> Vec<Result<Certificate, Error>> {
let futures: Vec<_> = certificates
.into_iter()
.map(|c| self.wait(c.digest()))
.collect();
join_all(futures).await
}
async fn wait(&self, block_id: CertificateDigest) -> Result<Certificate, Error> {
if let Ok(result) = timeout(
self.certificate_deliver_timeout,
self.certificate_store.notify_read(block_id),
)
.await
{
result.map_err(|_| Error::Internal { block_id })
} else {
Err(Error::BlockDeliveryTimeout { block_id })
}
}
}
#[async_trait]
impl Handler for BlockSynchronizerHandler {
#[instrument(level="trace", skip_all, fields(num_block_ids = block_ids.len()))]
async fn get_and_synchronize_block_headers(
&self,
block_ids: Vec<CertificateDigest>,
) -> Vec<Result<Certificate, Error>> {
if block_ids.is_empty() {
trace!("No blocks were provided, will now return an empty list");
return vec![];
}
let sync_results = self.get_block_headers(block_ids).await;
let mut results: Vec<Result<Certificate, Error>> = Vec::new();
let mut wait_for = Vec::new();
for result in sync_results {
match result {
Ok(block_header) => {
if !block_header.fetched_from_storage {
self.tx_core
.send(PrimaryMessage::Certificate(
block_header.certificate.clone(),
))
.await
.expect("Couldn't send certificate to core");
wait_for.push(block_header.certificate.clone());
debug!(
"Need to causally complete {}",
block_header.certificate.digest()
);
} else {
results.push(Ok(block_header.certificate));
}
}
Err(err) => {
error!(
"Error occurred while synchronizing requested certificate {:?}",
err
);
results.push(Err(BlockNotFound {
block_id: err.block_id(),
}));
}
}
}
let mut wait_results = self.wait_all(wait_for).await;
results.append(&mut wait_results);
results
}
#[instrument(level="trace", skip_all, fields(num_block_ids = block_ids.len()))]
async fn get_block_headers(
&self,
block_ids: Vec<CertificateDigest>,
) -> Vec<BlockSynchronizeResult<BlockHeader>> {
if block_ids.is_empty() {
trace!("No blocks were provided, will now return an empty list");
return vec![];
}
let (tx, mut rx) = channel(block_ids.len());
self.tx_block_synchronizer
.send(Command::SynchronizeBlockHeaders {
block_ids,
respond_to: tx,
})
.await
.expect("Couldn't send message to block synchronizer");
let mut results = Vec::new();
while let Some(result) = rx.recv().await {
results.push(result)
}
results
}
#[instrument(level = "trace", skip_all, fields(num_certificates = certificates.len()))]
async fn synchronize_block_payloads(
&self,
certificates: Vec<Certificate>,
) -> Vec<Result<Certificate, Error>> {
if certificates.is_empty() {
trace!("No certificates were provided, will now return an empty list");
return vec![];
}
let (tx, mut rx) = channel(certificates.len());
self.tx_block_synchronizer
.send(Command::SynchronizeBlockPayload {
certificates,
respond_to: tx,
})
.await
.expect("Couldn't send message to block synchronizer");
let mut results = Vec::new();
while let Some(result) = rx.recv().await {
let r = result
.map(|h| h.certificate)
.map_err(|e| Error::PayloadSyncError {
block_id: e.block_id(),
error: e,
});
if let Err(err) = r {
error!(
"Error for payload synchronization with block id {}, error: {err}",
err.block_id()
);
}
results.push(r)
}
results
}
}