forked from casper-network/casper-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheffect.rs
More file actions
2366 lines (2205 loc) · 74.8 KB
/
effect.rs
File metadata and controls
2366 lines (2205 loc) · 74.8 KB
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Effects subsystem.
//!
//! Effects describe things that the creator of the effect intends to happen, producing a value upon
//! completion (they actually are boxed futures).
//!
//! A pinned, boxed future returning an event is called an effect and typed as an `Effect<Ev>`,
//! where `Ev` is the event's type, as every effect must have its return value either wrapped in an
//! event through [`EffectExt::event`](EffectExt::event) or ignored using
//! [`EffectExt::ignore`](EffectExt::ignore). As an example, the
//! [`handle_event`](crate::components::Component::handle_event) function of a component always
//! returns `Effect<Self::Event>`.
//!
//! # A primer on events
//!
//! There are three distinct groups of events found around the node:
//!
//! * (unbound) events: These events are not associated with a particular reactor or component and
//! represent information or requests by themselves. An example is the
//! [`PeerBehaviorAnnouncement`](`crate::effect::announcements::PeerBehaviorAnnouncement`), it can
//! be emitted through an effect by different components and contains the ID of a peer that should
//! be shunned. It is not associated with a particular reactor or component though.
//!
//! While the node is running, these unbound events cannot exist on their own, instead they are
//! typically converted into a concrete reactor event by the effect builder as soon as they are
//! created.
//!
//! * reactor events: A running reactor has a single event type that encompasses all possible
//! unbound events that can occur during its operation and all component events of components it
//! is made of. Usually they are implemented as one large `enum` with only newtype-variants.
//!
//! * component events: Every component defines its own set of events, typically for internal use.
//! If the component is able to process unbound events like announcements or requests, it will
//! have a `From` implementation that allows converting them into a suitable component event.
//!
//! Component events are also created from the return values of effects: While effects do not
//! return events themselves when called, their return values are turned first into component
//! events through the [`event`](EffectExt) method. In a second step, inside the
//! reactors routing code, `wrap_effect` will then convert from component to reactor event.
//!
//! # Using effects
//!
//! To create an effect, an `EffectBuilder` will be passed in by the calling reactor runner. For
//! example, given an effect builder `effect_builder`, we can create a `set_timeout` future and turn
//! it into an effect:
//!
//! ```ignore
//! use std::time::Duration;
//! use casper_node::effect::EffectExt;
//!
//! // Note: This is our "component" event.
//! enum Event {
//! ThreeSecondsElapsed(Duration)
//! }
//!
//! effect_builder
//! .set_timeout(Duration::from_secs(3))
//! .event(Event::ThreeSecondsElapsed);
//! ```
//!
//! This example will produce an effect that, after three seconds, creates an
//! `Event::ThreeSecondsElapsed`. Note that effects do nothing on their own, they need to be passed
//! to a [`reactor`](../reactor/index.html) to be executed.
//!
//! # Arbitrary effects
//!
//! While it is technically possible to turn any future into an effect, it is in general advisable
//! to only use the methods on [`EffectBuilder`] or short, anonymous futures to create effects.
//!
//! # Announcements and requests
//!
//! Events are usually classified into either announcements or requests, although these properties
//! are not reflected in the type system.
//!
//! **Announcements** are events that are essentially "fire-and-forget"; the component that created
//! the effect resulting in the creation of the announcement will never expect an "answer".
//! Announcements are often dispatched to multiple components by the reactor; since that usually
//! involves a [`clone`](`Clone::clone`), they should be kept light.
//!
//! A good example is the arrival of a new transaction passed in by a client. Depending on the setup
//! it may be stored, buffered or, in certain testing setups, just discarded. None of this is a
//! concern of the component that talks to the client and deserializes the incoming transaction
//! though, instead it simply returns an effect that produces an announcement.
//!
//! **Requests** are complex events that are used when a component needs something from other
//! components. Typically, an effect (which uses [`EffectBuilder::make_request`] in its
//! implementation) is called resulting in the actual request being scheduled and handled. In
//! contrast to announcements, requests must always be handled by exactly one component.
//!
//! Every request has a [`Responder`]-typed field, which a handler of a request calls to produce
//! another effect that will send the return value to the original requesting component. Failing to
//! call the [`Responder::respond`] function will result in a runtime warning.
pub(crate) mod announcements;
pub(crate) mod diagnostics_port;
pub(crate) mod incoming;
pub(crate) mod requests;
use std::{
any::type_name,
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt::{self, Debug, Display, Formatter},
future::Future,
mem,
sync::Arc,
time::{Duration, Instant},
};
use datasize::DataSize;
use futures::{channel::oneshot, future::BoxFuture, FutureExt};
use once_cell::sync::Lazy;
use serde::{Serialize, Serializer};
use smallvec::{smallvec, SmallVec};
use tokio::{sync::Semaphore, time};
use tracing::{debug, error, warn};
use casper_binary_port::{
ConsensusStatus, ConsensusValidatorChanges, LastProgress, NetworkName, RecordId, Uptime,
};
use casper_storage::{
block_store::types::ApprovalsHashes,
data_access_layer::{
prefixed_values::{PrefixedValuesRequest, PrefixedValuesResult},
tagged_values::{TaggedValuesRequest, TaggedValuesResult},
AddressableEntityResult, BalanceRequest, BalanceResult, EraValidatorsRequest,
EraValidatorsResult, ExecutionResultsChecksumResult, PutTrieRequest, PutTrieResult,
QueryRequest, QueryResult, SeigniorageRecipientsRequest, SeigniorageRecipientsResult,
TrieRequest, TrieResult,
},
DbRawBytesSpec,
};
use casper_types::{
execution::{Effects as ExecutionEffects, ExecutionResult},
Approval, AvailableBlockRange, Block, BlockHash, BlockHeader, BlockSignatures,
BlockSynchronizerStatus, BlockV2, ChainspecRawBytes, DeployHash, Digest, EntityAddr, EraId,
ExecutionInfo, FinalitySignature, FinalitySignatureId, FinalitySignatureV2, HashAddr, Key,
NextUpgrade, Package, PackageAddr, ProtocolUpgradeConfig, PublicKey, TimeDiff, Timestamp,
Transaction, TransactionHash, TransactionId, Transfer, U512,
};
use crate::{
components::{
block_synchronizer::{
GlobalStateSynchronizerError, GlobalStateSynchronizerResponse, TrieAccumulatorError,
TrieAccumulatorResponse,
},
consensus::{ClContext, EraDump, ProposedBlock},
contract_runtime::SpeculativeExecutionResult,
diagnostics_port::StopAtSpec,
fetcher::{FetchItem, FetchResult},
gossiper::GossipItem,
network::{blocklist::BlocklistJustification, FromIncoming, NetworkInsights},
transaction_acceptor,
},
contract_runtime::ExecutionPreState,
failpoints::FailpointActivation,
reactor::{main_reactor::ReactorState, EventQueueHandle, QueueKind},
types::{
appendable_block::AppendableBlock, BlockExecutionResultsOrChunk,
BlockExecutionResultsOrChunkId, BlockWithMetadata, ExecutableBlock, FinalizedBlock,
InvalidProposalError, LegacyDeploy, MetaBlock, MetaBlockState, NodeId, TransactionHeader,
},
utils::{fmt_limit::FmtLimit, SharedFlag, Source},
};
use announcements::{
BlockAccumulatorAnnouncement, ConsensusAnnouncement, ContractRuntimeAnnouncement,
ControlAnnouncement, FatalAnnouncement, FetchedNewBlockAnnouncement,
FetchedNewFinalitySignatureAnnouncement, GossiperAnnouncement, MetaBlockAnnouncement,
PeerBehaviorAnnouncement, QueueDumpFormat, TransactionAcceptorAnnouncement,
TransactionBufferAnnouncement, UnexecutedBlockAnnouncement, UpgradeWatcherAnnouncement,
};
use casper_storage::data_access_layer::EntryPointExistsResult;
use diagnostics_port::DumpConsensusStateRequest;
use requests::{
AcceptTransactionRequest, BeginGossipRequest, BlockAccumulatorRequest,
BlockSynchronizerRequest, BlockValidationRequest, ChainspecRawBytesRequest, ConsensusRequest,
ContractRuntimeRequest, FetcherRequest, MakeBlockExecutableRequest, MarkBlockCompletedRequest,
MetricsRequest, NetworkInfoRequest, NetworkRequest, ReactorInfoRequest, SetNodeStopRequest,
StorageRequest, SyncGlobalStateRequest, TransactionBufferRequest, TrieAccumulatorRequest,
UpgradeWatcherRequest,
};
/// A resource that will never be available, thus trying to acquire it will wait forever.
static UNOBTAINABLE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(0));
/// A pinned, boxed future that produces one or more events.
pub(crate) type Effect<Ev> = BoxFuture<'static, Multiple<Ev>>;
/// Multiple effects in a container.
pub(crate) type Effects<Ev> = Multiple<Effect<Ev>>;
/// A small collection of rarely more than two items.
///
/// Stored in a `SmallVec` to avoid allocations in case there are less than three items grouped. The
/// size of two items is chosen because one item is the most common use case, and large items are
/// typically boxed. In the latter case two pointers and one enum variant discriminator is almost
/// the same size as an empty vec, which is two pointers.
pub(crate) type Multiple<T> = SmallVec<[T; 2]>;
/// The type of peers that should receive the gossip message.
#[derive(Debug, Serialize, PartialEq, Eq, Hash, Copy, Clone, DataSize)]
pub(crate) enum GossipTarget {
/// Both validators and non validators.
Mixed(EraId),
/// All peers.
All,
}
impl Display for GossipTarget {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
GossipTarget::Mixed(era_id) => write!(formatter, "gossip target mixed for {}", era_id),
GossipTarget::All => write!(formatter, "gossip target all"),
}
}
}
/// A responder satisfying a request.
#[must_use]
#[derive(DataSize)]
pub(crate) struct Responder<T> {
/// Sender through which the response ultimately should be sent.
sender: Option<oneshot::Sender<T>>,
/// Reactor flag indicating shutdown.
is_shutting_down: SharedFlag,
}
/// A responder that will automatically send a `None` on drop.
#[must_use]
#[derive(DataSize, Debug)]
pub(crate) struct AutoClosingResponder<T>(Responder<Option<T>>);
impl<T> AutoClosingResponder<T> {
/// Creates a new auto closing responder from a responder of `Option<T>`.
pub(crate) fn from_opt_responder(responder: Responder<Option<T>>) -> Self {
AutoClosingResponder(responder)
}
/// Extracts the inner responder.
fn into_inner(mut self) -> Responder<Option<T>> {
let is_shutting_down = self.0.is_shutting_down;
mem::replace(
&mut self.0,
Responder {
sender: None,
is_shutting_down,
},
)
}
}
impl<T: Debug> AutoClosingResponder<T> {
/// Send `Some(data)` to the origin of the request.
pub(crate) async fn respond(self, data: T) {
self.into_inner().respond(Some(data)).await;
}
/// Send `None` to the origin of the request.
pub(crate) async fn respond_none(self) {
self.into_inner().respond(None).await;
}
}
impl<T> Drop for AutoClosingResponder<T> {
fn drop(&mut self) {
if let Some(sender) = self.0.sender.take() {
debug!(
sending_value = %self.0,
"responding None by dropping auto-close responder"
);
// We still haven't answered, send an answer.
if let Err(_unsent_value) = sender.send(None) {
debug!(
unsent_value = %self.0,
"failed to auto-close responder, ignoring"
);
}
}
}
}
impl<T: 'static + Send> Responder<T> {
/// Creates a new `Responder`.
#[inline]
fn new(sender: oneshot::Sender<T>, is_shutting_down: SharedFlag) -> Self {
Responder {
sender: Some(sender),
is_shutting_down,
}
}
/// Helper method for tests.
///
/// Allows creating a responder manually, without observing the shutdown flag. This function
/// should not be used, unless you are writing alternative infrastructure, e.g. for tests.
#[cfg(test)]
#[inline]
pub(crate) fn without_shutdown(sender: oneshot::Sender<T>) -> Self {
Responder::new(sender, SharedFlag::global_shared())
}
}
impl<T: Debug> Responder<T> {
/// Send `data` to the origin of the request.
pub(crate) async fn respond(mut self, data: T) {
if let Some(sender) = self.sender.take() {
if let Err(data) = sender.send(data) {
// If we cannot send a response down the channel, it means the original requester is
// no longer interested in our response. This typically happens during shutdowns, or
// in cases where an originating external request has been cancelled.
debug!(
data=?FmtLimit::new(1000, &data),
"ignored failure to send response to request down oneshot channel"
);
}
} else {
error!(
data=?FmtLimit::new(1000, &data),
"tried to send a value down a responder channel, but it was already used"
);
}
}
}
impl<T> Debug for Responder<T> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "Responder<{}>", type_name::<T>(),)
}
}
impl<T> Display for Responder<T> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(formatter, "responder({})", type_name::<T>(),)
}
}
impl<T> Drop for Responder<T> {
fn drop(&mut self) {
if self.sender.is_some() {
if self.is_shutting_down.is_set() {
debug!(
responder=?self,
"ignored dropping of responder during shutdown"
);
} else {
// This is usually a very serious error, as another component will now be stuck.
//
// See the code `make_request` for more details.
error!(
responder=?self,
"dropped without being responded to outside of shutdown"
);
}
}
}
}
impl<T> Serialize for Responder<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{:?}", self))
}
}
impl<T> Serialize for AutoClosingResponder<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
/// Effect extension for futures, used to convert futures into actual effects.
pub(crate) trait EffectExt: Future + Send {
/// Finalizes a future into an effect that returns a single event.
///
/// The function `f` is used to translate the returned value from an effect into an event.
fn event<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> U + 'static + Send,
U: 'static,
Self: Sized;
/// Finalizes a future into an effect that runs but drops the result.
fn ignore<Ev>(self) -> Effects<Ev>;
}
/// Effect extension for futures, used to convert futures returning a `Result` into two different
/// effects.
pub(crate) trait EffectResultExt {
/// The type the future will return if `Ok`.
type Value;
/// The type the future will return if `Err`.
type Error;
/// Finalizes a future returning a `Result` into two different effects.
///
/// The function `f_ok` is used to translate the returned value from an effect into an event,
/// while the function `f_err` does the same for a potential error.
fn result<U, F, G>(self, f_ok: F, f_err: G) -> Effects<U>
where
F: FnOnce(Self::Value) -> U + 'static + Send,
G: FnOnce(Self::Error) -> U + 'static + Send,
U: 'static;
}
impl<T> EffectExt for T
where
T: Future + Send + 'static + Sized,
{
fn event<U, F>(self, f: F) -> Effects<U>
where
F: FnOnce(Self::Output) -> U + 'static + Send,
U: 'static,
{
smallvec![self.map(f).map(|item| smallvec![item]).boxed()]
}
fn ignore<Ev>(self) -> Effects<Ev> {
smallvec![self.map(|_| Multiple::new()).boxed()]
}
}
impl<T, V, E> EffectResultExt for T
where
T: Future<Output = Result<V, E>> + Send + 'static + Sized,
{
type Value = V;
type Error = E;
fn result<U, F, G>(self, f_ok: F, f_err: G) -> Effects<U>
where
F: FnOnce(V) -> U + 'static + Send,
G: FnOnce(E) -> U + 'static + Send,
U: 'static,
{
smallvec![self
.map(|result| result.map_or_else(f_err, f_ok))
.map(|item| smallvec![item])
.boxed()]
}
}
/// A builder for [`Effect`](type.Effect.html)s.
///
/// Provides methods allowing the creation of effects which need to be scheduled on the reactor's
/// event queue, without giving direct access to this queue.
///
/// The `REv` type parameter indicates which reactor event effects created by this builder will
/// produce as side effects.
#[derive(Debug)]
pub(crate) struct EffectBuilder<REv: 'static> {
/// A handle to the referenced event queue.
event_queue: EventQueueHandle<REv>,
}
// Implement `Clone` and `Copy` manually, as `derive` will make it depend on `REv` otherwise.
impl<REv> Clone for EffectBuilder<REv> {
fn clone(&self) -> Self {
*self
}
}
impl<REv> Copy for EffectBuilder<REv> {}
impl<REv> EffectBuilder<REv> {
/// Creates a new effect builder.
pub(crate) fn new(event_queue: EventQueueHandle<REv>) -> Self {
EffectBuilder { event_queue }
}
/// Extract the event queue handle out of the effect builder.
pub(crate) fn into_inner(self) -> EventQueueHandle<REv> {
self.event_queue
}
/// Performs a request.
///
/// Given a request `Q`, that when completed will yield a result of `T`, produces a future that
/// will
///
/// 1. create an event to send the request to the respective component (thus `Q: Into<REv>`),
/// 2. wait for a response and return it.
///
/// This function is usually only used internally by effects implemented on the effects builder,
/// but IO components may also make use of it.
///
/// # Cancellation safety
///
/// This future is cancellation safe: If it is dropped without being polled, it indicates
/// that the original requester is no longer interested in the result, which will be discarded.
pub(crate) async fn make_request<T, Q, F>(self, f: F, queue_kind: QueueKind) -> T
where
T: Send + 'static,
Q: Into<REv>,
F: FnOnce(Responder<T>) -> Q,
{
let (event, wait_future) = self.create_request_parts(f);
// Schedule the request before awaiting the response.
self.event_queue.schedule(event, queue_kind).await;
wait_future.await
}
/// Creates the part necessary to make a request.
///
/// A request usually consists of two parts: The request event that needs to be scheduled on the
/// reactor queue and associated future that allows waiting for the response. This function
/// creates both of them without processing or spawning either.
///
/// Usually you will want to call the higher level `make_request` function.
pub(crate) fn create_request_parts<T, Q, F>(self, f: F) -> (REv, impl Future<Output = T>)
where
T: Send + 'static,
Q: Into<REv>,
F: FnOnce(Responder<T>) -> Q,
{
// Prepare a channel.
let (sender, receiver) = oneshot::channel();
// Create response function.
let responder = Responder::new(sender, self.event_queue.shutdown_flag());
// Now inject the request event into the event loop.
let request_event = f(responder).into();
let fut = async move {
match receiver.await {
Ok(value) => value,
Err(err) => {
// The channel should usually not be closed except during shutdowns, as it
// indicates a panic or disappearance of the remote that is
// supposed to process the request.
//
// If it does happen, we pretend nothing happened instead of crashing.
if self.event_queue.shutdown_flag().is_set() {
debug!(%err, channel=?type_name::<T>(), "ignoring closed channel due to shutdown");
} else {
error!(%err, channel=?type_name::<T>(), "request for channel closed, this may be a bug? \
check if a component is stuck from now on");
}
// We cannot produce any value to satisfy the request, so we just abandon this
// task by waiting on a resource we can never acquire.
let _ = UNOBTAINABLE.acquire().await;
panic!("should never obtain unobtainable semaphore");
}
}
};
(request_event, fut)
}
/// Run and end effect immediately.
///
/// Can be used to trigger events from effects when combined with `.event`. Do not use this to
/// "do nothing", as it will still cause a task to be spawned.
#[inline(always)]
#[allow(clippy::manual_async_fn)]
pub(crate) fn immediately(self) -> impl Future<Output = ()> + Send {
// Note: This function is implemented manually without `async` sugar because the `Send`
// inference seems to not work in all cases otherwise.
async {}
}
/// Reports a fatal error. Normally called via the `crate::fatal!()` macro.
///
/// Usually causes the node to cease operations quickly and exit/crash.
pub(crate) async fn fatal(self, file: &'static str, line: u32, msg: String)
where
REv: From<FatalAnnouncement>,
{
self.event_queue
.schedule(FatalAnnouncement { file, line, msg }, QueueKind::Control)
.await;
}
/// Sets a timeout.
pub(crate) async fn set_timeout(self, timeout: Duration) -> Duration {
let then = Instant::now();
time::sleep(timeout).await;
then.elapsed()
}
/// Retrieve a snapshot of the nodes current metrics formatted as string.
///
/// If an error occurred producing the metrics, `None` is returned.
pub(crate) async fn get_metrics(self) -> Option<String>
where
REv: From<MetricsRequest>,
{
self.make_request(
|responder| MetricsRequest::RenderNodeMetricsText { responder },
QueueKind::Api,
)
.await
}
/// Sends a network message.
///
/// The message is queued and sent, but no delivery guaranteed. Will return after the message
/// has been buffered in the outgoing kernel buffer and thus is subject to backpressure.
pub(crate) async fn send_message<P>(self, dest: NodeId, payload: P)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| NetworkRequest::SendMessage {
dest: Box::new(dest),
payload: Box::new(payload),
respond_after_queueing: false,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await;
}
/// Enqueues a network message.
///
/// The message is queued in "fire-and-forget" fashion, there is no guarantee that the peer
/// will receive it. Returns as soon as the message is queued inside the networking component.
pub(crate) async fn enqueue_message<P>(self, dest: NodeId, payload: P)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| NetworkRequest::SendMessage {
dest: Box::new(dest),
payload: Box::new(payload),
respond_after_queueing: true,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await;
}
/// Broadcasts a network message to validator peers in the given era.
pub(crate) async fn broadcast_message_to_validators<P>(self, payload: P, era_id: EraId)
where
REv: From<NetworkRequest<P>>,
{
self.make_request(
|responder| {
debug!("validator broadcast for {}", era_id);
NetworkRequest::ValidatorBroadcast {
payload: Box::new(payload),
era_id,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
}
},
QueueKind::Network,
)
.await;
}
/// Gossips a network message.
///
/// A low-level "gossip" function, selects `count` randomly chosen nodes on the network,
/// excluding the indicated ones, and sends each a copy of the message.
///
/// Returns the IDs of the chosen nodes.
pub(crate) async fn gossip_message<P>(
self,
payload: P,
gossip_target: GossipTarget,
count: usize,
exclude: HashSet<NodeId>,
) -> HashSet<NodeId>
where
REv: From<NetworkRequest<P>>,
P: Send,
{
self.make_request(
|responder| NetworkRequest::Gossip {
payload: Box::new(payload),
gossip_target,
count,
exclude,
auto_closing_responder: AutoClosingResponder::from_opt_responder(responder),
},
QueueKind::Network,
)
.await
.unwrap_or_default()
}
/// Gets a structure describing the current network status.
pub(crate) async fn get_network_insights(self) -> NetworkInsights
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::Insight { responder },
QueueKind::Regular,
)
.await
}
/// Gets a map of the current network peers to their socket addresses.
pub(crate) async fn network_peers(self) -> BTreeMap<NodeId, String>
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::Peers { responder },
QueueKind::Api,
)
.await
}
/// Gets up to `count` fully-connected network peers in random order.
pub async fn get_fully_connected_peers(self, count: usize) -> Vec<NodeId>
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::FullyConnectedPeers { count, responder },
QueueKind::NetworkInfo,
)
.await
}
/// Gets up to `count` fully-connected network validators in random order.
pub async fn get_fully_connected_validators(self, count: usize, era_id: EraId) -> Vec<NodeId>
where
REv: From<NetworkInfoRequest>,
{
self.make_request(
|responder| NetworkInfoRequest::FullyConnectedValidators {
count,
era_id,
responder,
},
QueueKind::NetworkInfo,
)
.await
}
/// Announces which transactions have expired.
pub(crate) async fn announce_expired_transactions(self, hashes: Vec<TransactionHash>)
where
REv: From<TransactionBufferAnnouncement>,
{
self.event_queue
.schedule(
TransactionBufferAnnouncement::TransactionsExpired(hashes),
QueueKind::Validation,
)
.await;
}
/// Announces an incoming network message.
pub(crate) async fn announce_incoming<P>(self, sender: NodeId, payload: P)
where
REv: FromIncoming<P>,
{
self.event_queue
.schedule(
<REv as FromIncoming<P>>::from_incoming(sender, payload),
QueueKind::NetworkIncoming,
)
.await;
}
/// Announces that a gossiper has received a new item, where the item's ID is the complete item.
pub(crate) async fn announce_complete_item_received_via_gossip<T: GossipItem>(self, item: T::Id)
where
REv: From<GossiperAnnouncement<T>>,
{
assert!(
T::ID_IS_COMPLETE_ITEM,
"{} must be an item where the ID _is_ the complete item",
item
);
self.event_queue
.schedule(
GossiperAnnouncement::NewCompleteItem(item),
QueueKind::Gossip,
)
.await;
}
/// Announces that a gossiper has received a full item, where the item's ID is NOT the complete
/// item.
pub(crate) async fn announce_item_body_received_via_gossip<T: GossipItem>(
self,
item: Box<T>,
sender: NodeId,
) where
REv: From<GossiperAnnouncement<T>>,
{
self.event_queue
.schedule(
GossiperAnnouncement::NewItemBody { item, sender },
QueueKind::Gossip,
)
.await;
}
/// Announces that the block accumulator has received and stored a new finality signature.
pub(crate) async fn announce_finality_signature_accepted(
self,
finality_signature: Box<FinalitySignatureV2>,
) where
REv: From<BlockAccumulatorAnnouncement>,
{
self.event_queue
.schedule(
BlockAccumulatorAnnouncement::AcceptedNewFinalitySignature { finality_signature },
QueueKind::FinalitySignature,
)
.await;
}
/// Request that a block be made executable, if able to: `ExecutableBlock`.
///
/// Completion means that the block can be enqueued for processing by the execution engine via
/// the contract_runtime component.
pub(crate) async fn make_block_executable(
self,
block_hash: BlockHash,
) -> Option<ExecutableBlock>
where
REv: From<MakeBlockExecutableRequest>,
{
self.make_request(
|responder| MakeBlockExecutableRequest {
block_hash,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Request that a block with a specific height be marked completed.
///
/// Completion means that the block itself (along with its header) and all of its transactions
/// have been persisted to storage and its global state root hash is missing no dependencies
/// in the global state.
pub(crate) async fn mark_block_completed(self, block_height: u64) -> bool
where
REv: From<MarkBlockCompletedRequest>,
{
self.make_request(
|responder| MarkBlockCompletedRequest {
block_height,
responder,
},
QueueKind::FromStorage,
)
.await
}
/// Try to accept a transaction received from the JSON-RPC server.
pub(crate) async fn try_accept_transaction(
self,
transaction: Transaction,
is_speculative: bool,
) -> Result<(), transaction_acceptor::Error>
where
REv: From<AcceptTransactionRequest>,
{
self.make_request(
|responder| AcceptTransactionRequest {
transaction,
is_speculative,
responder,
},
QueueKind::Api,
)
.await
}
/// Announces that a transaction not previously stored has now been accepted and stored.
pub(crate) fn announce_new_transaction_accepted(
self,
transaction: Arc<Transaction>,
source: Source,
) -> impl Future<Output = ()>
where
REv: From<TransactionAcceptorAnnouncement>,
{
self.event_queue.schedule(
TransactionAcceptorAnnouncement::AcceptedNewTransaction {
transaction,
source,
},
QueueKind::Validation,
)
}
/// Announces that we have received a gossip message from this peer,
/// implying the peer holds the indicated item.
pub(crate) async fn announce_gossip_received<T>(self, item_id: T::Id, sender: NodeId)
where
REv: From<GossiperAnnouncement<T>>,
T: GossipItem,
{
self.event_queue
.schedule(
GossiperAnnouncement::GossipReceived { item_id, sender },
QueueKind::Gossip,
)
.await;
}
/// Announces that we have finished gossiping the indicated item.
pub(crate) async fn announce_finished_gossiping<T>(self, item_id: T::Id)
where
REv: From<GossiperAnnouncement<T>>,
T: GossipItem,
{
self.event_queue
.schedule(
GossiperAnnouncement::FinishedGossiping(item_id),
QueueKind::Gossip,
)
.await;
}
pub(crate) fn announce_invalid_transaction(
self,
transaction: Transaction,
source: Source,
) -> impl Future<Output = ()>
where
REv: From<TransactionAcceptorAnnouncement>,
{
self.event_queue.schedule(
TransactionAcceptorAnnouncement::InvalidTransaction {
transaction,
source,
},
QueueKind::Validation,
)
}
/// Announces upgrade activation point read.
pub(crate) async fn upgrade_watcher_announcement(self, maybe_next_upgrade: Option<NextUpgrade>)
where
REv: From<UpgradeWatcherAnnouncement>,
{
self.event_queue
.schedule(
UpgradeWatcherAnnouncement(maybe_next_upgrade),
QueueKind::Control,
)
.await;
}
/// Announces a committed Step success.
pub(crate) async fn announce_commit_step_success(self, era_id: EraId, effects: ExecutionEffects)
where
REv: From<ContractRuntimeAnnouncement>,
{
self.event_queue
.schedule(
ContractRuntimeAnnouncement::CommitStepSuccess { era_id, effects },
QueueKind::ContractRuntime,
)
.await;
}
pub(crate) async fn update_contract_runtime_state(self, new_pre_state: ExecutionPreState)
where
REv: From<ContractRuntimeRequest>,
{
self.event_queue
.schedule(
ContractRuntimeRequest::UpdatePreState { new_pre_state },
QueueKind::ContractRuntime,
)
.await;
}
/// Announces validators for upcoming era.
pub(crate) async fn announce_upcoming_era_validators(
self,
era_that_is_ending: EraId,
upcoming_era_validators: BTreeMap<EraId, BTreeMap<PublicKey, U512>>,
) where
REv: From<ContractRuntimeAnnouncement>,
{
self.event_queue
.schedule(
ContractRuntimeAnnouncement::UpcomingEraValidators {
era_that_is_ending,
upcoming_era_validators,
},
QueueKind::ContractRuntime,
)
.await;
}
pub(crate) async fn announce_new_era_gas_price(self, era_id: EraId, next_era_gas_price: u8)
where
REv: From<ContractRuntimeAnnouncement>,
{
self.event_queue