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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
#![forbid(unsafe_code)]
use crate::{
logging::{LogEntry, LogSchema},
metrics::{increment_counter, start_timer},
network::StorageServiceNetworkEvents,
};
use ::network::ProtocolId;
use bounded_executor::BoundedExecutor;
use diem_config::config::StorageServiceConfig;
use diem_logger::prelude::*;
use diem_types::{
account_state_blob::AccountStatesChunkWithProof,
epoch_change::EpochChangeProof,
transaction::{TransactionListWithProof, TransactionOutputListWithProof, Version},
};
use futures::stream::StreamExt;
use serde::{Deserialize, Serialize};
use std::{sync::Arc, time::Duration};
use storage_interface::DbReader;
use storage_service_types::{
AccountStatesChunkWithProofRequest, CompleteDataRange, DataSummary,
EpochEndingLedgerInfoRequest, ProtocolMetadata, Result, ServerProtocolVersion,
StorageServerSummary, StorageServiceError, StorageServiceRequest, StorageServiceResponse,
TransactionOutputsWithProofRequest, TransactionsWithProofRequest,
};
use thiserror::Error;
use tokio::runtime::Handle;
mod logging;
mod metrics;
pub mod network;
#[cfg(test)]
mod tests;
pub const STORAGE_SERVER_VERSION: u64 = 1;
const SUMMARY_LOG_FREQUENCY_SECS: u64 = 5;
#[derive(Clone, Debug, Deserialize, Error, PartialEq, Serialize)]
pub enum Error {
#[error("Invalid request received: {0}")]
InvalidRequest(String),
#[error("Storage error encountered: {0}")]
StorageErrorEncountered(String),
#[error("Unexpected error encountered: {0}")]
UnexpectedErrorEncountered(String),
}
impl Error {
fn get_label(&self) -> &'static str {
match self {
Error::InvalidRequest(_) => "invalid_request",
Error::StorageErrorEncountered(_) => "storage_error",
Error::UnexpectedErrorEncountered(_) => "unexpected_error",
}
}
}
pub struct StorageServiceServer<T> {
config: StorageServiceConfig,
bounded_executor: BoundedExecutor,
storage: T,
network_requests: StorageServiceNetworkEvents,
}
impl<T: StorageReaderInterface> StorageServiceServer<T> {
pub fn new(
config: StorageServiceConfig,
executor: Handle,
storage: T,
network_requests: StorageServiceNetworkEvents,
) -> Self {
let bounded_executor =
BoundedExecutor::new(config.max_concurrent_requests as usize, executor);
Self {
config,
bounded_executor,
storage,
network_requests,
}
}
pub async fn start(mut self) {
while let Some(request) = self.network_requests.next().await {
let (peer, protocol, request, response_sender) = request;
debug!(LogSchema::new(LogEntry::ReceivedStorageRequest)
.request(&request)
.message(&format!(
"Received storage request. Peer: {:?}, protocol: {:?}.",
peer, protocol,
)));
let storage = self.storage.clone();
let config = self.config;
self.bounded_executor
.spawn_blocking(move || {
let response = Handler::new(config, storage).call(protocol, request);
log_storage_response(&response);
response_sender.send(response);
})
.await;
}
}
}
#[derive(Clone)]
pub struct Handler<T> {
config: StorageServiceConfig,
storage: T,
}
impl<T: StorageReaderInterface> Handler<T> {
pub fn new(config: StorageServiceConfig, storage: T) -> Self {
Self { config, storage }
}
pub fn call(
&self,
protocol: ProtocolId,
request: StorageServiceRequest,
) -> Result<StorageServiceResponse> {
increment_counter(
&metrics::STORAGE_REQUESTS_RECEIVED,
protocol,
request.get_label().into(),
);
let _timer = start_timer(
&metrics::STORAGE_REQUEST_PROCESSING_LATENCY,
protocol,
request.get_label().into(),
);
let response = match &request {
StorageServiceRequest::GetAccountStatesChunkWithProof(request) => {
self.get_account_states_chunk_with_proof(request)
}
StorageServiceRequest::GetEpochEndingLedgerInfos(request) => {
self.get_epoch_ending_ledger_infos(request)
}
StorageServiceRequest::GetNumberOfAccountsAtVersion(version) => {
self.get_number_of_accounts_at_version(*version)
}
StorageServiceRequest::GetServerProtocolVersion => self.get_server_protocol_version(),
StorageServiceRequest::GetStorageServerSummary => self.get_storage_server_summary(),
StorageServiceRequest::GetTransactionOutputsWithProof(request) => {
self.get_transaction_outputs_with_proof(request)
}
StorageServiceRequest::GetTransactionsWithProof(request) => {
self.get_transactions_with_proof(request)
}
};
match response {
Err(error) => {
increment_counter(
&metrics::STORAGE_ERRORS_ENCOUNTERED,
protocol,
error.get_label().into(),
);
error!(LogSchema::new(LogEntry::StorageServiceError)
.error(&error)
.request(&request));
Err(StorageServiceError::InternalError(error.to_string()))
}
Ok(response) => {
increment_counter(
&metrics::STORAGE_RESPONSES_SENT,
protocol,
response.get_label().into(),
);
Ok(response)
}
}
}
fn get_account_states_chunk_with_proof(
&self,
request: &AccountStatesChunkWithProofRequest,
) -> Result<StorageServiceResponse, Error> {
let account_states_chunk_with_proof = self.storage.get_account_states_chunk_with_proof(
request.version,
request.start_account_index,
request.end_account_index,
)?;
Ok(StorageServiceResponse::AccountStatesChunkWithProof(
account_states_chunk_with_proof,
))
}
fn get_epoch_ending_ledger_infos(
&self,
request: &EpochEndingLedgerInfoRequest,
) -> Result<StorageServiceResponse, Error> {
let epoch_change_proof = self
.storage
.get_epoch_ending_ledger_infos(request.start_epoch, request.expected_end_epoch)?;
Ok(StorageServiceResponse::EpochEndingLedgerInfos(
epoch_change_proof,
))
}
fn get_number_of_accounts_at_version(
&self,
version: Version,
) -> Result<StorageServiceResponse, Error> {
let number_of_accounts = self.storage.get_number_of_accounts(version)?;
Ok(StorageServiceResponse::NumberOfAccountsAtVersion(
number_of_accounts,
))
}
fn get_server_protocol_version(&self) -> Result<StorageServiceResponse, Error> {
let server_protocol_version = ServerProtocolVersion {
protocol_version: STORAGE_SERVER_VERSION,
};
Ok(StorageServiceResponse::ServerProtocolVersion(
server_protocol_version,
))
}
fn get_storage_server_summary(&self) -> Result<StorageServiceResponse, Error> {
let storage_server_summary = StorageServerSummary {
protocol_metadata: ProtocolMetadata {
max_epoch_chunk_size: self.config.max_epoch_chunk_size,
max_transaction_chunk_size: self.config.max_transaction_chunk_size,
max_transaction_output_chunk_size: self.config.max_transaction_output_chunk_size,
max_account_states_chunk_size: self.config.max_account_states_chunk_sizes,
},
data_summary: self.storage.get_data_summary()?,
};
Ok(StorageServiceResponse::StorageServerSummary(
storage_server_summary,
))
}
fn get_transaction_outputs_with_proof(
&self,
request: &TransactionOutputsWithProofRequest,
) -> Result<StorageServiceResponse, Error> {
let transaction_output_list_with_proof = self.storage.get_transaction_outputs_with_proof(
request.proof_version,
request.start_version,
request.end_version,
)?;
Ok(StorageServiceResponse::TransactionOutputsWithProof(
transaction_output_list_with_proof,
))
}
fn get_transactions_with_proof(
&self,
request: &TransactionsWithProofRequest,
) -> Result<StorageServiceResponse, Error> {
let transactions_with_proof = self.storage.get_transactions_with_proof(
request.proof_version,
request.start_version,
request.end_version,
request.include_events,
)?;
Ok(StorageServiceResponse::TransactionsWithProof(
transactions_with_proof,
))
}
}
pub trait StorageReaderInterface: Clone + Send + 'static {
fn get_data_summary(&self) -> Result<DataSummary, Error>;
fn get_transactions_with_proof(
&self,
proof_version: u64,
start_version: u64,
end_version: u64,
include_events: bool,
) -> Result<TransactionListWithProof, Error>;
fn get_epoch_ending_ledger_infos(
&self,
start_epoch: u64,
expected_end_epoch: u64,
) -> Result<EpochChangeProof, Error>;
fn get_transaction_outputs_with_proof(
&self,
proof_version: u64,
start_version: u64,
end_version: u64,
) -> Result<TransactionOutputListWithProof, Error>;
fn get_number_of_accounts(&self, version: u64) -> Result<u64, Error>;
fn get_account_states_chunk_with_proof(
&self,
version: u64,
start_account_index: u64,
end_account_index: u64,
) -> Result<AccountStatesChunkWithProof, Error>;
}
#[derive(Clone)]
pub struct StorageReader {
storage: Arc<dyn DbReader>,
}
impl StorageReader {
pub fn new(storage: Arc<dyn DbReader>) -> Self {
Self { storage }
}
fn fetch_account_states_range(
&self,
latest_version: Version,
transactions_range: &Option<CompleteDataRange<Version>>,
) -> Result<Option<CompleteDataRange<Version>>, Error> {
let pruning_window = self
.storage
.get_state_prune_window()
.map(|window| window as u64);
if let Some(pruning_window) = pruning_window {
if latest_version > pruning_window {
let mut lowest_account_version =
latest_version.checked_sub(pruning_window).ok_or_else(|| {
Error::UnexpectedErrorEncountered(
"Lowest account states version has overflown!".into(),
)
})?;
lowest_account_version =
lowest_account_version.checked_add(1).ok_or_else(|| {
Error::UnexpectedErrorEncountered(
"Lowest account states version has overflown!".into(),
)
})?;
let account_range = CompleteDataRange::new(lowest_account_version, latest_version)
.map_err(|error| Error::UnexpectedErrorEncountered(error.to_string()))?;
return Ok(Some(account_range));
}
}
Ok(*transactions_range)
}
fn fetch_transaction_range(
&self,
latest_version: Version,
) -> Result<Option<CompleteDataRange<Version>>, Error> {
let first_transaction_version = self
.storage
.get_first_txn_version()
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
if let Some(first_transaction_version) = first_transaction_version {
let transaction_range =
CompleteDataRange::new(first_transaction_version, latest_version)
.map_err(|error| Error::UnexpectedErrorEncountered(error.to_string()))?;
Ok(Some(transaction_range))
} else {
Ok(None)
}
}
fn fetch_transaction_output_range(
&self,
latest_version: Version,
) -> Result<Option<CompleteDataRange<Version>>, Error> {
let first_output_version = self
.storage
.get_first_write_set_version()
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
if let Some(first_output_version) = first_output_version {
let output_range = CompleteDataRange::new(first_output_version, latest_version)
.map_err(|error| Error::UnexpectedErrorEncountered(error.to_string()))?;
Ok(Some(output_range))
} else {
Ok(None)
}
}
}
impl StorageReaderInterface for StorageReader {
fn get_data_summary(&self) -> Result<DataSummary, Error> {
let latest_ledger_info_with_sigs = self
.storage
.get_latest_ledger_info()
.map_err(|err| Error::StorageErrorEncountered(err.to_string()))?;
let latest_ledger_info = latest_ledger_info_with_sigs.ledger_info();
let epoch_ending_ledger_infos = if latest_ledger_info.ends_epoch() {
let highest_ending_epoch = latest_ledger_info.epoch();
Some(CompleteDataRange::from_genesis(highest_ending_epoch))
} else if latest_ledger_info.epoch() > 0 {
let highest_ending_epoch =
latest_ledger_info.epoch().checked_sub(1).ok_or_else(|| {
Error::UnexpectedErrorEncountered("Highest ending epoch overflowed!".into())
})?;
Some(CompleteDataRange::from_genesis(highest_ending_epoch))
} else {
None
};
let latest_version = latest_ledger_info.version();
let transactions = self.fetch_transaction_range(latest_version)?;
let transaction_outputs = self.fetch_transaction_output_range(latest_version)?;
let account_states = self.fetch_account_states_range(latest_version, &transactions)?;
let data_summary = DataSummary {
synced_ledger_info: Some(latest_ledger_info_with_sigs),
epoch_ending_ledger_infos,
transactions,
transaction_outputs,
account_states,
};
Ok(data_summary)
}
fn get_transactions_with_proof(
&self,
proof_version: u64,
start_version: u64,
end_version: u64,
include_events: bool,
) -> Result<TransactionListWithProof, Error> {
let expected_num_transactions = inclusive_range_len(start_version, end_version)?;
let transaction_list_with_proof = self
.storage
.get_transactions(
start_version,
expected_num_transactions,
proof_version,
include_events,
)
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
Ok(transaction_list_with_proof)
}
fn get_epoch_ending_ledger_infos(
&self,
start_epoch: u64,
expected_end_epoch: u64,
) -> Result<EpochChangeProof, Error> {
let expected_end_epoch = expected_end_epoch.checked_add(1).ok_or_else(|| {
Error::UnexpectedErrorEncountered("Expected end epoch has overflown!".into())
})?;
let epoch_change_proof = self
.storage
.get_epoch_ending_ledger_infos(start_epoch, expected_end_epoch)
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
Ok(epoch_change_proof)
}
fn get_transaction_outputs_with_proof(
&self,
proof_version: u64,
start_version: u64,
end_version: u64,
) -> Result<TransactionOutputListWithProof, Error> {
let expected_num_outputs = inclusive_range_len(start_version, end_version)?;
let output_list_with_proof = self
.storage
.get_transaction_outputs(start_version, expected_num_outputs, proof_version)
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
Ok(output_list_with_proof)
}
fn get_number_of_accounts(&self, version: u64) -> Result<u64, Error> {
let number_of_accounts = self
.storage
.get_account_count(version)
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
Ok(number_of_accounts as u64)
}
fn get_account_states_chunk_with_proof(
&self,
version: u64,
start_account_index: u64,
end_account_index: u64,
) -> Result<AccountStatesChunkWithProof, Error> {
let expected_num_accounts = inclusive_range_len(start_account_index, end_account_index)?;
let account_states_chunk_with_proof = self
.storage
.get_account_chunk_with_proof(
version,
start_account_index as usize,
expected_num_accounts as usize,
)
.map_err(|error| Error::StorageErrorEncountered(error.to_string()))?;
Ok(account_states_chunk_with_proof)
}
}
fn inclusive_range_len(start: u64, end: u64) -> Result<u64, Error> {
let len = end.checked_sub(start).ok_or_else(|| {
Error::InvalidRequest(format!("end ({}) must be >= start ({})", end, start))
})?;
let len = len
.checked_add(1)
.ok_or_else(|| Error::InvalidRequest(format!("end ({}) must not be u64::MAX", end)))?;
Ok(len)
}
fn log_storage_response(storage_response: &Result<StorageServiceResponse, StorageServiceError>) {
match storage_response {
Ok(storage_response) => {
let response = format!("{}", storage_response);
if matches!(
storage_response,
StorageServiceResponse::StorageServerSummary(_)
) {
sample!(
SampleRate::Duration(Duration::from_secs(SUMMARY_LOG_FREQUENCY_SECS)),
{
debug!(LogSchema::new(LogEntry::SentStorageResponse).response(&response));
}
);
} else {
debug!(LogSchema::new(LogEntry::SentStorageResponse).response(&response));
}
}
Err(storage_error) => {
let storage_error = format!("{:?}", storage_error);
debug!(LogSchema::new(LogEntry::SentStorageResponse).response(&storage_error));
}
};
}