-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathlib.rs
More file actions
4134 lines (3626 loc) · 144 KB
/
lib.rs
File metadata and controls
4134 lines (3626 loc) · 144 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
//! Execute asynchronous tasks with a configurable scheduler.
//!
//! This crate provides a collection of runtimes that can be
//! used to execute asynchronous tasks in a variety of ways. For production use,
//! the `tokio` module provides a runtime backed by [Tokio](https://tokio.rs).
//! For testing and simulation, the `deterministic` module provides a runtime
//! that allows for deterministic execution of tasks (given a fixed seed).
//!
//! # Terminology
//!
//! Each runtime is typically composed of an `Executor` and a `Context`. The `Executor` implements the
//! `Runner` trait and drives execution of a runtime. The `Context` implements any number of the
//! other traits to provide core functionality.
//!
//! # Status
//!
//! Stability varies by primitive. See [README](https://github.com/commonwarexyz/monorepo#stability) for details.
#![doc(
html_logo_url = "https://commonware.xyz/imgs/rustdoc_logo.svg",
html_favicon_url = "https://commonware.xyz/favicon.ico"
)]
use commonware_macros::stability_scope;
#[macro_use]
mod macros;
mod network;
mod process;
mod storage;
stability_scope!(ALPHA {
pub mod deterministic;
pub mod mocks;
});
stability_scope!(ALPHA, cfg(not(target_arch = "wasm32")) {
pub mod benchmarks;
});
stability_scope!(ALPHA, cfg(any(feature = "iouring-storage", feature = "iouring-network")) {
mod iouring;
});
stability_scope!(BETA, cfg(not(target_arch = "wasm32")) {
pub mod tokio;
});
stability_scope!(BETA {
use commonware_macros::select;
use commonware_parallel::{Rayon, ThreadPool};
use iobuf::PoolError;
use prometheus_client::registry::Metric;
use rayon::ThreadPoolBuildError;
use std::{
future::Future,
io::Error as IoError,
net::SocketAddr,
num::NonZeroUsize,
time::{Duration, SystemTime},
};
use thiserror::Error;
/// Prefix for runtime metrics.
pub(crate) const METRICS_PREFIX: &str = "runtime";
/// Re-export of `Buf` and `BufMut` traits for usage with [I/O buffers](iobuf).
pub use bytes::{Buf, BufMut};
/// Re-export of [governor::Quota] for rate limiting configuration.
pub use governor::Quota;
pub mod iobuf;
pub use iobuf::{
BufferPool, BufferPoolConfig, BufferPoolThreadCache, Builder as IoBufsBuilder, IoBuf,
IoBufMut, IoBufs, IoBufsMut,
};
pub mod utils;
pub use utils::*;
pub mod telemetry;
/// Default [`Blob`] version used when no version is specified via [`Storage::open`].
pub const DEFAULT_BLOB_VERSION: u16 = 0;
/// Errors that can occur when interacting with the runtime.
#[derive(Error, Debug)]
pub enum Error {
#[error("exited")]
Exited,
#[error("closed")]
Closed,
#[error("timeout")]
Timeout,
#[error("bind failed")]
BindFailed,
#[error("connection failed")]
ConnectionFailed,
#[error("write failed")]
WriteFailed,
#[error("read failed")]
ReadFailed,
#[error("send failed")]
SendFailed,
#[error("recv failed")]
RecvFailed,
#[error("dns resolution failed: {0}")]
ResolveFailed(String),
#[error("partition name invalid, must only contain alphanumeric, dash ('-'), or underscore ('_') characters: {0}")]
PartitionNameInvalid(String),
#[error("partition creation failed: {0}")]
PartitionCreationFailed(String),
#[error("partition missing: {0}")]
PartitionMissing(String),
#[error("partition corrupt: {0}")]
PartitionCorrupt(String),
#[error("blob open failed: {0}/{1} error: {2}")]
BlobOpenFailed(String, String, IoError),
#[error("blob missing: {0}/{1}")]
BlobMissing(String, String),
#[error("blob resize failed: {0}/{1} error: {2}")]
BlobResizeFailed(String, String, IoError),
#[error("blob sync failed: {0}/{1} error: {2}")]
BlobSyncFailed(String, String, IoError),
#[error("blob insufficient length")]
BlobInsufficientLength,
#[error("blob corrupt: {0}/{1} reason: {2}")]
BlobCorrupt(String, String, String),
#[error("blob version mismatch: expected one of {expected:?}, found {found}")]
BlobVersionMismatch {
expected: std::ops::RangeInclusive<u16>,
found: u16,
},
#[error("invalid or missing checksum")]
InvalidChecksum,
#[error("offset overflow")]
OffsetOverflow,
#[error("io error: {0}")]
Io(#[from] IoError),
#[error("buffer pool: {0}")]
Pool(#[from] PoolError),
}
/// Interface that any task scheduler must implement to start
/// running tasks.
pub trait Runner {
/// Context defines the environment available to tasks.
/// Example of possible services provided by the context include:
/// - [Clock] for time-based operations
/// - [Network] for network operations
/// - [Storage] for storage operations
type Context;
/// Start running a root task.
///
/// When this function returns, all spawned tasks will be canceled. If clean
/// shutdown cannot be implemented via `Drop`, consider using [Spawner::stop] and
/// [Spawner::stopped] to coordinate clean shutdown.
fn start<F, Fut>(self, f: F) -> Fut::Output
where
F: FnOnce(Self::Context) -> Fut,
Fut: Future;
}
/// Interface that any task scheduler must implement to spawn tasks.
pub trait Spawner: Clone + Send + Sync + 'static {
/// Return a [`Spawner`] that schedules tasks onto the runtime's shared executor.
///
/// Set `blocking` to `true` when the task may hold the thread for a short, blocking operation.
/// Runtimes can use this hint to move the work to a blocking-friendly pool so asynchronous
/// tasks on a work-stealing executor are not starved. For long-lived, blocking work, use
/// [`Spawner::dedicated`] instead.
///
/// The shared executor with `blocking == false` is the default spawn mode.
fn shared(self, blocking: bool) -> Self;
/// Return a [`Spawner`] that runs tasks on a dedicated thread when the runtime supports it.
///
/// Reserve this for long-lived or prioritized tasks that should not compete for resources in the
/// shared executor.
///
/// This is not the default behavior. See [`Spawner::shared`] for more information.
fn dedicated(self) -> Self;
/// Return a [`Spawner`] that runs tasks on a dedicated thread pinned to the given core.
///
/// Core pinning is currently Linux only and a no-op on other platforms. Pinning may
/// silently fail in restricted environments (e.g. containers with cgroup CPU limits),
/// this method will still succeed but the thread will run unpinned.
///
/// Use [`available_cores`] to query the number of available CPUs.
///
/// Implies [`Spawner::dedicated`].
///
/// # Panics
///
/// Panics if `core` is greater than or equal to the number of available CPUs.
fn pinned(self, core: usize) -> Self;
/// Return a [`Spawner`] that instruments the next spawned task with the label of the spawning context.
fn instrumented(self) -> Self;
/// Spawn a task with the current context.
///
/// Unlike directly awaiting a future, the task starts running immediately even if the caller
/// never awaits the returned [`Handle`].
///
/// # Mandatory Supervision
///
/// All tasks are supervised. When a parent task finishes or is aborted, all its descendants are aborted.
///
/// Spawn consumes the current task and provides a new child context to the spawned task. Likewise, cloning
/// a context (either via [`Clone::clone`] or [`Metrics::with_label`]) returns a child context.
///
/// ```txt
/// ctx_a
/// |
/// +-- clone() ---> ctx_c
/// | |
/// | +-- spawn() ---> Task C (ctx_d)
/// |
/// +-- spawn() ---> Task A (ctx_b)
/// |
/// +-- spawn() ---> Task B (ctx_e)
///
/// Task A finishes or aborts --> Task B and Task C are aborted
/// ```
///
/// # Spawn Configuration
///
/// When a context is cloned (either via [`Clone::clone`] or [`Metrics::with_label`]) or provided via
/// [`Spawner::spawn`], any configuration made via [`Spawner::dedicated`] or [`Spawner::shared`] is reset.
///
/// Child tasks should assume they start from a clean configuration without needing to inspect how their
/// parent was configured.
fn spawn<F, Fut, T>(self, f: F) -> Handle<T>
where
F: FnOnce(Self) -> Fut + Send + 'static,
Fut: Future<Output = T> + Send + 'static,
T: Send + 'static;
/// Signals the runtime to stop execution and waits for all outstanding tasks
/// to perform any required cleanup and exit.
///
/// This method does not actually kill any tasks but rather signals to them, using
/// the [signal::Signal] returned by [Spawner::stopped], that they should exit.
/// It then waits for all [signal::Signal] references to be dropped before returning.
///
/// ## Multiple Stop Calls
///
/// This method is idempotent and safe to call multiple times concurrently (on
/// different instances of the same context since it consumes `self`). The first
/// call initiates shutdown with the provided `value`, and all subsequent calls
/// will wait for the same completion regardless of their `value` parameter, i.e.
/// the original `value` from the first call is preserved.
///
/// ## Timeout
///
/// If a timeout is provided, the method will return an error if all [signal::Signal]
/// references have not been dropped within the specified duration.
fn stop(
self,
value: i32,
timeout: Option<Duration>,
) -> impl Future<Output = Result<(), Error>> + Send;
/// Returns an instance of a [signal::Signal] that resolves when [Spawner::stop] is called by
/// any task.
///
/// If [Spawner::stop] has already been called, the [signal::Signal] returned will resolve
/// immediately. The [signal::Signal] returned will always resolve to the value of the
/// first [Spawner::stop] call.
fn stopped(&self) -> signal::Signal;
}
/// Trait for creating [rayon]-compatible thread pools with each worker thread
/// placed on dedicated threads via [Spawner].
pub trait ThreadPooler: Spawner + Metrics {
/// Creates a clone-able [rayon]-compatible thread pool with [Spawner::spawn].
///
/// # Arguments
/// - `concurrency`: The number of tasks to execute concurrently in the pool.
///
/// # Returns
/// A `Result` containing the configured [rayon::ThreadPool] or a [rayon::ThreadPoolBuildError] if the pool cannot
/// be built.
fn create_thread_pool(
&self,
concurrency: NonZeroUsize,
) -> Result<ThreadPool, ThreadPoolBuildError>;
/// Creates a clone-able [Rayon] strategy for use with [commonware_parallel].
///
/// # Arguments
/// - `concurrency`: The number of tasks to execute concurrently in the pool.
///
/// # Returns
/// A `Result` containing the configured [Rayon] strategy or a [rayon::ThreadPoolBuildError] if the pool cannot be
/// built.
fn create_strategy(
&self,
concurrency: NonZeroUsize,
) -> Result<Rayon, ThreadPoolBuildError> {
self.create_thread_pool(concurrency).map(Rayon::with_pool)
}
}
/// Interface to register and encode metrics.
pub trait Metrics: Clone + Send + Sync + 'static {
/// Get the current label of the context.
fn label(&self) -> String;
/// Create a new instance of `Metrics` with the given label appended to the end
/// of the current `Metrics` label.
///
/// This is commonly used to create a nested context for `register`.
///
/// Labels must start with `[a-zA-Z]` and contain only `[a-zA-Z0-9_]`. It is not permitted for
/// any implementation to use `METRICS_PREFIX` as the start of a label (reserved for metrics for the runtime).
fn with_label(&self, label: &str) -> Self;
/// Create a new instance of `Metrics` with an additional attribute (key-value pair) applied
/// to all metrics registered in this context and any child contexts.
///
/// Unlike [`Metrics::with_label`] which affects the metric name prefix, `with_attribute` adds
/// a key-value pair that appears as a separate dimension in the metric output. This is
/// useful for instrumenting n-ary data structures in a way that is easy to manage downstream.
///
/// Keys must start with `[a-zA-Z]` and contain only `[a-zA-Z0-9_]`. Values can be any string.
///
/// # Labeling Children
///
/// Attributes apply to the entire subtree of contexts. When you call `with_attribute`, the
/// label is automatically added to all metrics registered in that context and any child
/// contexts created via `with_label`:
///
/// ```text
/// context
/// |-- with_label("orchestrator")
/// |-- with_attribute("epoch", "5")
/// |-- counter: votes -> orchestrator_votes{epoch="5"}
/// |-- counter: proposals -> orchestrator_proposals{epoch="5"}
/// |-- with_label("engine")
/// |-- gauge: height -> orchestrator_engine_height{epoch="5"}
/// ```
///
/// This pattern avoids wrapping every metric in a `Family` and avoids polluting metric
/// names with dynamic values like `orchestrator_epoch_5_votes`.
///
/// _Using attributes does not reduce cardinality (N epochs still means N time series).
/// Attributes just make metrics easier to query, filter, and aggregate._
///
/// # Family Label Conflicts
///
/// When using `Family` metrics, avoid using attribute keys that match the Family's label field names.
/// If a conflict occurs, the encoded output will contain duplicate labels (e.g., `{env="prod",env="staging"}`),
/// which is invalid Prometheus format and may cause scraping issues.
///
/// ```ignore
/// #[derive(EncodeLabelSet)]
/// struct Labels { env: String }
///
/// // BAD: attribute "env" conflicts with Family field "env"
/// let ctx = context.with_attribute("env", "prod");
/// let family: Family<Labels, Counter> = Family::default();
/// ctx.register("requests", "help", family);
/// // Produces invalid: requests_total{env="prod",env="staging"}
///
/// // GOOD: use distinct names
/// let ctx = context.with_attribute("region", "us_east");
/// // Produces valid: requests_total{region="us_east",env="staging"}
/// ```
///
/// # Example
///
/// ```ignore
/// // Instead of creating epoch-specific metric names:
/// let ctx = context.with_label(&format!("consensus_engine_{}", epoch));
/// // Produces: consensus_engine_5_votes_total, consensus_engine_6_votes_total, ...
///
/// // Use attributes to add epoch as a label dimension:
/// let ctx = context.with_label("consensus_engine").with_attribute("epoch", epoch);
/// // Produces: consensus_engine_votes_total{epoch="5"}, consensus_engine_votes_total{epoch="6"}, ...
/// ```
///
/// Multiple attributes can be chained:
/// ```ignore
/// let ctx = context
/// .with_label("engine")
/// .with_attribute("region", "us_east")
/// .with_attribute("instance", "i1");
/// // Produces: engine_requests_total{region="us_east",instance="i1"} 42
/// ```
///
/// # Querying The Latest Attribute
///
/// To query the latest attribute value dynamically, create a gauge to track the current value:
/// ```ignore
/// // Create a gauge to track the current epoch
/// let latest_epoch = Gauge::<i64>::default();
/// context.with_label("orchestrator").register("latest_epoch", "current epoch", latest_epoch.clone());
/// latest_epoch.set(current_epoch);
/// // Produces: orchestrator_latest_epoch 5
/// ```
///
/// Then create a dashboard variable `$latest_epoch` with query `max(orchestrator_latest_epoch)`
/// and use it in panel queries: `consensus_engine_votes_total{epoch="$latest_epoch"}`
fn with_attribute(&self, key: &str, value: impl std::fmt::Display) -> Self;
/// Register a metric with the runtime.
///
/// Any registered metric will include (as a prefix) the label of the current context.
///
/// Names must start with `[a-zA-Z]` and contain only `[a-zA-Z0-9_]`.
fn register<N: Into<String>, H: Into<String>>(&self, name: N, help: H, metric: impl Metric);
/// Encode all metrics into a buffer.
///
/// To ensure downstream analytics tools work correctly, users must never duplicate metrics
/// (via the concatenation of nested `with_label` and `register` calls). This can be
/// avoided by using `with_label` and `with_attribute` to create new context instances
/// (ensures all context instances are namespaced).
fn encode(&self) -> String;
/// Create a scoped context for metrics with a bounded lifetime (e.g., per-epoch
/// consensus engines). All metrics registered through the returned context (and
/// child contexts via [`Metrics::with_label`]/[`Metrics::with_attribute`]) go into
/// a separate registry that is automatically removed when all clones of the scoped
/// context are dropped.
///
/// If the context is already scoped, returns a clone with the same scope (scopes
/// nest by inheritance, not by creating new independent scopes).
///
/// # Uniqueness
///
/// Scoped metrics share the same global uniqueness constraint as
/// [`Metrics::register`]: each (prefixed_name, attributes) pair must be unique.
/// Callers should use [`Metrics::with_attribute`] to distinguish metrics across
/// scopes (e.g., an "epoch" attribute) rather than re-registering identical keys.
///
/// # Example
///
/// ```ignore
/// let scoped = context
/// .with_label("engine")
/// .with_attribute("epoch", epoch)
/// .with_scope();
///
/// // Register metrics into the scoped registry
/// let counter = Counter::default();
/// scoped.register("votes", "vote count", counter.clone());
///
/// // Metrics are removed when all clones of `scoped` are dropped.
/// ```
fn with_scope(&self) -> Self;
}
/// A direct (non-keyed) rate limiter using the provided [governor::clock::Clock] `C`.
///
/// This is a convenience type alias for creating single-entity rate limiters.
/// For per-key rate limiting, use [KeyedRateLimiter].
pub type RateLimiter<C> = governor::RateLimiter<
governor::state::NotKeyed,
governor::state::InMemoryState,
C,
governor::middleware::NoOpMiddleware<<C as governor::clock::Clock>::Instant>,
>;
/// A rate limiter keyed by `K` using the provided [governor::clock::Clock] `C`.
///
/// This is a convenience type alias for creating per-peer rate limiters
/// using governor's [HashMapStateStore].
///
/// [HashMapStateStore]: governor::state::keyed::HashMapStateStore
pub type KeyedRateLimiter<K, C> = governor::RateLimiter<
K,
governor::state::keyed::HashMapStateStore<K>,
C,
governor::middleware::NoOpMiddleware<<C as governor::clock::Clock>::Instant>,
>;
/// Interface that any task scheduler must implement to provide
/// time-based operations.
///
/// It is necessary to mock time to provide deterministic execution
/// of arbitrary tasks.
pub trait Clock:
governor::clock::Clock<Instant = SystemTime>
+ governor::clock::ReasonablyRealtime
+ Clone
+ Send
+ Sync
+ 'static
{
/// Returns the current time.
fn current(&self) -> SystemTime;
/// Sleep for the given duration.
fn sleep(&self, duration: Duration) -> impl Future<Output = ()> + Send + 'static;
/// Sleep until the given deadline.
fn sleep_until(&self, deadline: SystemTime) -> impl Future<Output = ()> + Send + 'static;
/// Await a future with a timeout, returning `Error::Timeout` if it expires.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use commonware_runtime::{deterministic, Error, Runner, Clock};
///
/// let executor = deterministic::Runner::default();
/// executor.start(|context| async move {
/// match context
/// .timeout(Duration::from_millis(100), async { 42 })
/// .await
/// {
/// Ok(value) => assert_eq!(value, 42),
/// Err(Error::Timeout) => panic!("should not timeout"),
/// Err(e) => panic!("unexpected error: {:?}", e),
/// }
/// });
/// ```
fn timeout<F, T>(
&self,
duration: Duration,
future: F,
) -> impl Future<Output = Result<T, Error>> + Send + '_
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
async move {
select! {
result = future => Ok(result),
_ = self.sleep(duration) => Err(Error::Timeout),
}
}
}
}
/// Syntactic sugar for the type of [Sink] used by a given [Network] N.
pub type SinkOf<N> = <<N as Network>::Listener as Listener>::Sink;
/// Syntactic sugar for the type of [Stream] used by a given [Network] N.
pub type StreamOf<N> = <<N as Network>::Listener as Listener>::Stream;
/// Syntactic sugar for the type of [Listener] used by a given [Network] N.
pub type ListenerOf<N> = <N as crate::Network>::Listener;
/// Interface that any runtime must implement to create
/// network connections.
pub trait Network: Clone + Send + Sync + 'static {
/// The type of [Listener] that's returned when binding to a socket.
/// Accepting a connection returns a [Sink] and [Stream] which are defined
/// by the [Listener] and used to send and receive data over the connection.
type Listener: Listener;
/// Bind to the given socket address.
fn bind(
&self,
socket: SocketAddr,
) -> impl Future<Output = Result<Self::Listener, Error>> + Send;
/// Dial the given socket address.
fn dial(
&self,
socket: SocketAddr,
) -> impl Future<Output = Result<(SinkOf<Self>, StreamOf<Self>), Error>> + Send;
}
/// Interface for DNS resolution.
pub trait Resolver: Clone + Send + Sync + 'static {
/// Resolve a hostname to IP addresses.
///
/// Returns a list of IP addresses that the hostname resolves to.
fn resolve(
&self,
host: &str,
) -> impl Future<Output = Result<Vec<std::net::IpAddr>, Error>> + Send;
}
/// Interface that any runtime must implement to handle
/// incoming network connections.
pub trait Listener: Sync + Send + 'static {
/// The type of [Sink] that's returned when accepting a connection.
/// This is used to send data to the remote connection.
type Sink: Sink;
/// The type of [Stream] that's returned when accepting a connection.
/// This is used to receive data from the remote connection.
type Stream: Stream;
/// Accept an incoming connection.
fn accept(
&mut self,
) -> impl Future<Output = Result<(SocketAddr, Self::Sink, Self::Stream), Error>> + Send;
/// Returns the local address of the listener.
fn local_addr(&self) -> Result<SocketAddr, std::io::Error>;
}
/// Interface that any runtime must implement to send
/// messages over a network connection.
pub trait Sink: Sync + Send + 'static {
/// Send a message to the sink.
///
/// # Warning
///
/// If the sink returns an error, part of the message may still be delivered.
fn send(
&mut self,
bufs: impl Into<IoBufs> + Send,
) -> impl Future<Output = Result<(), Error>> + Send;
}
/// Interface that any runtime must implement to receive
/// messages over a network connection.
pub trait Stream: Sync + Send + 'static {
/// Receive exactly `len` bytes from the stream.
///
/// The runtime allocates the buffer and returns it as `IoBufs`.
///
/// # Warning
///
/// If the stream returns an error, partially read data may be discarded.
fn recv(&mut self, len: usize) -> impl Future<Output = Result<IoBufs, Error>> + Send;
/// Peek at buffered data without consuming.
///
/// Returns up to `max_len` bytes from the internal buffer, or an empty slice
/// if no data is currently buffered. This does not perform any I/O or block.
///
/// This is useful e.g. for parsing length prefixes without committing to a read
/// or paying the cost of async.
fn peek(&self, max_len: usize) -> &[u8];
}
/// Interface to interact with storage.
///
/// To support storage implementations that enable concurrent reads and
/// writes, blobs are responsible for maintaining synchronization.
///
/// Storage can be backed by a local filesystem, cloud storage, etc.
///
/// # Partition Names
///
/// Partition names must be non-empty and contain only ASCII alphanumeric
/// characters, dashes (`-`), or underscores (`_`). Names containing other
/// characters (e.g., `/`, `.`, spaces) will return an error.
pub trait Storage: Clone + Send + Sync + 'static {
/// The readable/writeable storage buffer that can be opened by this Storage.
type Blob: Blob;
/// [`Storage::open_versioned`] with [`DEFAULT_BLOB_VERSION`] as the only value
/// in the versions range. The blob version is omitted from the return value.
fn open(
&self,
partition: &str,
name: &[u8],
) -> impl Future<Output = Result<(Self::Blob, u64), Error>> + Send {
async move {
let (blob, size, _) = self
.open_versioned(partition, name, DEFAULT_BLOB_VERSION..=DEFAULT_BLOB_VERSION)
.await?;
Ok((blob, size))
}
}
/// Open an existing blob in a given partition or create a new one, returning
/// the blob and its length.
///
/// Multiple instances of the same blob can be opened concurrently, however,
/// writing to the same blob concurrently may lead to undefined behavior.
///
/// An Ok result indicates the blob is durably created (or already exists).
///
/// # Versions
///
/// Blobs are versioned. If the blob's version is not in `versions`, returns
/// [Error::BlobVersionMismatch].
///
/// # Returns
///
/// A tuple of (blob, logical_size, blob_version).
fn open_versioned(
&self,
partition: &str,
name: &[u8],
versions: std::ops::RangeInclusive<u16>,
) -> impl Future<Output = Result<(Self::Blob, u64, u16), Error>> + Send;
/// Remove a blob from a given partition.
///
/// If no `name` is provided, the entire partition is removed.
///
/// An Ok result indicates the blob is durably removed.
fn remove(
&self,
partition: &str,
name: Option<&[u8]>,
) -> impl Future<Output = Result<(), Error>> + Send;
/// Return all blobs in a given partition.
fn scan(&self, partition: &str)
-> impl Future<Output = Result<Vec<Vec<u8>>, Error>> + Send;
}
/// Interface to read and write to a blob.
///
/// To support blob implementations that enable concurrent reads and
/// writes, blobs are responsible for maintaining synchronization.
///
/// Cloning a blob is similar to wrapping a single file descriptor in
/// a lock whereas opening a new blob (of the same name) is similar to
/// opening a new file descriptor. If multiple blobs are opened with the same
/// name, they are not expected to coordinate access to underlying storage
/// and writing to both is undefined behavior.
///
/// When a blob is dropped, any unsynced changes may be discarded. Implementations
/// may attempt to sync during drop but errors will go unhandled. Call `sync`
/// before dropping to ensure all changes are durably persisted.
#[allow(clippy::len_without_is_empty)]
pub trait Blob: Clone + Send + Sync + 'static {
/// Read `len` bytes at `offset` into caller-provided buffer(s).
///
/// The caller provides the buffer(s), and the implementation fills it with
/// exactly `len` bytes of data read from the blob starting at `offset`.
/// Returns the same buffer(s), filled with data.
///
/// # Contract
///
/// - The returned buffers reuse caller-provided storage, with exactly `len`
/// bytes filled from `offset`.
/// - Caller-provided chunk layout is preserved.
///
/// # Panics
///
/// Panics if `len` exceeds the total capacity of `bufs`.
fn read_at_buf(
&self,
offset: u64,
len: usize,
bufs: impl Into<IoBufsMut> + Send,
) -> impl Future<Output = Result<IoBufsMut, Error>> + Send;
/// Read `len` bytes at `offset`, returning a buffer(s) with exactly `len` bytes
/// of data read from the blob starting at `offset`.
///
/// To reuse a buffer(s), use [`Blob::read_at_buf`].
fn read_at(
&self,
offset: u64,
len: usize,
) -> impl Future<Output = Result<IoBufsMut, Error>> + Send;
/// Write `bufs` to the blob at the given offset.
fn write_at(
&self,
offset: u64,
bufs: impl Into<IoBufs> + Send,
) -> impl Future<Output = Result<(), Error>> + Send;
/// Resize the blob to the given length.
///
/// If the length is greater than the current length, the blob is extended with zeros.
/// If the length is less than the current length, the blob is resized.
fn resize(&self, len: u64) -> impl Future<Output = Result<(), Error>> + Send;
/// Ensure all pending data is durably persisted.
fn sync(&self) -> impl Future<Output = Result<(), Error>> + Send;
}
/// Interface that any runtime must implement to provide buffer pools.
pub trait BufferPooler: Clone + Send + Sync + 'static {
/// Returns the network [BufferPool].
fn network_buffer_pool(&self) -> &BufferPool;
/// Returns the storage [BufferPool].
fn storage_buffer_pool(&self) -> &BufferPool;
}
});
stability_scope!(BETA, cfg(feature = "external") {
/// Interface that runtimes can implement to constrain the execution latency of a future.
pub trait Pacer: Clock + Clone + Send + Sync + 'static {
/// Defer completion of a future until a specified `latency` has elapsed. If the future is
/// not yet ready at the desired time of completion, the runtime will block until the future
/// is ready.
///
/// In [crate::deterministic], this is used to ensure interactions with external systems can
/// be interacted with deterministically. In [crate::tokio], this is a no-op (allows
/// multiple runtimes to be tested with no code changes).
///
/// # Setting Latency
///
/// `pace` is not meant to be a time penalty applied to awaited futures and should be set to
/// the expected resolution latency of the future. To better explore the possible behavior of an
/// application, users can set latency to a randomly chosen value in the range of
/// `[expected latency / 2, expected latency * 2]`.
///
/// # Warning
///
/// Because `pace` blocks if the future is not ready, it is important that the future's completion
/// doesn't require anything in the current thread to complete (or else it will deadlock).
fn pace<'a, F, T>(
&'a self,
latency: Duration,
future: F,
) -> impl Future<Output = T> + Send + 'a
where
F: Future<Output = T> + Send + 'a,
T: Send + 'a;
}
/// Extension trait that makes it more ergonomic to use [Pacer].
///
/// This inverts the call-site of [`Pacer::pace`] by letting the future itself request how the
/// runtime should delay completion relative to the clock.
pub trait FutureExt: Future + Send + Sized {
/// Delay completion of the future until a specified `latency` on `pacer`.
fn pace<'a, E>(
self,
pacer: &'a E,
latency: Duration,
) -> impl Future<Output = Self::Output> + Send + 'a
where
E: Pacer + 'a,
Self: Send + 'a,
Self::Output: Send + 'a,
{
pacer.pace(latency, self)
}
}
impl<F> FutureExt for F where F: Future + Send {}
});
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::traces::collector::TraceStorage;
use bytes::Bytes;
use commonware_macros::{select, test_collect_traces};
use commonware_utils::{
channel::{mpsc, oneshot},
sync::Mutex,
NZUsize, SystemTimeExt,
};
use futures::{
future::{pending, ready},
join, pin_mut, FutureExt,
};
use prometheus_client::{
encoding::{EncodeLabelKey, EncodeLabelSet, EncodeLabelValue},
metrics::{counter::Counter, family::Family},
};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::{
collections::HashMap,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
pin::Pin,
str::FromStr,
sync::{
atomic::{AtomicU32, Ordering},
Arc,
},
task::{Context as TContext, Poll, Waker},
};
use tracing::{error, Level};
use utils::reschedule;
fn test_error_future<R: Runner>(runner: R) {
#[allow(clippy::unused_async)]
async fn error_future() -> Result<&'static str, &'static str> {
Err("An error occurred")
}
let result = runner.start(|_| error_future());
assert_eq!(result, Err("An error occurred"));
}
fn test_clock_sleep<R: Runner>(runner: R)
where
R::Context: Spawner + Clock,
{
runner.start(|context| async move {
// Capture initial time
let start = context.current();
let sleep_duration = Duration::from_millis(10);
context.sleep(sleep_duration).await;
// After run, time should have advanced
let end = context.current();
assert!(end.duration_since(start).unwrap() >= sleep_duration);
});
}
fn test_clock_sleep_until<R: Runner>(runner: R)
where
R::Context: Spawner + Clock + Metrics,
{
runner.start(|context| async move {
// Trigger sleep
let now = context.current();
context.sleep_until(now + Duration::from_millis(100)).await;
// Ensure slept duration has elapsed
let elapsed = now.elapsed().unwrap();
assert!(elapsed >= Duration::from_millis(100));
});
}
fn test_clock_sleep_until_far_future<R: Runner>(runner: R)
where
R::Context: Spawner + Clock,
{
runner.start(|context| async move {
let sleep = context.sleep_until(SystemTime::limit());
let result = context.timeout(Duration::from_millis(1), sleep).await;
assert!(matches!(result, Err(Error::Timeout)));
});
}
fn test_clock_timeout<R: Runner>(runner: R)
where
R::Context: Spawner + Clock,
{
runner.start(|context| async move {
// Future completes before timeout
let result = context
.timeout(Duration::from_millis(100), async { "success" })
.await;
assert_eq!(result.unwrap(), "success");
// Future exceeds timeout duration
let result = context
.timeout(Duration::from_millis(50), pending::<()>())
.await;
assert!(matches!(result, Err(Error::Timeout)));
// Future completes within timeout
let result = context
.timeout(
Duration::from_millis(100),
context.sleep(Duration::from_millis(50)),
)
.await;
assert!(result.is_ok());
});
}
fn test_root_finishes<R: Runner>(runner: R)
where
R::Context: Spawner,
{
runner.start(|context| async move {
context.spawn(|_| async move {
loop {
reschedule().await;
}
});
});
}
fn test_spawn_after_abort<R>(runner: R)
where
R: Runner,
R::Context: Spawner + Clone,
{
runner.start(|context| async move {
// Create a child context
let child = context.clone();
// Spawn parent and abort
let parent_handle = context.spawn(move |_| async move {
pending::<()>().await;
});
parent_handle.abort();
// Spawn child and ensure it aborts
let child_handle = child.spawn(move |_| async move {
pending::<()>().await;
});
assert!(matches!(child_handle.await, Err(Error::Closed)));
});
}
fn test_spawn_abort<R: Runner>(runner: R, dedicated: bool, blocking: bool)
where
R::Context: Spawner,
{
runner.start(|context| async move {
let context = if dedicated {
assert!(!blocking);
context.dedicated()
} else {
context.shared(blocking)
};
let handle = context.spawn(|_| async move {
loop {
reschedule().await;
}
});
handle.abort();