-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
supervisor.rs
1139 lines (1034 loc) · 37.1 KB
/
supervisor.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 crate::broadcast::{Broadcast, Parent, Sender};
use crate::children::{Children, ChildrenRef};
use crate::context::BastionId;
use crate::message::{BastionMessage, Deployment, Message};
use crate::system::schedule;
use futures::prelude::*;
use futures::stream::FuturesOrdered;
use futures::{pending, poll};
use fxhash::FxHashMap;
use lightproc::prelude::*;
use std::iter::FromIterator;
use std::ops::RangeFrom;
use std::task::Poll;
#[derive(Debug)]
/// A supervisor that can supervise both [`Children`] and other
/// supervisors using a defined [`SupervisionStrategy`] (set
/// with [`with_strategy`] or [`SupervisionStrategy::OneForOne`]
/// by default).
///
/// When a supervised children group or supervisor faults, the
/// supervisor will restart it and eventually some of its other
/// supervised entities, depending on its supervision strategy.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// let sp_ref: SupervisorRef = Bastion::supervisor(|sp| {
/// // Configure the supervisor...
/// sp.with_strategy(SupervisionStrategy::OneForOne)
/// // ...and return it.
/// }).expect("Couldn't create the supervisor.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Children`]: children/struct.Children.html
/// [`SupervisionStrategy`]: supervisor/enum.SupervisionStrategy.html
/// [`with_strategy`]: #method.with_strategy
pub struct Supervisor {
bcast: Broadcast,
// The order in which children and supervisors were added.
// It is only updated when at least one of those is resat.
order: Vec<BastionId>,
// The currently launched supervised children and supervisors.
launched: FxHashMap<BastionId, (usize, ProcHandle<Supervised>)>,
// Supervised children and supervisors that are stopped.
// This is used when resetting or recovering when the
// supervision strategy is not "one-for-one".
stopped: FxHashMap<BastionId, Supervised>,
strategy: SupervisionStrategy,
// Messages that were received before the supervisor was
// started. Those will be "replayed" once a start message
// is received.
pre_start_msgs: Vec<BastionMessage>,
started: bool,
}
#[derive(Debug, Clone)]
/// A "reference" to a [`Supervisor`], allowing to
/// communicate with it.
///
/// [`Supervisor`]: supervisor/struct.Supervisor.html
pub struct SupervisorRef {
id: BastionId,
sender: Sender,
}
#[derive(Debug, Clone)]
/// The strategy a supervisor should use when one of its
/// supervised children groups or supervisors dies (in
/// the case of a children group, it could be because one
/// of its elements panicked or returned an error).
///
/// The default strategy is `OneForOne`.
pub enum SupervisionStrategy {
/// When a children group dies (either because it got
/// killed, it panicked or returned an error), only
/// this group is restarted.
OneForOne,
/// When a children group dies (either because it got
/// killed, it panicked or returned an error), all the
/// children groups are restarted (even those which were
/// stopped) in the same order they were added to the
/// supervisor.
OneForAll,
/// When a children group dies (either because it got
/// killed, it panicked or returned an error), this
/// group and all the ones that were added to the
/// supervisor after it are restarted (even those which
/// were stopped) in the same order they were added to
/// the supervisor.
RestForOne,
}
#[derive(Debug)]
enum Supervised {
Supervisor(Supervisor),
Children(Children),
}
impl Supervisor {
pub(crate) fn new(bcast: Broadcast) -> Self {
let order = Vec::new();
let launched = FxHashMap::default();
let stopped = FxHashMap::default();
let strategy = SupervisionStrategy::default();
let pre_start_msgs = Vec::new();
let started = false;
Supervisor {
bcast,
order,
launched,
stopped,
strategy,
pre_start_msgs,
started,
}
}
fn stack(&self) -> ProcStack {
// FIXME: with_pid
ProcStack::default()
}
pub(crate) async fn reset(&mut self, bcast: Broadcast) {
// TODO: stop or kill?
let killed = self.kill(0..).await;
self.bcast = bcast;
self.pre_start_msgs.clear();
self.pre_start_msgs.shrink_to_fit();
let mut reset = FuturesOrdered::new();
for supervised in killed {
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
reset.push(async {
// FIXME: panics?
supervised.reset(bcast).await.unwrap()
})
}
while let Some(supervised) = reset.next().await {
let id = supervised.id().clone();
let launched = supervised.launch();
self.launched
.insert(id.clone(), (self.order.len(), launched));
self.order.push(id);
}
if self.started {
let msg = BastionMessage::start();
self.bcast.send_children(msg);
}
}
pub(crate) fn id(&self) -> &BastionId {
&self.bcast.id()
}
pub(crate) fn bcast(&self) -> &Broadcast {
&self.bcast
}
pub(crate) fn as_ref(&self) -> SupervisorRef {
// TODO: clone or ref?
let id = self.bcast.id().clone();
let sender = self.bcast.sender().clone();
SupervisorRef::new(id, sender)
}
/// Creates a new supervisor, passes it through the specified
/// `init` closure and then starts supervising it.
///
/// If you don't need to chain calls to this `Supervisor`'s methods
/// and need to get a [`SupervisorRef`] referencing the newly
/// created supervisor, use the [`supervisor_ref`] method instead.
///
/// # Arguments
///
/// * `init` - The closure taking the new supervisor as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # Bastion::supervisor(|parent| {
/// parent.supervisor(|sp| {
/// // Configure the supervisor...
/// sp.with_strategy(SupervisionStrategy::OneForOne)
/// // ...and return it.
/// })
/// # }).unwrap();
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`SupervisorRef`]: ../struct.SupervisorRef.html
/// [`supervisor_ref`]: #method.supervisor_ref
pub fn supervisor<S>(self, init: S) -> Self
where
S: FnOnce(Supervisor) -> Supervisor,
{
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let supervisor = Supervisor::new(bcast);
let supervisor = init(supervisor);
let msg = BastionMessage::deploy_supervisor(supervisor);
self.bcast.send_self(msg);
self
}
/// Creates a new `Supervisor`, passes it through the specified
/// `init` closure and then starts supervising it.
///
/// If you need to chain calls to this `Supervisor`'s methods and
/// don't need to get a [`SupervisorRef`] referencing the newly
/// created supervisor, use the [`supervisor`] method instead.
///
/// # Arguments
///
/// * `init` - The closure taking the new `Supervisor` as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # Bastion::supervisor(|mut parent| {
/// let sp_ref: SupervisorRef = parent.supervisor_ref(|sp| {
/// // Configure the supervisor...
/// sp.with_strategy(SupervisionStrategy::OneForOne)
/// // ...and return it.
/// });
/// # parent
/// # }).unwrap();
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`SupervisorRef`]: ../struct.SupervisorRef.html
/// [`supervisor`]: #method.supervisor
pub fn supervisor_ref<S>(&mut self, init: S) -> SupervisorRef
where
S: FnOnce(Supervisor) -> Supervisor,
{
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let supervisor = Supervisor::new(bcast);
let supervisor = init(supervisor);
let supervisor_ref = supervisor.as_ref();
let msg = BastionMessage::deploy_supervisor(supervisor);
self.bcast.send_self(msg);
supervisor_ref
}
/// Creates a new [`Children`], passes it through the specified
/// `init` closure and then starts supervising it.
///
/// If you don't need to chain calls to this `Supervisor`'s methods
/// and need to get a [`ChildrenRef`] referencing the newly
/// created supervisor, use the [`children`] method instead.
///
/// # Arguments
///
/// * `init` - The closure taking the new `Children` as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # Bastion::supervisor(|sp| {
/// sp.children(|children| {
/// children.with_exec(|ctx: BastionContext| {
/// async move {
/// // Send and receive messages...
/// let opt_msg: Option<Msg> = ctx.try_recv().await;
///
/// // ...and return `Ok(())` or `Err(())` when you are done...
/// Ok(())
/// // Note that if `Err(())` was returned, the supervisor would
/// // restart the children group.
/// }
/// })
/// })
/// # }).unwrap();
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Children`]: children/struct.Children.html
/// [`ChildrenRef`]: children/struct.ChildrenRef.html
/// [`children_ref`]: #method.children_ref
pub fn children<C>(self, init: C) -> Self
where
C: FnOnce(Children) -> Children,
{
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let children = Children::new(bcast);
let mut children = init(children);
children.launch_elems();
let msg = BastionMessage::deploy_children(children);
self.bcast.send_self(msg);
self
}
/// Creates a new [`Children`], passes it through the specified
/// `init` closure and then starts supervising it.
///
/// If you need to chain calls to this `Supervisor`'s methods and
/// don't need to get a [`ChildrenRef`] referencing the newly
/// created supervisor, use the [`children`] method instead.
///
/// # Arguments
///
/// * `init` - The closure taking the new `Children` as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # Bastion::supervisor(|mut sp| {
/// let children_ref: ChildrenRef = sp.children_ref(|children| {
/// children.with_exec(|ctx: BastionContext| {
/// async move {
/// // Send and receive messages...
/// let opt_msg: Option<Msg> = ctx.try_recv().await;
///
/// // ...and return `Ok(())` or `Err(())` when you are done...
/// Ok(())
/// // Note that if `Err(())` was returned, the supervisor would
/// // restart the children group.
/// }
/// })
/// });
/// # sp
/// # }).unwrap();
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Children`]: children/struct.Children.html
/// [`ChildrenRef`]: children/struct.ChildrenRef.html
/// [`children`]: #method.children
pub fn children_ref<C>(&self, init: C) -> ChildrenRef
where
C: FnOnce(Children) -> Children,
{
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let children = Children::new(bcast);
let mut children = init(children);
children.launch_elems();
let children_ref = children.as_ref();
let msg = BastionMessage::deploy_children(children);
self.bcast.send_self(msg);
children_ref
}
/// Sets the strategy the supervisor should use when one
/// of its supervised children groups or supervisors dies
/// (in the case of a children group, it could be because one
/// of its elements panicked or returned an error).
///
/// The default strategy is
/// [`SupervisorStrategy::OneForOne`].
///
/// # Arguments
///
/// * `strategy` - The strategy to use:
/// - [`SupervisionStrategy::OneForOne`] would only restart
/// the supervised children groups or supervisors that
/// fault.
/// - [`SupervisionStrategy::OneForAll`] would restart all
/// the supervised children groups or supervisors (even
/// those which were stopped) when one of them faults,
/// respecting the order in which they were added.
/// - [`SupervisionStrategy::RestForOne`] would restart the
/// supervised children groups or supervisors that fault
/// along with all the other supervised children groups
/// or supervisors that were added after them (even the
/// stopped ones), respecting the order in which they
/// were added.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// Bastion::supervisor(|sp| {
/// // Note that "one-for-one" is the default strategy.
/// sp.with_strategy(SupervisionStrategy::OneForOne)
/// }).expect("Couldn't create the supervisor");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`SupervisionStrategy::OneForOne`]: supervisor/enum.SupervisionStrategy.html#variant.OneForOne
/// [`SupervisionStrategy::OneForAll`]: supervisor/enum.SupervisionStrategy.html#variant.OneForAll
/// [`SupervisionStrategy::RestForOne`]: supervisor/enum.SupervisionStrategy.html#variant.RestForOne
pub fn with_strategy(mut self, strategy: SupervisionStrategy) -> Self {
self.strategy = strategy;
self
}
async fn stop(&mut self, range: RangeFrom<usize>) -> Vec<Supervised> {
if range.start == 0 {
self.bcast.stop_children();
} else {
// FIXME: panics
for id in self.order.get(range.clone()).unwrap() {
self.bcast.stop_child(id);
}
}
self.collect(range).await
}
async fn kill(&mut self, range: RangeFrom<usize>) -> Vec<Supervised> {
if range.start == 0 {
self.bcast.kill_children();
} else {
// FIXME: panics
for id in self.order.get(range.clone()).unwrap() {
self.bcast.kill_child(id);
}
}
self.collect(range).await
}
fn stopped(&mut self) {
self.bcast.stopped();
}
fn faulted(&mut self) {
self.bcast.faulted();
}
async fn collect(&mut self, range: RangeFrom<usize>) -> Vec<Supervised> {
let mut supervised = Vec::new();
// FIXME: panics?
for id in self.order.get(range).unwrap() {
// TODO: Err if None?
if let Some((_, launched)) = self.launched.remove(&id) {
// TODO: add a "stopped" list and poll from it instead of awaiting
supervised.push(launched);
}
}
let supervised = FuturesOrdered::from_iter(supervised.into_iter().rev());
let mut supervised = supervised.collect::<Vec<_>>().await;
let mut collected = Vec::with_capacity(supervised.len());
for id in self.order.drain(..) {
if let Some(supervised) = self.stopped.remove(&id) {
collected.push(supervised);
continue;
}
match supervised.pop() {
Some(Some(supervised)) if supervised.id() == &id => {
collected.push(supervised);
}
// FIXME
Some(Some(_)) => unimplemented!(),
// FIXME
Some(None) => unimplemented!(),
// FIXME
None => unimplemented!(),
}
}
collected
}
async fn recover(&mut self, id: BastionId) -> Result<(), ()> {
match self.strategy {
SupervisionStrategy::OneForOne => {
let (order, launched) = self.launched.remove(&id).ok_or(())?;
// TODO: add a "waiting" list and poll from it instead of awaiting
// FIXME: panics?
let supervised = launched.await.unwrap();
self.bcast.unregister(supervised.id());
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let id = bcast.id().clone();
// FIXME: panics?
let supervised = supervised.reset(bcast).await.unwrap();
self.bcast.register(supervised.bcast());
if self.started {
let msg = BastionMessage::start();
self.bcast.send_child(&id, msg);
}
let launched = supervised.launch();
self.launched.insert(id.clone(), (order, launched));
self.order[order] = id;
}
SupervisionStrategy::OneForAll => {
// TODO: stop or kill?
for supervised in self.kill(0..).await {
self.bcast.unregister(supervised.id());
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let id = bcast.id().clone();
// FIXME: panics.
let supervised = supervised.reset(bcast).await.unwrap();
self.bcast.register(supervised.bcast());
let launched = supervised.launch();
self.launched
.insert(id.clone(), (self.order.len(), launched));
self.order.push(id);
}
if self.started {
let msg = BastionMessage::start();
self.bcast.send_children(msg);
}
}
SupervisionStrategy::RestForOne => {
let (order, _) = self.launched.get(&id).ok_or(())?;
let order = *order;
// TODO: stop or kill?
for supervised in self.kill(order..).await {
self.bcast.unregister(supervised.id());
let parent = Parent::supervisor(self.as_ref());
let bcast = Broadcast::new(parent);
let id = bcast.id().clone();
// FIXME: panics?
let supervised = supervised.reset(bcast).await.unwrap();
self.bcast.register(supervised.bcast());
if self.started {
let msg = BastionMessage::start();
self.bcast.send_child(&id, msg);
}
let launched = supervised.launch();
self.launched
.insert(id.clone(), (self.order.len(), launched));
self.order.push(id);
}
}
}
Ok(())
}
async fn handle(&mut self, msg: BastionMessage) -> Result<(), ()> {
match msg {
BastionMessage::Start => unreachable!(),
BastionMessage::Stop => {
self.stop(0..).await;
self.stopped();
return Err(());
}
BastionMessage::Kill => {
self.kill(0..).await;
self.stopped();
return Err(());
}
BastionMessage::Deploy(deployment) => match deployment {
Deployment::Supervisor(supervisor) => {
self.bcast.register(&supervisor.bcast);
if self.started {
let msg = BastionMessage::start();
self.bcast.send_child(supervisor.id(), msg);
}
let id = supervisor.id().clone();
let supervised = Supervised::supervisor(supervisor);
let launched = supervised.launch();
self.launched
.insert(id.clone(), (self.order.len(), launched));
self.order.push(id);
}
Deployment::Children(children) => {
self.bcast.register(children.bcast());
if self.started {
let msg = BastionMessage::start();
self.bcast.send_child(children.id(), msg);
}
let id = children.id().clone();
let supervised = Supervised::children(children);
let launched = supervised.launch();
self.launched
.insert(id.clone(), (self.order.len(), launched));
self.order.push(id);
}
},
// FIXME
BastionMessage::Prune { .. } => unimplemented!(),
BastionMessage::SuperviseWith(strategy) => {
self.strategy = strategy;
}
BastionMessage::Message(_) => {
self.bcast.send_children(msg);
}
BastionMessage::Stopped { id } => {
// FIXME: Err if None?
if let Some((_, launched)) = self.launched.remove(&id) {
// TODO: add a "waiting" list an poll from it instead of awaiting
// FIXME: panics?
let supervised = launched.await.unwrap();
self.bcast.unregister(&id);
self.stopped.insert(id, supervised);
}
}
BastionMessage::Faulted { id } => {
if self.recover(id).await.is_err() {
self.kill(0..).await;
self.faulted();
return Err(());
}
}
}
Ok(())
}
async fn run(mut self) -> Self {
loop {
match poll!(&mut self.bcast.next()) {
// TODO: Err if started == true?
Poll::Ready(Some(BastionMessage::Start)) => {
self.started = true;
let msg = BastionMessage::start();
self.bcast.send_children(msg);
let msgs = self.pre_start_msgs.drain(..).collect::<Vec<_>>();
self.pre_start_msgs.shrink_to_fit();
for msg in msgs {
if self.handle(msg).await.is_err() {
return self;
}
}
}
Poll::Ready(Some(msg)) if !self.started => {
self.pre_start_msgs.push(msg);
}
Poll::Ready(Some(msg)) => {
if self.handle(msg).await.is_err() {
return self;
}
}
Poll::Ready(None) => {
// TODO: stop or kill?
self.kill(0..).await;
self.faulted();
return self;
}
Poll::Pending => pending!(),
}
}
}
pub(crate) fn launch(self) -> ProcHandle<Self> {
let stack = self.stack();
let (proc, handle) = LightProc::build(self.run(), schedule, stack);
proc.schedule();
handle
}
}
impl SupervisorRef {
pub(crate) fn new(id: BastionId, sender: Sender) -> Self {
SupervisorRef { id, sender }
}
/// Creates a new [`Supervisor`], passes it through the specified
/// `init` closure and then sends it to the supervisor this
/// `SupervisorRef` is referencing to supervise it.
///
/// This method returns a [`SupervisorRef`] referencing the newly
/// created supervisor if it succeeded, or `Err(())`
/// otherwise.
///
/// # Arguments
///
/// * `init` - The closure taking the new [`Supervisor`] as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # let mut parent_ref = Bastion::supervisor(|sp| sp).unwrap();
/// let sp_ref: SupervisorRef = parent_ref.supervisor(|sp| {
/// // Configure the supervisor...
/// sp.with_strategy(SupervisionStrategy::OneForOne)
/// // ...and return it.
/// }).expect("Couldn't create the supervisor.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Supervisor`]: supervisor/struct.Supervisor.html
pub fn supervisor<S>(&self, init: S) -> Result<Self, ()>
where
S: FnOnce(Supervisor) -> Supervisor,
{
let parent = Parent::supervisor(self.clone());
let bcast = Broadcast::new(parent);
let supervisor = Supervisor::new(bcast);
let supervisor = init(supervisor);
let supervisor_ref = supervisor.as_ref();
let msg = BastionMessage::deploy_supervisor(supervisor);
self.send(msg).map_err(|_| ())?;
Ok(supervisor_ref)
}
/// Creates a new [`Children`], passes it through the specified
/// `init` closure and then sends it to the supervisor this
/// `SupervisorRef` is referencing to supervise it.
///
/// This methods returns a [`ChildrenRef`] referencing the newly
/// created children group it it succeeded, or `Err(())`
/// otherwise.
///
/// # Arguments
///
/// * `init` - The closure taking the new [`Children`] as an
/// argument and returning it once configured.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # let sp_ref = Bastion::supervisor(|sp| sp).unwrap();
/// let children_ref: ChildrenRef = sp_ref.children(|children| {
/// children.with_exec(|ctx: BastionContext| {
/// async move {
/// // Send and receive messages...
/// let opt_msg: Option<Msg> = ctx.try_recv().await;
///
/// // ...and return `Ok(())` or `Err(())` when you are done...
/// Ok(())
/// // Note that if `Err(())` was returned, the supervisor would
/// // restart the children group.
/// }
/// })
/// }).expect("Couldn't create the children group.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`Children`]: children/struct.Children.html
/// [`ChildrenRef`]: children/struct.ChildrenRef.html
pub fn children<C>(&self, init: C) -> Result<ChildrenRef, ()>
where
C: FnOnce(Children) -> Children,
{
let parent = Parent::supervisor(self.clone());
let bcast = Broadcast::new(parent);
let children = Children::new(bcast);
let mut children = init(children);
children.launch_elems();
let children_ref = children.as_ref();
let msg = BastionMessage::deploy_children(children);
self.send(msg).map_err(|_| ())?;
Ok(children_ref)
}
/// Sends to the supervisor this `SupervisorRef` is
/// referencing the strategy that it should start
/// using when one of its supervised children groups or
/// supervisors dies (in the case of a children group,
/// it could be because one of its elements panicked or
/// returned an error).
///
/// The default strategy `Supervisor` is
/// [`SupervisorStrategy::OneForOne`].
///
/// This method returns `()` if it succeeded, or `Err(())`
/// otherwise.
///
/// # Arguments
///
/// * `strategy` - The strategy to use:
/// - [`SupervisionStrategy::OneForOne`] would only restart
/// the supervised children groups or supervisors that
/// fault.
/// - [`SupervisionStrategy::OneForAll`] would restart all
/// the supervised children groups or supervisors (even
/// those which were stopped) when one of them faults,
/// respecting the order in which they were added.
/// - [`SupervisionStrategy::RestForOne`] would restart the
/// supervised children groups or supervisors that fault
/// along with all the other supervised children groups
/// or supervisors that were added after them (even the
/// stopped ones), respecting the order in which they
/// were added.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # let sp_ref = Bastion::supervisor(|sp| sp).unwrap();
/// // Note that "one-for-one" is the default strategy.
/// sp_ref.strategy(SupervisionStrategy::OneForOne);
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
///
/// [`SupervisionStrategy::OneForOne`]: supervisor/enum.SupervisionStrategy.html#variant.OneForOne
/// [`SupervisionStrategy::OneForAll`]: supervisor/enum.SupervisionStrategy.html#variant.OneForAll
/// [`SupervisionStrategy::RestForOne`]: supervisor/enum.SupervisionStrategy.html#variant.RestForOne
pub fn strategy(&self, strategy: SupervisionStrategy) -> Result<(), ()> {
let msg = BastionMessage::supervise_with(strategy);
self.send(msg).map_err(|_| ())
}
/// Sends a message to the supervisor this `SupervisorRef`
/// is referencing which will then send it to all of its
/// supervised children groups and supervisors.
///
/// This method returns `()` if it succeeded, or `Err(msg)`
/// otherwise.
///
/// # Arguments
///
/// * `msg` - The message to send.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # let sp_ref = Bastion::supervisor(|sp| sp).unwrap();
/// let msg = "A message containing data.";
/// sp_ref.broadcast(msg).expect("Couldn't send the message.");
///
/// # Bastion::children(|children| {
/// # children.with_exec(|ctx: BastionContext| {
/// # async move {
/// // And then in every future of the elements of the children
/// // groups that are supervised by this supervisor or one of
/// // its supervised supervisors (etc.)...
/// msg! { ctx.recv().await?,
/// ref msg: &'static str => {
/// assert_eq!(msg, &"A message containing data.");
/// };
/// // We are only broadcasting a `&'static str` in this
/// // example, so we know that this won't happen...
/// _: _ => ();
/// }
/// #
/// # Ok(())
/// # }
/// # })
/// # }).unwrap();
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// # }
/// ```
pub fn broadcast<M: Message>(&self, msg: M) -> Result<(), M> {
let msg = BastionMessage::broadcast(msg);
// FIXME: panics?
self.send(msg).map_err(|msg| msg.into_msg().unwrap())
}
/// Sends a message to the supervisor this `SupervisorRef`
/// is referencing to tell it to stop every running children
/// groups and supervisors that it is supervising.
///
/// This method returns `()` if it succeeded, or `Err(())`
/// otherwise.
///
/// # Example
///
/// ```
/// # use bastion::prelude::*;
/// #
/// # fn main() {
/// # Bastion::init();
/// #
/// # let sp_ref = Bastion::supervisor(|sp| sp).unwrap();
/// sp_ref.stop().expect("Couldn't send the message.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();