-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathdeterministic.rs
More file actions
2385 lines (2104 loc) · 76 KB
/
deterministic.rs
File metadata and controls
2385 lines (2104 loc) · 76 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
//! A deterministic runtime that randomly selects tasks to run based on a seed
//!
//! # Panics
//!
//! Unless configured otherwise, any task panic will lead to a runtime panic.
//!
//! # External Processes
//!
//! When testing an application that interacts with some external process, it can appear to
//! the runtime that progress has stalled because no pending tasks can make progress and/or
//! that futures resolve at variable latency (which in turn triggers non-deterministic execution).
//!
//! To support such applications, the runtime can be built with the `external` feature to both
//! sleep for each [Config::cycle] (opting to wait if all futures are pending) and to constrain
//! the resolution latency of any future (with `pace()`).
//!
//! **Applications that do not interact with external processes (or are able to mock them) should never
//! need to enable this feature. It is commonly used when testing consensus with external execution environments
//! that use their own runtime (but are deterministic over some set of inputs).**
//!
//! # Metrics
//!
//! This runtime enforces metrics are unique and well-formed:
//! - Labels must start with `[a-zA-Z]` and contain only `[a-zA-Z0-9_]`
//! - Metric names must be unique (panics on duplicate registration)
//!
//! # Example
//!
//! ```rust
//! use commonware_runtime::{Spawner, Runner, deterministic, Metrics};
//!
//! let executor = deterministic::Runner::default();
//! executor.start(|context| async move {
//! println!("Parent started");
//! let result = context.with_label("child").spawn(|_| async move {
//! println!("Child started");
//! "hello"
//! });
//! println!("Child result: {:?}", result.await);
//! println!("Parent exited");
//! println!("Auditor state: {}", context.auditor().state());
//! });
//! ```
pub use crate::storage::faulty::Config as FaultConfig;
use crate::{
network::{
audited::Network as AuditedNetwork, deterministic::Network as DeterministicNetwork,
metered::Network as MeteredNetwork,
},
storage::{
audited::Storage as AuditedStorage, faulty::Storage as FaultyStorage,
memory::Storage as MemStorage, metered::Storage as MeteredStorage,
},
telemetry::metrics::task::Label,
utils::{
add_attribute,
signal::{Signal, Stopper},
supervision::Tree,
Panicker, Registry, ScopeGuard,
},
validate_label, BufferPool, BufferPoolConfig, Clock, Error, Execution, Handle, ListenerOf,
Metrics as _, Panicked, Spawner as _, METRICS_PREFIX,
};
#[cfg(feature = "external")]
use crate::{Blocker, Pacer};
use commonware_codec::Encode;
use commonware_macros::select;
use commonware_parallel::ThreadPool;
use commonware_utils::{
hex,
sync::{Mutex, RwLock},
time::SYSTEM_TIME_PRECISION,
SystemTimeExt,
};
#[cfg(feature = "external")]
use futures::task::noop_waker;
use futures::{
future::Either,
task::{waker, ArcWake},
Future,
};
use governor::clock::{Clock as GClock, ReasonablyRealtime};
#[cfg(feature = "external")]
use pin_project::pin_project;
use prometheus_client::{
metrics::{counter::Counter, family::Family, gauge::Gauge},
registry::{Metric, Registry as PrometheusRegistry},
};
use rand::{prelude::SliceRandom, rngs::StdRng, CryptoRng, RngCore, SeedableRng};
use rand_core::CryptoRngCore;
use rayon::{ThreadPoolBuildError, ThreadPoolBuilder};
use sha2::{Digest as _, Sha256};
use std::{
borrow::Cow,
collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
mem::{replace, take},
net::{IpAddr, SocketAddr},
num::NonZeroUsize,
panic::{catch_unwind, resume_unwind, AssertUnwindSafe},
pin::Pin,
sync::{Arc, Weak},
task::{self, Poll, Waker},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tracing::{info_span, trace, Instrument};
use tracing_opentelemetry::OpenTelemetrySpanExt;
#[derive(Debug)]
struct Metrics {
iterations: Counter,
tasks_spawned: Family<Label, Counter>,
tasks_running: Family<Label, Gauge>,
task_polls: Family<Label, Counter>,
network_bandwidth: Counter,
}
impl Metrics {
pub fn init(registry: &mut PrometheusRegistry) -> Self {
let metrics = Self {
iterations: Counter::default(),
task_polls: Family::default(),
tasks_spawned: Family::default(),
tasks_running: Family::default(),
network_bandwidth: Counter::default(),
};
registry.register(
"iterations",
"Total number of iterations",
metrics.iterations.clone(),
);
registry.register(
"tasks_spawned",
"Total number of tasks spawned",
metrics.tasks_spawned.clone(),
);
registry.register(
"tasks_running",
"Number of tasks currently running",
metrics.tasks_running.clone(),
);
registry.register(
"task_polls",
"Total number of task polls",
metrics.task_polls.clone(),
);
registry.register(
"bandwidth",
"Total amount of data sent over network",
metrics.network_bandwidth.clone(),
);
metrics
}
}
/// A SHA-256 digest.
type Digest = [u8; 32];
/// Track the state of the runtime for determinism auditing.
pub struct Auditor {
digest: Mutex<Digest>,
}
impl Default for Auditor {
fn default() -> Self {
Self {
digest: Digest::default().into(),
}
}
}
impl Auditor {
/// Record that an event happened.
/// This auditor's hash will be updated with the event's `label` and
/// whatever other data is passed in the `payload` closure.
pub(crate) fn event<F>(&self, label: &'static [u8], payload: F)
where
F: FnOnce(&mut Sha256),
{
let mut digest = self.digest.lock();
let mut hasher = Sha256::new();
hasher.update(digest.as_ref());
hasher.update(label);
payload(&mut hasher);
*digest = hasher.finalize().into();
}
/// Generate a representation of the current state of the runtime.
///
/// This can be used to ensure that logic running on top
/// of the runtime is interacting deterministically.
pub fn state(&self) -> String {
let hash = self.digest.lock();
hex(hash.as_ref())
}
}
/// A dynamic RNG that can safely be sent between threads.
pub type BoxDynRng = Box<dyn CryptoRngCore + Send + 'static>;
/// Configuration for the `deterministic` runtime.
pub struct Config {
/// Random number generator.
rng: BoxDynRng,
/// The cycle duration determines how much time is advanced after each iteration of the event
/// loop. This is useful to prevent starvation if some task never yields.
cycle: Duration,
/// Time the runtime starts at.
start_time: SystemTime,
/// If the runtime is still executing at this point (i.e. a test hasn't stopped), panic.
timeout: Option<Duration>,
/// Whether spawned tasks should catch panics instead of propagating them.
catch_panics: bool,
/// Configuration for deterministic storage fault injection.
/// Defaults to no faults being injected.
storage_fault_cfg: FaultConfig,
/// Buffer pool configuration for network I/O.
network_buffer_pool_cfg: BufferPoolConfig,
/// Buffer pool configuration for storage I/O.
storage_buffer_pool_cfg: BufferPoolConfig,
}
impl Config {
/// Returns a new [Config] with default values.
pub fn new() -> Self {
cfg_if::cfg_if! {
if #[cfg(miri)] {
// Reduce max_per_class to avoid slow atomics under Miri
let network_buffer_pool_cfg = BufferPoolConfig::for_network()
.with_max_per_class(commonware_utils::NZUsize!(32))
.with_thread_cache_disabled();
let storage_buffer_pool_cfg = BufferPoolConfig::for_storage()
.with_max_per_class(commonware_utils::NZUsize!(32))
.with_thread_cache_disabled();
} else {
let network_buffer_pool_cfg =
BufferPoolConfig::for_network().with_thread_cache_disabled();
let storage_buffer_pool_cfg =
BufferPoolConfig::for_storage().with_thread_cache_disabled();
}
}
Self {
rng: Box::new(StdRng::seed_from_u64(42)),
cycle: Duration::from_millis(1),
start_time: UNIX_EPOCH,
timeout: None,
catch_panics: false,
storage_fault_cfg: FaultConfig::default(),
network_buffer_pool_cfg,
storage_buffer_pool_cfg,
}
}
// Setters
/// See [Config]
pub fn with_seed(self, seed: u64) -> Self {
self.with_rng(Box::new(StdRng::seed_from_u64(seed)))
}
/// Provide the config with a dynamic RNG directly.
///
/// This can be useful for, e.g. fuzzing, where beyond just having randomness,
/// you might want to control specific bytes of the RNG. By taking in a dynamic
/// RNG object, any behavior is possible.
pub fn with_rng(mut self, rng: BoxDynRng) -> Self {
self.rng = rng;
self
}
/// See [Config]
pub const fn with_cycle(mut self, cycle: Duration) -> Self {
self.cycle = cycle;
self
}
/// See [Config]
pub const fn with_start_time(mut self, start_time: SystemTime) -> Self {
self.start_time = start_time;
self
}
/// See [Config]
pub const fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
self.timeout = timeout;
self
}
/// See [Config]
pub const fn with_catch_panics(mut self, catch_panics: bool) -> Self {
self.catch_panics = catch_panics;
self
}
/// See [Config]
pub const fn with_network_buffer_pool_config(mut self, cfg: BufferPoolConfig) -> Self {
self.network_buffer_pool_cfg = cfg;
self
}
/// See [Config]
pub const fn with_storage_buffer_pool_config(mut self, cfg: BufferPoolConfig) -> Self {
self.storage_buffer_pool_cfg = cfg;
self
}
/// Configure storage fault injection.
///
/// When set, the runtime will inject deterministic storage errors based on
/// the provided configuration. Faults are drawn from the shared RNG, ensuring
/// reproducible failure patterns for a given seed.
pub const fn with_storage_fault_config(mut self, faults: FaultConfig) -> Self {
self.storage_fault_cfg = faults;
self
}
// Getters
/// See [Config]
pub const fn cycle(&self) -> Duration {
self.cycle
}
/// See [Config]
pub const fn start_time(&self) -> SystemTime {
self.start_time
}
/// See [Config]
pub const fn timeout(&self) -> Option<Duration> {
self.timeout
}
/// See [Config]
pub const fn catch_panics(&self) -> bool {
self.catch_panics
}
/// See [Config]
pub const fn network_buffer_pool_config(&self) -> &BufferPoolConfig {
&self.network_buffer_pool_cfg
}
/// See [Config]
pub const fn storage_buffer_pool_config(&self) -> &BufferPoolConfig {
&self.storage_buffer_pool_cfg
}
/// Assert that the configuration is valid.
pub fn assert(&self) {
assert!(
self.cycle != Duration::default() || self.timeout.is_none(),
"cycle duration must be non-zero when timeout is set",
);
assert!(
self.cycle >= SYSTEM_TIME_PRECISION,
"cycle duration must be greater than or equal to system time precision"
);
assert!(
self.start_time >= UNIX_EPOCH,
"start time must be greater than or equal to unix epoch"
);
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
/// A (prefixed_name, attributes) pair identifying a unique metric registration.
type MetricKey = (String, Vec<(String, String)>);
/// Deterministic runtime that randomly selects tasks to run based on a seed.
pub struct Executor {
registry: Mutex<Registry>,
registered_metrics: Mutex<HashSet<MetricKey>>,
cycle: Duration,
deadline: Option<SystemTime>,
metrics: Arc<Metrics>,
auditor: Arc<Auditor>,
rng: Arc<Mutex<BoxDynRng>>,
time: Mutex<SystemTime>,
tasks: Arc<Tasks>,
sleeping: Mutex<BinaryHeap<Alarm>>,
shutdown: Mutex<Stopper>,
panicker: Panicker,
dns: Mutex<HashMap<String, Vec<IpAddr>>>,
}
impl Executor {
/// Advance simulated time by [Config::cycle].
///
/// When built with the `external` feature, sleep for [Config::cycle] to let
/// external processes make progress.
fn advance_time(&self) -> SystemTime {
#[cfg(feature = "external")]
std::thread::sleep(self.cycle);
let mut time = self.time.lock();
*time = time
.checked_add(self.cycle)
.expect("executor time overflowed");
let now = *time;
trace!(now = now.epoch_millis(), "time advanced");
now
}
/// When idle, jump directly to the next actionable time.
///
/// When built with the `external` feature, never skip ahead (to ensure we poll all pending tasks
/// every [Config::cycle]).
fn skip_idle_time(&self, current: SystemTime) -> SystemTime {
if cfg!(feature = "external") || self.tasks.ready() != 0 {
return current;
}
let mut skip_until = None;
{
let sleeping = self.sleeping.lock();
if let Some(next) = sleeping.peek() {
if next.time > current {
skip_until = Some(next.time);
}
}
}
skip_until.map_or(current, |deadline| {
let mut time = self.time.lock();
*time = deadline;
let now = *time;
trace!(now = now.epoch_millis(), "time skipped");
now
})
}
/// Wake any sleepers whose deadlines have elapsed.
fn wake_ready_sleepers(&self, current: SystemTime) {
let mut sleeping = self.sleeping.lock();
while let Some(next) = sleeping.peek() {
if next.time <= current {
let sleeper = sleeping.pop().unwrap();
sleeper.waker.wake();
} else {
break;
}
}
}
/// Ensure the runtime is making progress.
///
/// When built with the `external` feature, always poll pending tasks after the passage of time.
fn assert_liveness(&self) {
if cfg!(feature = "external") || self.tasks.ready() != 0 {
return;
}
panic!("runtime stalled");
}
}
/// An artifact that can be used to recover the state of the runtime.
///
/// This is useful when mocking unclean shutdown (while retaining deterministic behavior).
pub struct Checkpoint {
cycle: Duration,
deadline: Option<SystemTime>,
auditor: Arc<Auditor>,
rng: Arc<Mutex<BoxDynRng>>,
time: Mutex<SystemTime>,
storage: Arc<Storage>,
dns: Mutex<HashMap<String, Vec<IpAddr>>>,
catch_panics: bool,
network_buffer_pool_cfg: BufferPoolConfig,
storage_buffer_pool_cfg: BufferPoolConfig,
}
impl Checkpoint {
/// Get a reference to the [Auditor].
pub fn auditor(&self) -> Arc<Auditor> {
self.auditor.clone()
}
}
#[allow(clippy::large_enum_variant)]
enum State {
Config(Config),
Checkpoint(Checkpoint),
}
/// Implementation of [crate::Runner] for the `deterministic` runtime.
pub struct Runner {
state: State,
}
impl From<Config> for Runner {
fn from(cfg: Config) -> Self {
Self::new(cfg)
}
}
impl From<Checkpoint> for Runner {
fn from(checkpoint: Checkpoint) -> Self {
Self {
state: State::Checkpoint(checkpoint),
}
}
}
impl Runner {
/// Initialize a new `deterministic` runtime with the given seed and cycle duration.
pub fn new(cfg: Config) -> Self {
// Ensure config is valid
cfg.assert();
Self {
state: State::Config(cfg),
}
}
/// Initialize a new `deterministic` runtime with the default configuration
/// and the provided seed.
pub fn seeded(seed: u64) -> Self {
Self::new(Config::default().with_seed(seed))
}
/// Initialize a new `deterministic` runtime with the default configuration
/// but exit after the given timeout.
pub fn timed(timeout: Duration) -> Self {
let cfg = Config {
timeout: Some(timeout),
..Config::default()
};
Self::new(cfg)
}
/// Like [crate::Runner::start], but also returns a [Checkpoint] that can be used
/// to recover the state of the runtime in a subsequent run.
pub fn start_and_recover<F, Fut>(self, f: F) -> (Fut::Output, Checkpoint)
where
F: FnOnce(Context) -> Fut,
Fut: Future,
{
// Setup context and return strong reference to executor
let (context, executor, panicked) = match self.state {
State::Config(config) => Context::new(config),
State::Checkpoint(checkpoint) => Context::recover(checkpoint),
};
// Pin root task to the heap
let storage = context.storage.clone();
let network_buffer_pool_cfg = context.network_buffer_pool.config().clone();
let storage_buffer_pool_cfg = context.storage_buffer_pool.config().clone();
let mut root = Box::pin(panicked.interrupt(f(context)));
// Register the root task
Tasks::register_root(&executor.tasks);
// Process tasks until root task completes or progress stalls.
// Wrap the loop in catch_unwind to ensure task cleanup runs even if the loop or a task panics.
let result = catch_unwind(AssertUnwindSafe(|| loop {
// Ensure we have not exceeded our deadline
{
let current = executor.time.lock();
if let Some(deadline) = executor.deadline {
if *current >= deadline {
drop(current);
panic!("runtime timeout");
}
}
}
// Drain all ready tasks
let mut queue = executor.tasks.drain();
// Shuffle tasks (if more than one)
if queue.len() > 1 {
let mut rng = executor.rng.lock();
queue.shuffle(&mut *rng);
}
// Run all snapshotted tasks
//
// This approach is more efficient than randomly selecting a task one-at-a-time
// because it ensures we don't pull the same pending task multiple times in a row (without
// processing a different task required for other tasks to make progress).
trace!(
iter = executor.metrics.iterations.get(),
tasks = queue.len(),
"starting loop"
);
let mut output = None;
for id in queue {
// Lookup the task (it may have completed already)
let Some(task) = executor.tasks.get(id) else {
trace!(id, "skipping missing task");
continue;
};
// Record task for auditing
executor.auditor.event(b"process_task", |hasher| {
hasher.update(task.id.to_be_bytes());
hasher.update(task.label.name().as_bytes());
});
executor.metrics.task_polls.get_or_create(&task.label).inc();
trace!(id, "processing task");
// Prepare task for polling
let waker = waker(Arc::new(TaskWaker {
id,
tasks: Arc::downgrade(&executor.tasks),
}));
let mut cx = task::Context::from_waker(&waker);
// Poll the task
match &task.mode {
Mode::Root => {
// Poll the root task
if let Poll::Ready(result) = root.as_mut().poll(&mut cx) {
trace!(id, "root task is complete");
output = Some(result);
break;
}
}
Mode::Work(future) => {
// Get the future (if it still exists)
let mut fut_opt = future.lock();
let Some(fut) = fut_opt.as_mut() else {
trace!(id, "skipping already complete task");
// Remove the future
executor.tasks.remove(id);
continue;
};
// Poll the task
if fut.as_mut().poll(&mut cx).is_ready() {
trace!(id, "task is complete");
// Remove the future
executor.tasks.remove(id);
*fut_opt = None;
continue;
}
}
}
// Try again later if task is still pending
trace!(id, "task is still pending");
}
// If the root task has completed, exit as soon as possible
if let Some(output) = output {
break output;
}
// Advance time (skipping ahead if no tasks are ready yet)
let mut current = executor.advance_time();
current = executor.skip_idle_time(current);
// Wake sleepers and ensure we continue to make progress
executor.wake_ready_sleepers(current);
executor.assert_liveness();
// Record that we completed another iteration of the event loop.
executor.metrics.iterations.inc();
}));
// Clear remaining tasks from the executor.
//
// It is critical that we wait to drop the strong
// reference to executor until after we have dropped
// all tasks (as they may attempt to upgrade their weak
// reference to the executor during drop).
executor.sleeping.lock().clear(); // included in tasks
let tasks = executor.tasks.clear();
for task in tasks {
let Mode::Work(future) = &task.mode else {
continue;
};
*future.lock() = None;
}
// Drop the root task to release any Context references it may still hold.
// This is necessary when the loop exits early (e.g., timeout) while the
// root future is still Pending and holds captured variables with Context references.
drop(root);
// Assert the context doesn't escape the start() function (behavior
// is undefined in this case)
assert!(
Arc::weak_count(&executor) == 0,
"executor still has weak references"
);
// Handle the result — resume the original panic after cleanup if one was caught.
let output = match result {
Ok(output) => output,
Err(payload) => resume_unwind(payload),
};
// Extract the executor from the Arc
let executor = Arc::into_inner(executor).expect("executor still has strong references");
// Construct a checkpoint that can be used to restart the runtime
let checkpoint = Checkpoint {
cycle: executor.cycle,
deadline: executor.deadline,
auditor: executor.auditor,
rng: executor.rng,
time: executor.time,
storage,
dns: executor.dns,
catch_panics: executor.panicker.catch(),
network_buffer_pool_cfg,
storage_buffer_pool_cfg,
};
(output, checkpoint)
}
}
impl Default for Runner {
fn default() -> Self {
Self::new(Config::default())
}
}
impl crate::Runner for Runner {
type Context = Context;
fn start<F, Fut>(self, f: F) -> Fut::Output
where
F: FnOnce(Self::Context) -> Fut,
Fut: Future,
{
let (output, _) = self.start_and_recover(f);
output
}
}
/// The mode of a [Task].
enum Mode {
Root,
Work(Mutex<Option<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>),
}
/// A future being executed by the [Executor].
struct Task {
id: u128,
label: Label,
mode: Mode,
}
/// A waker for a [Task].
struct TaskWaker {
id: u128,
tasks: Weak<Tasks>,
}
impl ArcWake for TaskWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
// Upgrade the weak reference to re-enqueue this task.
// If upgrade fails, the task queue has been dropped and no action is required.
//
// This can happen if some data is passed into the runtime and it drops after the runtime exits.
if let Some(tasks) = arc_self.tasks.upgrade() {
tasks.queue(arc_self.id);
}
}
}
/// A collection of [Task]s that are being executed by the [Executor].
struct Tasks {
/// The next task id.
counter: Mutex<u128>,
/// Tasks ready to be polled.
ready: Mutex<Vec<u128>>,
/// All running tasks.
running: Mutex<BTreeMap<u128, Arc<Task>>>,
}
impl Tasks {
/// Create a new task queue.
const fn new() -> Self {
Self {
counter: Mutex::new(0),
ready: Mutex::new(Vec::new()),
running: Mutex::new(BTreeMap::new()),
}
}
/// Increment the task counter and return the old value.
fn increment(&self) -> u128 {
let mut counter = self.counter.lock();
let old = *counter;
*counter = counter.checked_add(1).expect("task counter overflow");
old
}
/// Register the root task.
///
/// If the root task has already been registered, this function will panic.
fn register_root(arc_self: &Arc<Self>) {
let id = arc_self.increment();
let task = Arc::new(Task {
id,
label: Label::root(),
mode: Mode::Root,
});
arc_self.register(id, task);
}
/// Register a non-root task to be executed.
fn register_work(
arc_self: &Arc<Self>,
label: Label,
future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
) {
let id = arc_self.increment();
let task = Arc::new(Task {
id,
label,
mode: Mode::Work(Mutex::new(Some(future))),
});
arc_self.register(id, task);
}
/// Register a new task to be executed.
fn register(&self, id: u128, task: Arc<Task>) {
// Track as running until completion
self.running.lock().insert(id, task);
// Add to ready
self.queue(id);
}
/// Enqueue an already registered task to be executed.
fn queue(&self, id: u128) {
let mut ready = self.ready.lock();
ready.push(id);
}
/// Drain all ready tasks.
fn drain(&self) -> Vec<u128> {
let mut queue = self.ready.lock();
let len = queue.len();
replace(&mut *queue, Vec::with_capacity(len))
}
/// The number of ready tasks.
fn ready(&self) -> usize {
self.ready.lock().len()
}
/// Lookup a task.
///
/// We must return cloned here because we cannot hold the running lock while polling a task (will
/// deadlock if [Self::register_work] is called).
fn get(&self, id: u128) -> Option<Arc<Task>> {
let running = self.running.lock();
running.get(&id).cloned()
}
/// Remove a task.
fn remove(&self, id: u128) {
self.running.lock().remove(&id);
}
/// Clear all tasks.
fn clear(&self) -> Vec<Arc<Task>> {
// Clear ready
self.ready.lock().clear();
// Clear running tasks
let running: BTreeMap<u128, Arc<Task>> = {
let mut running = self.running.lock();
take(&mut *running)
};
running.into_values().collect()
}
}
type Network = MeteredNetwork<AuditedNetwork<DeterministicNetwork>>;
type Storage = MeteredStorage<AuditedStorage<FaultyStorage<MemStorage>>>;
/// Implementation of [crate::Spawner], [crate::Clock],
/// [crate::Network], and [crate::Storage] for the `deterministic`
/// runtime.
pub struct Context {
name: String,
attributes: Vec<(String, String)>,
scope: Option<Arc<ScopeGuard>>,
executor: Weak<Executor>,
network: Arc<Network>,
storage: Arc<Storage>,
network_buffer_pool: BufferPool,
storage_buffer_pool: BufferPool,
tree: Arc<Tree>,
execution: Execution,
instrumented: bool,
}
impl Clone for Context {
fn clone(&self) -> Self {
let (child, _) = Tree::child(&self.tree);
Self {
name: self.name.clone(),
attributes: self.attributes.clone(),
scope: self.scope.clone(),
executor: self.executor.clone(),
network: self.network.clone(),
storage: self.storage.clone(),
network_buffer_pool: self.network_buffer_pool.clone(),
storage_buffer_pool: self.storage_buffer_pool.clone(),
tree: child,
execution: Execution::default(),
instrumented: false,
}
}
}
impl Context {
fn new(cfg: Config) -> (Self, Arc<Executor>, Panicked) {
// Create a new registry
let mut registry = Registry::new();
let runtime_registry = registry.root_mut().sub_registry_with_prefix(METRICS_PREFIX);
// Initialize runtime
let metrics = Arc::new(Metrics::init(runtime_registry));
let start_time = cfg.start_time;
let deadline = cfg
.timeout
.map(|timeout| start_time.checked_add(timeout).expect("timeout overflowed"));
let auditor = Arc::new(Auditor::default());
// Create shared RNG (used by both executor and storage)
let rng = Arc::new(Mutex::new(cfg.rng));
// Initialize buffer pools
let network_buffer_pool = BufferPool::new(
cfg.network_buffer_pool_cfg.clone(),
runtime_registry.sub_registry_with_prefix("network_buffer_pool"),
);
let storage_buffer_pool = BufferPool::new(
cfg.storage_buffer_pool_cfg.clone(),
runtime_registry.sub_registry_with_prefix("storage_buffer_pool"),
);
// Create storage fault config (default to disabled if None)
let storage_fault_config = Arc::new(RwLock::new(cfg.storage_fault_cfg));
let storage = MeteredStorage::new(
AuditedStorage::new(
FaultyStorage::new(
MemStorage::new(storage_buffer_pool.clone()),
rng.clone(),
storage_fault_config,
),
auditor.clone(),
),
runtime_registry,
);
// Create network
let network = AuditedNetwork::new(DeterministicNetwork::default(), auditor.clone());
let network = MeteredNetwork::new(network, runtime_registry);
// Initialize panicker
let (panicker, panicked) = Panicker::new(cfg.catch_panics);
let executor = Arc::new(Executor {
registry: Mutex::new(registry),
registered_metrics: Mutex::new(HashSet::new()),
cycle: cfg.cycle,
deadline,
metrics,
auditor,
rng,
time: Mutex::new(start_time),
tasks: Arc::new(Tasks::new()),
sleeping: Mutex::new(BinaryHeap::new()),
shutdown: Mutex::new(Stopper::default()),
panicker,
dns: Mutex::new(HashMap::new()),
});
(
Self {
name: String::new(),
attributes: Vec::new(),
scope: None,
executor: Arc::downgrade(&executor),
network: Arc::new(network),
storage: Arc::new(storage),
network_buffer_pool,
storage_buffer_pool,
tree: Tree::root(),
execution: Execution::default(),