-
Notifications
You must be signed in to change notification settings - Fork 15
/
runtime.rs
1852 lines (1727 loc) · 64.7 KB
/
runtime.rs
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
use super::*;
use crate::{
messaging::{
DispatchEnvelope,
MsgEnvelope,
PathResolvable,
RegistrationEnvelope,
RegistrationError,
},
supervision::{ComponentSupervisor, ListenEvent, SupervisionPort, SupervisorMsg},
};
use executors::*;
use hocon::{Hocon, HoconLoader};
use oncemutex::{OnceMutex, OnceMutexGuard};
use std::{
clone::Clone,
fmt::{Debug, Formatter, Result as FmtResult},
path::PathBuf,
rc::Rc,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
Mutex,
Once,
},
};
static GLOBAL_RUNTIME_COUNT: AtomicUsize = AtomicUsize::new(0);
fn default_runtime_label() -> String {
let runtime_count = GLOBAL_RUNTIME_COUNT.fetch_add(1, Ordering::SeqCst) + 1;
format!("kompact-runtime-{}", runtime_count)
}
static mut DEFAULT_ROOT_LOGGER: Option<KompactLogger> = None;
static DEFAULT_ROOT_LOGGER_INIT: Once = Once::new();
fn default_logger() -> &'static KompactLogger {
unsafe {
DEFAULT_ROOT_LOGGER_INIT.call_once(|| {
let decorator = slog_term::TermDecorator::new().stdout().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).chan_size(1024).build().fuse();
DEFAULT_ROOT_LOGGER = Some(slog::Logger::root_typed(
Arc::new(drain),
o!(
"location" => slog::PushFnValue(|r: &slog::Record<'_>, ser: slog::PushFnValueSerializer<'_>| {
ser.emit(format_args!("{}:{}", r.file(), r.line()))
})
),
));
});
match DEFAULT_ROOT_LOGGER {
Some(ref l) => l,
None => unreachable!(),
}
}
}
type SchedulerBuilder = dyn Fn(usize) -> Box<dyn Scheduler>;
type SCBuilder = dyn Fn(&KompactSystem, Promise<()>, Promise<()>) -> Box<dyn SystemComponents>;
type TimerBuilder = dyn Fn() -> Box<dyn TimerComponent>;
/// A Kompact system error
#[derive(Debug, PartialEq, Clone)]
pub enum KompactError {
/// A mutex in the system has been poisoned
Poisoned,
/// An error occurred loading the HOCON config
ConfigError(hocon::Error),
}
impl From<hocon::Error> for KompactError {
fn from(e: hocon::Error) -> Self {
KompactError::ConfigError(e)
}
}
#[derive(Debug, Clone)]
enum ConfigSource {
File(PathBuf),
Str(String),
}
/// A configuration builder for Kompact systems
///
/// # Example
///
/// Set a custom label, and run up to 50 events or messages per scheduling of a component
/// on a threadpool with 2 threads.
///
/// ```
/// use kompact::prelude::*;
///
/// let mut conf = KompactConfig::default();
/// conf.label("My special system")
/// .throughput(50)
/// .threads(2);
/// let system = conf.build().expect("system");
/// # system.shutdown().expect("shutdown");
/// ```
#[derive(Clone)]
pub struct KompactConfig {
label: String,
throughput: usize,
msg_priority: f32,
threads: usize,
timer_builder: Rc<TimerBuilder>,
scheduler_builder: Rc<SchedulerBuilder>,
sc_builder: Rc<SCBuilder>,
root_logger: Option<KompactLogger>,
config_sources: Vec<ConfigSource>,
}
impl Debug for KompactConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(
f,
"KompactConfig{{
label={},
throughput={},
msg_priority={},
threads={},
timer_builder=<function>,
scheduler_builder=<function>,
sc_builder=<function>,
root_logger={:?},
config_sources={:?}
}}",
self.label,
self.throughput,
self.msg_priority,
self.threads,
self.root_logger,
self.config_sources
)
}
}
impl KompactConfig {
/// Create a minimal Kompact config
///
/// The minimal config uses the default label, i.e. `"kompact-runtime-{}"` for some sequence number.
/// It sets the event/message throughput to 2, split evenly between events and messages.
/// It runs with a single thread on a [small pool](crossbeam_workstealing_pool::small_pool).
/// It uses all default components, without networking, with the default timer and default logger.
pub fn new() -> KompactConfig {
KompactConfig {
label: default_runtime_label(),
throughput: 2,
msg_priority: 0.5,
threads: 1,
timer_builder: Rc::new(|| DefaultTimer::new_timer_component()),
scheduler_builder: Rc::new(|t| {
ExecutorScheduler::from(crossbeam_workstealing_pool::small_pool(t))
}),
sc_builder: Rc::new(|sys, dead_prom, disp_prom| {
Box::new(DefaultComponents::new(sys, dead_prom, disp_prom))
}),
root_logger: None,
config_sources: Vec::new(),
}
}
/// Set the name of the system
///
/// The label is used as metadata for logging output.
pub fn label<I>(&mut self, s: I) -> &mut Self
where
I: Into<String>,
{
self.label = s.into();
self
}
/// Set the maximum number of events/messages to handle before rescheduling a component
///
/// Larger values can increase throughput on highly loaded components,
/// but at the cost of fairness between components.
pub fn throughput(&mut self, n: usize) -> &mut Self {
assert!(n > 0, "throughput must be larger than 0");
self.throughput = n;
self
}
/// Set the ratio between handling messages and events.
///
/// A component will handle up to throughput * r messages
/// and throughput * (1-r) events before rescheduling.
///
/// If there are less events or messages than alloted queued up
/// the remaining allotment will be redistributed to the other type
/// until all throughput is used up or no messages or events remain.
pub fn msg_priority(&mut self, r: f32) -> &mut Self {
assert!(r > 0.0, "msg_priority must be larger than 0.0");
self.msg_priority = r;
self
}
/// The number of threads in the Kompact thread pool
///
/// # Note
///
/// You *must* ensure that the selected [scheduler](KompactConfig::scheduler) implementation
/// can manage the given number of threads, if you customise this value!
pub fn threads(&mut self, n: usize) -> &mut Self {
assert!(n > 0, "threads must be larger than 0");
self.threads = n;
self
}
/// Set a particular scheduler implementation
///
/// Takes a function `f` from the number of threads to a concrete scheduler implementation as argument.
pub fn scheduler<F>(&mut self, f: F) -> &mut Self
where
F: Fn(usize) -> Box<dyn Scheduler> + 'static,
{
self.scheduler_builder = Rc::new(f);
self
}
/// Set a particular scheduler implementation based on an [executor](executors::core::Executor)
///
/// Takes a function `f` from the number of threads to a concrete executor as argument.
pub fn executor<E, F>(&mut self, f: F) -> &mut Self
where
E: Executor + Sync + 'static,
F: Fn(usize) -> E + 'static,
{
let sb = move |t: usize| ExecutorScheduler::from(f(t));
self.scheduler_builder = Rc::new(sb);
self
}
/// Set a particular timer implementation
pub fn timer<T, F>(&mut self, f: F) -> &mut Self
where
T: TimerComponent + 'static,
F: Fn() -> Box<dyn TimerComponent> + 'static,
{
self.timer_builder = Rc::new(f);
self
}
/// Set a particular set of system components
///
/// In particular, this allows exchanging the default dispatcher for the
/// [NetworkDispatcher](prelude::NetworkDispatcher), which enables the created Kompact system
/// to perform network communication.
///
/// # Example
///
/// For using the network dispatcher, with the default deadletter box:
/// ```
/// use kompact::prelude::*;
///
/// let mut cfg = KompactConfig::new();
/// cfg.system_components(DeadletterBox::new, {
/// let net_config = NetworkConfig::new("127.0.0.1:0".parse().expect("Address should work"));
/// net_config.build()
/// });
/// let system = cfg.build().expect("KompactSystem");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn system_components<B, C, FB, FC>(
&mut self,
deadletter_fn: FB,
dispatcher_fn: FC,
) -> &mut Self
where
B: ComponentDefinition + ActorRaw<Message = Never> + Sized + 'static,
C: ComponentDefinition
+ ActorRaw<Message = DispatchEnvelope>
+ Sized
+ 'static
+ Dispatcher,
FB: Fn(Promise<()>) -> B + 'static,
FC: Fn(Promise<()>) -> C + 'static,
{
let sb = move |system: &KompactSystem, dead_prom: Promise<()>, disp_prom: Promise<()>| {
let deadletter_box = system.create_unsupervised(|| deadletter_fn(dead_prom));
let dispatcher = system.create_unsupervised(|| dispatcher_fn(disp_prom));
let cc = CustomComponents {
deadletter_box,
dispatcher,
};
Box::new(cc) as Box<dyn SystemComponents>
};
self.sc_builder = Rc::new(sb);
self
}
/// Set a particular set of system components
///
/// This function works just like [system_components](KompactConfig::system_components),
/// except that it assigns the dispatcher to its own thread using
/// [create_dedicated_unsupervised](KompactSystem::create_dedicated_unsupervised).
pub fn system_components_with_dedicated_dispatcher<B, C, FB, FC>(
&mut self,
deadletter_fn: FB,
dispatcher_fn: FC,
) -> &mut Self
where
B: ComponentDefinition + ActorRaw<Message = Never> + Sized + 'static,
C: ComponentDefinition
+ ActorRaw<Message = DispatchEnvelope>
+ Sized
+ 'static
+ Dispatcher,
FB: Fn(Promise<()>) -> B + 'static,
FC: Fn(Promise<()>) -> C + 'static,
{
let sb = move |system: &KompactSystem, dead_prom: Promise<()>, disp_prom: Promise<()>| {
let deadletter_box = system.create_unsupervised(|| deadletter_fn(dead_prom));
let dispatcher = system.create_dedicated_unsupervised(|| dispatcher_fn(disp_prom));
let cc = CustomComponents {
deadletter_box,
dispatcher,
};
Box::new(cc) as Box<dyn SystemComponents>
};
self.sc_builder = Rc::new(sb);
self
}
/// Set a particular set of system components
///
/// This function works just like [system_components](KompactConfig::system_components),
/// except that it assigns the dispatcher is pinned to its own thread using
/// [create_dedicated_pinned_unsupervised](KompactSystem::create_dedicated_pinned_unsupervised).
#[cfg(feature = "thread_pinning")]
pub fn system_components_with_dedicated_dispatcher_pinned<B, C, FB, FC>(
&mut self,
deadletter_fn: FB,
dispatcher_fn: FC,
dispatcher_core: CoreId,
) -> &mut Self
where
B: ComponentDefinition + ActorRaw<Message = Never> + Sized + 'static,
C: ComponentDefinition
+ ActorRaw<Message = DispatchEnvelope>
+ Sized
+ 'static
+ Dispatcher,
FB: Fn(Promise<()>) -> B + 'static,
FC: Fn(Promise<()>) -> C + 'static,
{
let sb = move |system: &KompactSystem, dead_prom: Promise<()>, disp_prom: Promise<()>| {
let deadletter_box = system.create_unsupervised(|| deadletter_fn(dead_prom));
let dispatcher = system
.create_dedicated_pinned_unsupervised(|| dispatcher_fn(disp_prom), dispatcher_core);
let cc = CustomComponents {
deadletter_box,
dispatcher,
};
Box::new(cc) as Box<dyn SystemComponents>
};
self.sc_builder = Rc::new(sb);
self
}
/// Set the logger implementation to use
pub fn logger(&mut self, logger: KompactLogger) -> &mut Self {
self.root_logger = Some(logger);
self
}
/// Load a HOCON config from a file at `path`
///
/// This method can be called multiple times, and the resulting configurations will be merged.
/// See [HoconLoader](hocon::HoconLoader) for more information.
///
/// The loaded config can be accessed via [`system.config()`](KompactSystem::config
/// or from within a component via [`self.ctx().config()`](ComponentContext::config.
pub fn load_config_file<P>(&mut self, path: P) -> &mut Self
where
P: Into<PathBuf>,
{
let p: PathBuf = path.into();
self.config_sources.push(ConfigSource::File(p));
self
}
/// Load a HOCON config from a string
///
/// This method can be called multiple times, and the resulting configurations will be merged.
/// See [HoconLoader](hocon::HoconLoader) for more information.
///
/// The loaded config can be accessed via [`system.config()`](KompactSystem::config
/// or from within a component via [`self.ctx().config()`](ComponentContext::config.
pub fn load_config_str<S>(&mut self, config: S) -> &mut Self
where
S: Into<String>,
{
let s: String = config.into();
self.config_sources.push(ConfigSource::Str(s));
self
}
/// Finalise the config and use it create a [KompactSystem](KompactSystem)
///
/// This function can fail, if the configuration sets up invalid schedulers
/// or dispatchers, for example.
///
/// # Example
///
/// Build a system with default settings with:
///
/// ```
/// use kompact::prelude::*;
///
/// let system = KompactConfig::default().build().expect("system");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn build(self) -> Result<KompactSystem, KompactError> {
KompactSystem::try_new(self)
}
fn max_messages(&self) -> usize {
let tpf = self.throughput as f32;
let mmf = tpf * self.msg_priority;
assert!(mmf >= 0.0, "msg_priority can not be negative!");
let mm = mmf as usize;
mm
}
}
impl Default for KompactConfig {
/// Create a default Kompact config
///
/// The default config uses the default label, i.e. `"kompact-runtime-{}"` for some sequence number.
/// It sets the event/message throughput to 50, split evenly between events and messages.
/// It runs with one thread per cpu on an appropriately sized [`crossbeam_workstealing_pool`](crossbeam_workstealing_pool) implementation.
/// It uses all default components, without networking, with the default timer and default logger.
fn default() -> Self {
let threads = std::cmp::max(1, num_cpus::get());
let scheduler_builder: Rc<SchedulerBuilder> = if threads <= 32 {
Rc::new(|t| ExecutorScheduler::from(crossbeam_workstealing_pool::small_pool(t)))
} else if threads <= 64 {
Rc::new(|t| ExecutorScheduler::from(crossbeam_workstealing_pool::large_pool(t)))
} else {
Rc::new(|t| ExecutorScheduler::from(crossbeam_workstealing_pool::dyn_pool(t)))
};
KompactConfig {
label: default_runtime_label(),
throughput: 50,
msg_priority: 0.5,
threads,
timer_builder: Rc::new(|| DefaultTimer::new_timer_component()),
scheduler_builder,
sc_builder: Rc::new(|sys, dead_prom, disp_prom| {
Box::new(DefaultComponents::new(sys, dead_prom, disp_prom))
}),
root_logger: None,
config_sources: Vec::new(),
}
}
}
/// A Kompact system is a collection of components and services
///
/// An instance of `KompactSystem` is created from a [KompactConfig](KompactConfig)
/// via the [build](KompactConfig::build) function.
///
/// It is possible to run more than one Kompact system in a single process.
/// This allows different settings to be used for different component groups, for example.
/// It can also be used for testing communication in unit or integration tests.
///
/// # Note
///
/// For some schedulers it can happen that components may switch from one system's scheduler to the
/// other's when running multiple systems in the same process and communicating between them via channels
/// or actor references.
/// Generally, this shouldn't be an issue, but it can invalidate assumptions on thread assignments, so it's
/// important to be aware of. If this behaviour needs to be avoided at all costs, one can either use a scheduler
/// that doesn't use thread-local variables to determine the target queue
/// (e.g., [`crossbeam_channel_pool`](executors::crossbeam_channel_pool)),
/// or limit cross-system communication to network-only,
/// incurring the associated serialisation/deserialisations costs.
///
/// # Example
///
/// Build a system with default settings with:
///
/// ```
/// use kompact::prelude::*;
///
/// let system = KompactConfig::default().build().expect("system");
/// # system.shutdown().expect("shutdown");
/// ```
#[derive(Clone)]
pub struct KompactSystem {
inner: Arc<KompactRuntime>,
config: Arc<Hocon>,
scheduler: Box<dyn Scheduler>,
}
impl KompactSystem {
/// Use the [build](KompactConfig::build) method instead.
pub(crate) fn try_new(conf: KompactConfig) -> Result<Self, KompactError> {
let scheduler = (*conf.scheduler_builder)(conf.threads);
let sc_builder = conf.sc_builder.clone();
let config_loader_initial: Result<HoconLoader, hocon::Error> =
Result::Ok(HoconLoader::new());
let config = conf
.config_sources
.iter()
.fold(config_loader_initial, |config_loader, source| {
config_loader.and_then(|cl| match source {
ConfigSource::File(path) => cl.load_file(path),
ConfigSource::Str(s) => cl.load_str(s),
})
})?
.hocon()?;
let runtime = Arc::new(KompactRuntime::new(conf));
let sys = KompactSystem {
inner: runtime,
config: Arc::new(config),
scheduler,
};
let (dead_prom, dead_f) = utils::promise();
let (disp_prom, disp_f) = utils::promise();
let system_components = (*sc_builder)(&sys, dead_prom, disp_prom);
let supervisor = sys.create_unsupervised(ComponentSupervisor::new);
let ic = InternalComponents::new(supervisor, system_components);
sys.inner.set_internal_components(ic);
sys.inner.start_internal_components(&sys);
let timeout = std::time::Duration::from_millis(50);
let mut wait_for: Option<Future<()>> = Some(dead_f);
while wait_for.is_some() {
if sys.inner.is_poisoned() {
return Err(KompactError::Poisoned);
}
match wait_for.take().unwrap().wait_timeout(timeout) {
Ok(_) => (),
Err(w) => wait_for = Some(w),
}
}
let mut wait_for: Option<Future<()>> = Some(disp_f);
while wait_for.is_some() {
if sys.inner.is_poisoned() {
return Err(KompactError::Poisoned);
}
match wait_for.take().unwrap().wait_timeout(timeout) {
Ok(_) => (),
Err(w) => wait_for = Some(w),
}
}
Ok(sys)
}
pub(crate) fn schedule(&self, c: Arc<dyn CoreContainer>) -> () {
self.scheduler.schedule(c);
}
/// Get a reference to the system-wide Kompact logger
///
/// # Example
///
/// ```
/// # use kompact::prelude::*;
/// # let system = KompactConfig::default().build().expect("system");
/// info!(system.logger(), "Hello World from the system logger!");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn logger(&self) -> &KompactLogger {
&self.inner.logger
}
/// Get a reference to the system configuration
///
/// Use [load_config_str](KompactConfig::load_config_str) or
/// or [load_config_file](KompactConfig::load_config_file)
/// to load values into the config object.
///
/// # Example
///
/// ```
/// use kompact::prelude::*;
/// let default_values = r#"{ a = 7 }"#;
/// let mut conf = KompactConfig::default();
/// conf.load_config_str(default_values);
/// let system = conf.build().expect("system");
/// assert_eq!(Some(7i64), system.config()["a"].as_i64());
/// ```
pub fn config(&self) -> &Hocon {
self.config.as_ref()
}
/// Get a owned reference to the system configuration
pub fn config_owned(&self) -> Arc<Hocon> {
self.config.clone()
}
pub(crate) fn poison(&self) {
self.inner.poison();
self.scheduler.poison();
}
/// Create a new component
///
/// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
/// which is the initialised to form a [Component](Component).
/// Since components are shared between threads, the created component
/// is wrapped into an [Arc](std::sync::Arc).
///
/// Newly created components are not started automatically.
/// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
/// to start a newly created component, once it is connected properly.
///
/// If you need address this component via the network, see the [register](KompactSystem::register) function.
///
/// # Example
///
/// ```
/// # use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// # let system = KompactConfig::default().build().expect("system");
/// let c = system.create(TestComponent1::new);
/// # system.shutdown().expect("shutdown");
/// ```
pub fn create<C, F>(&self, f: F) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
self.inner.assert_active();
let c = Arc::new(Component::new(self.clone(), f(), self.supervision_port()));
unsafe {
let mut cd = c.definition().lock().unwrap();
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
cd.setup(c.clone());
c.core().set_component(cc);
}
return c;
}
/// Create a new system component
///
/// You *must* use this instead of [create](KompactSystem::create) to create
/// a new system component.
/// During system initialisation the supervisor is not available, yet,
/// so normal [create](KompactSystem::create) calls will panic!
pub fn create_unsupervised<C, F>(&self, f: F) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
let c = Arc::new(Component::without_supervisor(self.clone(), f()));
unsafe {
let mut cd = c.definition().lock().unwrap();
cd.setup(c.clone());
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
c.core().set_component(cc);
}
return c;
}
/// Create a new component, which runs on its own dedicated thread.
///
/// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
/// which is the initialised to form a [Component](Component).
/// Since components are shared between threads, the created component
/// is wrapped into an [Arc](std::sync::Arc).
///
/// A dedicated thread is assigned to this component, which sleeps when the component has no work.
///
/// Newly created components are not started automatically.
/// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
/// to start a newly created component, once it is connected properly.
///
/// If you need address this component via the network, see the [register](KompactSystem::register) function.
pub fn create_dedicated<C, F>(&self, f: F) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
self.inner.assert_active();
let (scheduler, promise) =
dedicated_scheduler::DedicatedThreadScheduler::new().expect("Scheduler");
let c = Arc::new(Component::with_dedicated_scheduler(
self.clone(),
f(),
self.supervision_port(),
scheduler,
));
unsafe {
let mut cd = c.definition().lock().unwrap();
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
cd.setup(c.clone());
c.core().set_component(cc);
}
promise.fulfill(c.clone()).expect("Should accept component");
return c;
}
/// Create a new component, which runs on its own dedicated thread and is pinned to certain CPU core.
///
/// This functionality is only available with feature `thread_pinning`.
///
/// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
/// which is the initialised to form a [Component](Component).
/// Since components are shared between threads, the created component
/// is wrapped into an [Arc](std::sync::Arc).
///
/// A dedicated thread is assigned to this component, which sleeps when the component has no work.
/// The thread is also pinned to the given `core_id`, allowing static, manual, NUMA aware component assignments.
///
/// Newly created components are not started automatically.
/// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
/// to start a newly created component, once it is connected properly.
///
/// If you need address this component via the network, see the [register](KompactSystem::register) function.
#[cfg(feature = "thread_pinning")]
pub fn create_dedicated_pinned<C, F>(&self, f: F, core_id: CoreId) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
self.inner.assert_active();
let (scheduler, promise) =
dedicated_scheduler::DedicatedThreadScheduler::pinned(core_id).expect("Scheduler");
let c = Arc::new(Component::with_dedicated_scheduler(
self.clone(),
f(),
self.supervision_port(),
scheduler,
));
unsafe {
let mut cd = c.definition().lock().unwrap();
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
cd.setup(c.clone());
c.core().set_component(cc);
}
promise.fulfill(c.clone()).expect("Should accept component");
return c;
}
/// Create a new system component, which runs on its own dedicated thread.
///
/// A dedicated thread is assigned to this component, which sleeps when the component has no work.
///
/// You *must* use this instead of [create_dedicated](KompactSystem::create_dedicated) to create
/// a new system component on its own thread.
/// During system initialisation the supervisor is not available, yet,
/// so normal [create](KompactSystem::create) calls will panic!
pub fn create_dedicated_unsupervised<C, F>(&self, f: F) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
let (scheduler, promise) =
dedicated_scheduler::DedicatedThreadScheduler::new().expect("Scheduler");
let c = Arc::new(Component::without_supervisor_with_dedicated_scheduler(
self.clone(),
f(),
scheduler,
));
unsafe {
let mut cd = c.definition().lock().unwrap();
cd.setup(c.clone());
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
c.core().set_component(cc);
}
promise.fulfill(c.clone()).expect("Should accept component");
return c;
}
/// Create a new system component, which runs on its own dedicated thread.
///
/// A dedicated thread is assigned to this component, which sleeps when the component has no work.
/// The thread is also pinned to the given `core_id`, allowing static, manual, NUMA aware component assignments.
///
/// You *must* use this instead of [create_dedicated_pinned](KompactSystem::create_dedicated_pinned) to create
/// a new system component on its own thread.
/// During system initialisation the supervisor is not available, yet,
/// so normal [create](KompactSystem::create) calls will panic!
#[cfg(feature = "thread_pinning")]
pub fn create_dedicated_pinned_unsupervised<C, F>(
&self,
f: F,
core_id: CoreId,
) -> Arc<Component<C>>
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
let (scheduler, promise) =
dedicated_scheduler::DedicatedThreadScheduler::pinned(core_id).expect("Scheduler");
let c = Arc::new(Component::without_supervisor_with_dedicated_scheduler(
self.clone(),
f(),
scheduler,
));
unsafe {
let mut cd = c.definition().lock().unwrap();
cd.setup(c.clone());
let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
c.core().set_component(cc);
}
promise.fulfill(c.clone()).expect("Should accept component");
return c;
}
/// Attempts to register `c` with the dispatcher using its unique id
///
/// The returned future will contain the unique id [ActorPath](ActorPath)
/// for the given component, once it is completed by the dispatcher.
///
/// Once the future completes, the component can be addressed via the network,
/// even if it has not been started, yet (in which case messages will simply be queued up).
///
/// # Example
///
/// ```
/// use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// use std::time::Duration;
/// let mut cfg = KompactConfig::new();
/// cfg.system_components(DeadletterBox::new, {
/// let net_config = NetworkConfig::new("127.0.0.1:0".parse().expect("Address should work"));
/// net_config.build()
/// });
/// let system = cfg.build().expect("KompactSystem");
/// let c = system.create(TestComponent1::new);
/// system.register(&c).wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn register<C>(&self, c: &Arc<Component<C>>) -> Future<Result<ActorPath, RegistrationError>>
where
C: ComponentDefinition + 'static,
{
self.inner.assert_active();
let id = c.core().id().clone();
let id_path = PathResolvable::ActorId(id);
self.inner.register_by_path(c, id_path)
}
/// Creates a new component and registers it with the dispatcher
///
/// This function is simply a convenience shortcut for
/// [create](KompactSystem::create) followed by [register](KompactSystem::register),
/// as this combination is very common in networked Kompact systems.
///
/// # Example
///
/// ```
/// use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// use std::time::Duration;
/// let mut cfg = KompactConfig::new();
/// cfg.system_components(DeadletterBox::new, {
/// let net_config = NetworkConfig::new("127.0.0.1:0".parse().expect("Address should work"));
/// net_config.build()
/// });
/// let system = cfg.build().expect("KompactSystem");
/// let (c, registration_future) = system.create_and_register(TestComponent1::new);
/// registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn create_and_register<C, F>(
&self,
f: F,
) -> (
Arc<Component<C>>,
Future<Result<ActorPath, RegistrationError>>,
)
where
F: FnOnce() -> C,
C: ComponentDefinition + 'static,
{
// it will already check this twice...don't check it a third time
// self.inner.assert_active();
let c = self.create(f);
let r = self.register(&c);
(c, r)
}
// NOTE this was a terribly inconsistent API which hid a lot of possible failures away.
// If we feel we need a shortcut for create, register, start in the future, we should design
// a clearer and more reliable way of doing so.
// pub fn create_and_start<C, F>(&self, f: F) -> Arc<Component<C>>
// where
// F: FnOnce() -> C,
// C: ComponentDefinition + 'static,
// {
// self.inner.assert_active();
// let c = self.create(f);
// let path = PathResolvable::ActorId(c.core().id().clone());
// self.inner.register_by_path(&c, path);
// self.start(&c);
// c
// }
/// Attempts to register the provided component with a human-readable alias.
///
/// The returned future will contain the named [ActorPath](ActorPath)
/// for the given alias, once it is completed by the dispatcher.
///
/// # Note
///
/// While aliases are easier to read, lookup by unique ids is significantly more efficient.
/// However, named aliases allow services to be taken over by another component when the original registrant failed,
/// something that is not possible with unique paths. Thus, this kind of addressing lends itself to lookup-service
/// style components, for example.
///
/// # Example
///
/// ```
/// use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// use std::time::Duration;
/// let mut cfg = KompactConfig::new();
/// cfg.system_components(DeadletterBox::new, {
/// let net_config = NetworkConfig::new("127.0.0.1:0".parse().expect("Address should work"));
/// net_config.build()
/// });
/// let system = cfg.build().expect("KompactSystem");
/// let (c, unique_registration_future) = system.create_and_register(TestComponent1::new);
/// unique_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
/// let alias_registration_future = system.register_by_alias(&c, "test");
/// alias_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1 by alias");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn register_by_alias<C, A>(
&self,
c: &Arc<Component<C>>,
alias: A,
) -> Future<Result<ActorPath, RegistrationError>>
where
C: ComponentDefinition + 'static,
A: Into<String>,
{
self.inner.assert_active();
self.inner.register_by_alias(c, alias.into())
}
/// Start a component
///
/// A component only handles events/messages once it is started.
/// In particular, a component that isn't started shouldn't be scheduled and thus
/// access to its definition should always succeed,
/// for example via [on_definition](Component::on_definition).
///
/// # Example
///
/// ```
/// # use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// # let system = KompactConfig::default().build().expect("system");
/// let c = system.create(TestComponent1::new);
/// system.start(&c);
/// # system.shutdown().expect("shutdown");
/// ```
pub fn start<C>(&self, c: &Arc<Component<C>>) -> ()
where
C: ComponentDefinition + 'static,
{
self.inner.assert_not_poisoned();
c.enqueue_control(ControlEvent::Start);
}
/// Start a component and complete a future once it has started
///
/// When the returned future completes, the component is guaranteed to have started.
/// However, it is not guaranteed to be in an active state,
/// as it could already have been stopped or could have failed since.
///
/// A component only handles events/messages once it is started.
/// In particular, a component that isn't started shouldn't be scheduled and thus
/// access to its definition should always succeed,
/// for example via [on_definition](Component::on_definition).
///
/// # Example
///
/// ```
/// # use kompact::prelude::*;
/// # use kompact::doctest_helpers::*;
/// use std::time::Duration;
/// # let system = KompactConfig::default().build().expect("system");
/// let c = system.create(TestComponent1::new);
/// system.start_notify(&c)
/// .wait_timeout(Duration::from_millis(1000))
/// .expect("TestComponent1 never started!");
/// # system.shutdown().expect("shutdown");
/// ```
pub fn start_notify<C>(&self, c: &Arc<Component<C>>) -> Future<()>
where
C: ComponentDefinition + 'static,
{
self.inner.assert_active();
let (p, f) = utils::promise();
let amp = Arc::new(Mutex::new(p));