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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! actor-level execution state and local environment
//! during runtime
//!
//! Context starts before actor get created, and dropped
//! after actor closed, its lifecycle covers actor's.
//!
//! It kind of serves as a back-end of the actor, and
//! almost all actor methods get called with Context.
//!
#[cfg(not(feature = "log"))]
use crate::log;
#[cfg(feature = "time")]
use crate::time::Timing;
use crate::{
actor::{ActingState, Actor, ActorId, ActorState, Future, Handle, Localizer},
address::{Addr, Pack, QueueError, Receiver, Sender},
blocker::{Blocker, Blocking},
delayer::{Delayer, Delaying, Indicator},
message::{MStream, MStreaming, Message},
reactor::{inc_poll_budget, Reactor, ReactorPair},
register::ActorGuard,
stream::{Stream, Streaming},
};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
#[cfg(feature = "time")]
use core::time::Duration;
use core::{
any::Any,
fmt,
future::Future as CoreFuture,
pin::Pin,
ptr::NonNull,
task::{Context as CoreContext, Poll},
};
use futures_core::stream::Stream as CoreStream;
struct Pair<A> {
inner: Pin<Box<dyn Future<A, Output = ()>>>,
handle: Handle,
}
impl<A> fmt::Debug for Pair<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pair")
.field("inner", &"Pin<Box<Future<_>>>")
.field("handle", &self.handle)
.finish()
}
}
/// execution state and local environment
/// for actor during runtime
pub struct Context<A: Actor> {
/// the unique id of the actor
/// created when the actor
/// get registered
id: ActorId,
/// task queue
inner: Vec<Pair<A>>,
pack: Arc<Pack<A::Message>>,
bloc: Vec<Pair<A>>,
state: ActorState,
abortion: Vec<Handle>,
/// used to get access to the
/// inner futures of ContextRunner
///
/// **Safety**: ONLY the following
/// fields are allowed to be modified
/// - ContextRunner.inner
/// - ContextRunner.bloc
///
/// `ContextRunner.act` is okay
/// for reference
/// other field `ContextRunner.ctx`
/// ARE NOT ALLOED to access even
/// to get a shareable reference
tunnel: Option<NonNull<ContextRunner<A>>>,
}
impl<A: Actor> fmt::Debug for Context<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context<_>")
.field("id", &self.id)
.field("inner", &self.inner)
.field("pack", &self.pack)
.field("bloc", &self.bloc)
.field("state", &self.state)
.field("abortion", &self.abortion)
.field("tunnel", &self.tunnel)
.finish()
}
}
impl<A: Actor> Context<A> {
/// create an instance of Context
///
/// ```
/// struct CrossBus {}
/// impl Actor for CrossBus {
/// ...
/// }
///
/// let ctx = Context::<CrossBus>::new();
/// let addr = ctx.address();
/// ```
pub fn new() -> Self {
let pack = Pack::new();
Self {
id: 0,
pack,
state: ActorState::Created,
bloc: Vec::new(),
inner: Vec::new(),
abortion: Vec::new(),
tunnel: None,
}
}
/// get the address of the actor
/// what can laterly get access
/// to `Sender` or `Receiver`
///
/// ```
/// let addr = ctx.address();
/// let sender = addr.clone().sender();
/// let receiver = addr.receiver();
/// ...
/// ```
pub fn address(&self) -> Addr<A::Message> {
Addr::new(self.pack.clone())
}
/// get the id of the actor
/// that owns this Context
pub fn id(&self) -> ActorId {
self.id
}
/// set the id of the actor
/// that owns this Context
pub(crate) fn set_id(&mut self, id: usize) {
self.id = id;
}
/// spawn a new future for execution
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// async fn run() {
/// // do work here
/// }
///
/// impl Actor for CrossBus {
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// // spawn the `run` for execution
/// let dur = core::time::Duration::from_secs(1);
/// let local = Localizer::new(run());
/// ctx.spawn(local);
/// }
/// }
/// ```
pub fn spawn<F>(&mut self, f: F) -> Handle
where
F: Future<A, Output = ()> + 'static,
{
let handle = Handle::new();
let pair = Pair {
inner: Box::pin(f),
handle,
};
self.inner.push(pair);
handle
}
/// block the actor from receiving message
/// until the spawned future is completed
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// impl Actor for CrossBus {
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// // block the actor for 1 second
/// let dur = core::time::Duration::from_secs(1);
/// let sleep_fut = tokio::time::sleep(dur);
/// let local = Localizer::new(sleep_fut);
/// ctx.blocking(local);
/// }
/// }
/// ```
pub fn blocking<F>(&mut self, f: F) -> Handle
where
F: Future<A, Output = ()> + 'static,
A: Blocking<A>,
{
let target = Blocker::new(f);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.bloc.push(pair);
handle
}
/// block the actor from receiving message
/// with specified duration
///
/// feature **`time`** must be enabled
/// and the [Timing](`Timing`) implementation
/// is required with which the actor can know
/// the time
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// impl Actor for CrossBus {
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// // block the actor for 1 second
/// let dur = core::time::Duration::from_secs(1);
/// ctx.blocking_duration::<std::time::Instant>(dur);
/// }
/// }
/// ```
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub fn blocking_duration<T>(&mut self, duration: Duration) -> Handle
where
A: Blocking<A>,
T: Timing + 'static,
{
let target = Blocker::from_duration::<T>(duration);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.bloc.push(pair);
handle
}
/// send message to the queue
///
/// messages may be rejected when actor is
/// blocked or message queue is full/closed
///
/// ```no_run rust
/// struct Num(uisze);
/// impl Message for Num {}
///
/// struct CrossBus{
/// sum: isize
/// }
/// impl Actor for CrossBus {
/// type Message = Num;
///
/// fn create(ctx: &mut Context<Self>) -> Self {
/// Self { sum: 0, }
/// }
///
/// fn started(&mut self, ctx: &mut Context<Self>) {
/// ctx.send_message(Num(1));
/// ctx.send_message(Num(1));
/// ctx.send_message(Num(1));
/// }
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// self.sum += msg.0;
/// }
/// }
///
///
pub fn send_message(&mut self, msg: A::Message) -> Result<(), QueueError<A::Message>>
where
A::Message: Message + Send + 'static,
{
self.sender().send(msg)
}
/// send a batch of messages to the queue
///
/// messages may be rejected when actor is
/// blocked or message queue is full/closed
///
/// ```no_run rust
/// ...
/// fn started(&mut self, ctx: &mut Context<Self>) {
/// ctx.send_message_batch(vec![Num(1), Num(1), Num(1)]);
/// }
/// ...
/// ```
pub fn send_message_batch(
&mut self,
msgs: Vec<A::Message>,
) -> Vec<Result<(), QueueError<A::Message>>>
where
A::Message: Message + Send + 'static,
{
msgs.into_iter().map(|msg| self.send_message(msg)).collect()
}
/// send and execute normal [future](`CoreFuture`)
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// // returns unit type `()`
/// async fn run() {
/// // do work here
/// }
///
/// impl Actor for CrossBus {
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// let dur = core::time::Duration::from_secs(1);
/// ctx.send_future(run());
/// }
/// }
/// ```
pub fn send_future<F>(&mut self, fut: F) -> Handle
where
F: CoreFuture<Output = ()> + 'static,
{
let local = Localizer::new(fut);
let handle = Handle::new();
let pair = Pair {
inner: Box::pin(local),
handle,
};
self.inner.push(pair);
handle
}
/// instantly deliver a message
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
///
/// ```no_run rust
/// ...
/// fn started(&mut self, ctx: &mut Context<Self>) {
/// ctx.instant_message(Num(1));
/// }
/// ...
/// ```
pub fn instant_message(&mut self, msg: A::Message) -> Handle
where
A::Message: Message + Unpin + 'static,
A: Delaying<A>,
{
let target = Delayer::instant(msg);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// deliver a message with specified duration delay
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
///
/// feature **`time`** must be enabled
/// and the [Timing](`Timing`) implementation
/// is required with which the actor can know
/// the time
///
/// ```no_run rust
/// ...
/// fn started(&mut self, ctx: &mut Context<Self>) {
/// let dur = core::time::Duration::from_secs(1);
/// ctx.delay_message(Num(1), dur);
/// }
/// ...
/// ```
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub fn delay_message<T: Timing + 'static>(&mut self, msg: A::Message, delay: Duration) -> Handle
where
A::Message: Message + Unpin + 'static,
A: Delaying<A>,
{
let target = Delayer::from_duration::<T>(msg, delay);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// deliver a message with specified function that
/// it will be delayed as long as the `f` returns
/// Poll::Pending
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
pub fn delay_message_fn<F>(&mut self, msg: A::Message, f: F) -> Handle
where
A::Message: Message + Unpin + 'static,
A: Delaying<A>,
F: FnMut(&mut A, &mut Context<A>, &mut CoreContext<'_>) -> Poll<Indicator<A::Message>>
+ 'static
+ Unpin,
{
let target = Delayer::from_fn(Some(msg), f);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// repeatedly deliver a message with specified times
/// and interval duration
///
/// feature **`time`** must be enabled
/// and the [Timing](`Timing`) implementation
/// is required with which the actor can know
/// the time
///
/// **Safety**: Since consuming `message` couple times
/// involving memory safety, message mutating is **NOT**
/// allowed here!
/// eg it's ILLEGAL to mutate it in [Actor::action](crate::actor::Actor::action) or
/// somewhere else, or else it could lead to unexpected
/// behavior. It's caller's responsibility to prevent these
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
///
/// the argument `repeats` is `usize`, has three scenarios:
/// - None: Infinitely deliver the message
/// - Some(0): Just deliver the message **Once**
/// - Some(number): Deliver the message `number` times
///
/// ```no_run rust
/// ...
/// fn started(&mut self, ctx: &mut Context<Self>) {
/// // repeat 3 times send message with 1s interval
/// let dur = core::time::Duration::from_secs(1);
/// ctx.repeat_message(Num(1), Some(dur), Some(3));
/// }
/// ...
/// ```
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub unsafe fn repeat_message<T: Timing + 'static>(
&mut self,
message: A::Message,
dur: Option<Duration>,
repeats: Option<usize>,
) -> Handle
where
A::Message: Message + Unpin + 'static,
A: Delaying<A>,
{
let target = unsafe { Delayer::repeat::<T>(message, dur, repeats) };
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// deliver a message with specified
/// function that it will be delayed
/// as long as the `f` returns Poll::Pending
///
/// the function's Output **MUST** be `Indicator::Message`
/// if not, it will log out the error,
/// and gets ignored
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
pub fn delay_fn<F>(&mut self, f: F) -> Handle
where
A::Message: Message + Unpin + 'static,
A: Delaying<A>,
F: FnMut(&mut A, &mut Context<A>, &mut CoreContext<'_>) -> Poll<Indicator<A::Message>>
+ 'static
+ Unpin,
{
let target = Delayer::from_fn(None, f);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// spawn a stream into the actor
///
/// **NOTE** that the stream item
/// will be processed by [`Stream::action`](`Stream::action`)
/// **NOT** [`Actor::action`](`Actor::action`)
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Stream::action](crate::stream::Stream::action) directly
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// struct St { items: Vec<i32> }
/// impl Stream for St {
/// // impl stream for St here
/// ...
/// }
///
/// impl Actor for CrossBus {
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// // spawn stream
/// let st = St {items: vec![1, 1, 1]};
/// ctx.streaming(st);
/// }
/// }
/// ```
pub fn streaming<S>(&mut self, s: S) -> Handle
where
S: CoreStream + 'static,
A: Stream<S::Item>,
{
let target = Streaming::new(s);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// spawn a message stream into the actor
///
/// **NOTE** that the stream item is message
/// will be processed by [`Actor::action`](`Actor::action`)
/// **NOT** [`Stream::action`](`Stream::action`)
///
/// **NOTE** that the message bypass the message queue
/// and get handled by [Actor::action](crate::actor::Actor::action) directly
///
/// ``` no_run rust
/// use crossbus::prelude::*;
///
/// struct St { items: Vec<i32> }
/// impl Stream for St {
/// // impl stream for St here
/// ...
/// }
///
/// impl Actor for CrossBus {
///
/// fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>) {
/// // spawn stream
/// let st = St {items: vec![Num(1), Num(1), Num(1)]};
/// ctx.streaming(st);
/// }
/// }
/// ```
pub fn streaming_message<S>(&mut self, s: S) -> Handle
where
A: Actor<Message = S::Item> + MStream<S::Item>,
S: CoreStream + 'static,
S::Item: Message,
{
let target = MStreaming::new(s);
let handle = target.handle();
let pair = Pair {
inner: Box::pin(target),
handle,
};
self.inner.push(pair);
handle
}
/// get the sender of the actor
pub fn sender(&self) -> Sender<A::Message> {
self.pack.inc_sender(1);
self.pack.set_alive();
inc_poll_budget(2);
Sender {
pack: self.pack.clone(),
}
}
/// get the receiver of the actor
pub fn receiver(&self) -> Receiver<A::Message> {
Receiver {
pack: self.pack.clone(),
}
}
// TODO: maybe impl it with `tunnel`
/// abort a future
pub fn abort_future(&mut self, handle: Handle) {
self.abortion.push(handle);
}
/// get the current state of the actor
pub fn state(&self) -> ActorState {
self.state.clone()
}
/// set the state of the actor
pub fn set_state(&mut self, state: ActorState) {
self.state = state;
}
///// whether the actor is started or not
//pub fn is_started(&self) -> bool {
//self.state.is_started()
//}
///// whether the actor is running state
//pub fn is_running(&self) -> bool {
//self.state == ActorState::Running
//}
/// run the actor
pub fn run(self, act: ActorGuard<A>) -> Addr<A::Message> {
let addr = self.address();
let runner = ContextRunner::new(self, act);
Reactor::push(ReactorPair::new(runner));
addr
}
///// whether the actor is in stopping or not
//pub fn is_stopping(&self) -> bool {
//self.state == ActorState::Stopping
//}
///// whether the actor is stopped or not
//pub fn is_stopped(&self) -> bool {
//self.state == ActorState::Stopped
//}
/// restart the context, it will
/// - flush all blockers
/// - flush all running tasks
/// but the message queue will survive
pub fn restart(&mut self) {
self.state = ActorState::Started;
self.inner.clear();
self.bloc.clear();
self.abortion.clear();
}
/// stop the context and the actor
///
/// it can be restored if `Actor::state`
/// returns `ActingState::Resume`
/// if not, the actor will be stopped
pub fn stop(&mut self) {
self.state = ActorState::Stopping;
}
/// downcast the inner future into
/// type `&T`, where `T` is one
/// of the following four types:
/// - [stream::Streaming](crate::stream::Streaming)
/// - [message::MStreaming](crate::message::MStreaming)
/// - [blocker::Blocker](crate::blocker::Blocker)
/// - [delayer::Delayer](crate::delayer::Delayer)
pub fn downcast_ref<T: 'static>(&self, handle: Handle) -> Option<&T> {
let runner: &ContextRunner<A> = (&self.tunnel)
// **Safety**: the inner data is guaranted
// to be not null
.and_then(|boxed| Some(unsafe { boxed.as_ref() }))
.unwrap();
for pair in runner.inner.iter() {
if pair.handle == handle {
return pair
.inner
.downcast_ref()
.and_then(|any_| any_.downcast_ref::<T>());
}
}
for pair in runner.bloc.iter() {
if pair.handle == handle {
return pair
.inner
.downcast_ref()
.and_then(|any_| any_.downcast_ref::<T>());
}
}
for pair in self.inner.iter() {
if pair.handle == handle {
return pair
.inner
.downcast_ref()
.and_then(|any_| any_.downcast_ref::<T>());
}
}
for pair in self.bloc.iter() {
if pair.handle == handle {
return pair
.inner
.downcast_ref()
.and_then(|any_| any_.downcast_ref::<T>());
}
}
None
}
/// downcast the inner future into
/// type `&mut T`, where `T` is one
/// of the following four types:
/// - [stream::Streaming](crate::stream::Streaming)
/// - [message::MStreaming](crate::message::MStreaming)
/// - [blocker::Blocker](crate::blocker::Blocker)
/// - [delayer::Delayer](crate::delayer::Delayer)
pub fn downcast_mut<T: 'static>(&mut self, handle: Handle) -> Option<Pin<&mut T>> {
let runner: &mut ContextRunner<A> = (&mut self.tunnel)
// **Safety**: the inner data is guaranted
// to be not null
.and_then(|mut boxed| Some(unsafe { boxed.as_mut() }))
.unwrap();
for pair in runner.inner.iter_mut() {
if pair.handle == handle {
let pin_dyn = (&mut pair.inner).as_mut().downcast_mut();
let pin_data = pin_dyn
.and_then(|en: Pin<&mut dyn Any>| -> Option<&mut T> {
// **Safety**: Since the inner data is guarded
// with `Pin<Box<_>>` So
// We can guarantee that the data will
// never be moved out via the mutable
// reference
unsafe { en.get_unchecked_mut() }.downcast_mut::<T>()
})
// **Safety**: the inner data is pinned
// So it is safe to create a new Pin
.and_then(|en| Some(unsafe { Pin::new_unchecked(en) }));
return pin_data;
}
}
for pair in runner.bloc.iter_mut() {
if pair.handle == handle {
let pin_dyn = (&mut pair.inner).as_mut().downcast_mut();
let pin_data = pin_dyn
.and_then(|en: Pin<&mut dyn Any>| -> Option<&mut T> {
// **Safety**: Since the inner data is guarded
// with `Pin<Box<_>>` So
// We can guarantee that the data will
// never be moved out via the mutable
// reference
unsafe { en.get_unchecked_mut() }.downcast_mut::<T>()
})
// **Safety**: the inner data is pinned
// So it is safe to create a new Pin
.and_then(|en| Some(unsafe { Pin::new_unchecked(en) }));
return pin_data;
}
}
for pair in self.inner.iter_mut() {
if pair.handle == handle {
let pin_dyn = (&mut pair.inner).as_mut().downcast_mut();
let pin_data = pin_dyn
.and_then(|en: Pin<&mut dyn Any>| -> Option<&mut T> {
// **Safety**: Since the inner data is guarded
// with `Pin<Box<_>>` So
// We can guarantee that the data will
// never be moved out via the mutable
// reference
unsafe { en.get_unchecked_mut() }.downcast_mut::<T>()
})
// **Safety**: the inner data is pinned
// So it is safe to create a new Pin
.and_then(|en| Some(unsafe { Pin::new_unchecked(en) }));
return pin_data;
}
}
for pair in self.bloc.iter_mut() {
if pair.handle == handle {
let pin_dyn = (&mut pair.inner).as_mut().downcast_mut();
let pin_data = pin_dyn
.and_then(|en: Pin<&mut dyn Any>| -> Option<&mut T> {
// **Safety**: Since the inner data is guarded
// with `Pin<Box<_>>` So
// We can guarantee that the data will
// never be moved out via the mutable
// reference
unsafe { en.get_unchecked_mut() }.downcast_mut::<T>()
})
// **Safety**: the inner data is pinned
// So it is safe to create a new Pin
.and_then(|en| Some(unsafe { Pin::new_unchecked(en) }));
return pin_data;
}
}
None
}
}
/// Future-oriented runner that drive all tasks into
/// completion
pub struct ContextRunner<A>
where
A: Actor,
{
act: ActorGuard<A>,
inner: Vec<Pair<A>>,
bloc: Vec<Pair<A>>,
ctx: Context<A>,
}
impl<A: Actor> fmt::Debug for ContextRunner<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ContextRunner<_>")
.field("act", &self.act)
.field("inner", &self.inner)
.field("bloc", &self.bloc)
.field("ctx", &self.ctx)
.finish()
}
}
impl<A: Actor> ContextRunner<A> {
/// create an instance
pub fn new(ctx: Context<A>, act: ActorGuard<A>) -> Self {
let mut runner = Self {
ctx,
act,
inner: Vec::new(),
bloc: Vec::new(),
};
runner.tunnel();
runner
}
/// **Safety**: **MUST** update the tunnel
/// when new items (inner future / bloc)
/// comes.
/// when the underlying data the
/// pointer refer to is changed
/// and downcasting the items
/// is **INVALID** and will panic
/// the program
pub(crate) fn tunnel(&mut self) {
self.ctx.tunnel = NonNull::new(self);
}
/// pull new actor futures from context
pub fn update(&mut self) -> bool {
let mut blocked = false;
let mut tunnel = false;
if !self.ctx.bloc.is_empty() {
blocked = true;
tunnel = true;
self.bloc.extend(self.ctx.bloc.drain(0..));
log::info!("move bloc future into runner, {}", self.bloc.len());
}
if !self.ctx.inner.is_empty() {
tunnel = true;
self.inner.extend(self.ctx.inner.drain(0..));
log::info!("move inner future into runner: {}", self.inner.len());
}
if !self.ctx.abortion.is_empty() {
tunnel = true;
'outer: while let Some(handle) = self.ctx.abortion.pop() {
// remove spawned handle in ContextRunner
for index in 0..self.inner.len() {
if self.inner[index].handle == handle {
self.inner.swap_remove(index);
continue 'outer;
}
}
// remove spawned handle in Context
for index in 0..self.ctx.inner.len() {
if self.ctx.inner[index].handle == handle {
self.ctx.inner.swap_remove(index);
continue 'outer;
}
}
}
}
//self.ctx.pack.update_state();
if tunnel {
self.tunnel();
}
blocked
}
pub(crate) fn to_stop(&self) -> bool {
match self.ctx.state {
ActorState::Stopped | ActorState::Stopping => true,
_ => false,
}
}
/// should the runner continue to be
/// alive or exit
pub fn is_alive(&self) -> bool {
if self.ctx.state == ActorState::Stopped {
return false;
}
self.ctx.pack.update_state();
self.ctx.pack.sender_number() != 0
|| self.ctx.pack.is_alive()
|| self.ctx.pack.is_closing()
|| !self.ctx.state.is_started()
|| !self.inner.is_empty()
|| !self.bloc.is_empty()
}
/// if the actor is blocked or not
pub fn is_blocked(&self) -> bool {
!self.bloc.is_empty()
}
}
unsafe impl<A: Actor> Send for ContextRunner<A> {}
unsafe impl<A: Actor> Sync for ContextRunner<A> {}
/// **Safety**: no technical guarantee that only
/// one mutable access when mutably borrow
/// `ActorGuard<A>` in `ContextRunner`.
/// but so far it is safe to use.
/// Since mutation only happens in `poll` and its
/// called-functions inside, and at most one mutable
/// access happens there.
//
// NOTE for future development, maybe seal the
// ActorGuard before mutable borrowing
// for more complex logic
impl<A> CoreFuture for ContextRunner<A>
where
A: Actor,
{
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut CoreContext<'_>) -> Poll<()> {
let this = self.get_mut();
match this.ctx.state {
// first poll
ActorState::Created => {
// even if the actor state is changed
// after executing it
// it is ignored though anyway
// the actor should step into Started state
// for this state change
A::initial(&mut this.act, &mut this.ctx);
log::debug!("Actor successfully created");
match A::state(&mut this.act, &mut this.ctx) {
ActingState::Stop => {
// stop the actor
this.ctx.state = ActorState::Stopping;
log::debug!("Actor Stopping when Created");
cx.waker().wake_by_ref();
return Poll::Pending;
}
ActingState::Abort => {
// abort the actor
this.ctx.state = ActorState::Aborted;
log::debug!("Actor Aborted when Created");
cx.waker().wake_by_ref();
return Poll::Pending;
}
_ => {}
}
// if actor gets a new blocker here
// the actor won't be blocked anyway
// the actor should step into Running state
// for this blocker
this.update();
this.ctx.state = ActorState::Started;
log::debug!("Actor successfully started");
cx.waker().wake_by_ref();
Poll::Pending
}
// actor has been started
ActorState::Started => {
match A::state(&mut this.act, &mut this.ctx) {
ActingState::Stop => {
// stop the actor
this.ctx.state = ActorState::Stopping;
log::debug!("Actor stopping when Started");
cx.waker().wake_by_ref();
return Poll::Pending;
}
ActingState::Abort => {
// abort the actor
this.ctx.state = ActorState::Aborted;
log::debug!("Actor Aborted when Started");
cx.waker().wake_by_ref();
return Poll::Pending;
}
_ => {}
}
A::started(&mut this.act, &mut this.ctx);
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Started {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
// if actor gets a new blocker here
// the actor won't be blocked anyway
// the actor should step into Running state
// for this blocker
this.update();
this.ctx.state = ActorState::Running;
log::debug!("Actor successfully Running");
cx.waker().wake_by_ref();
Poll::Pending
}
// actor is running
// this is the core part of actor future
// that drive all operations into completion
ActorState::Running => {
match A::state(&mut this.act, &mut this.ctx) {
ActingState::Stop => {
// stop the actor
this.ctx.state = ActorState::Stopping;
log::debug!("Actor Stopping when to Running");
cx.waker().wake_by_ref();
return Poll::Pending;
}
ActingState::Abort => {
// abort the actor
this.ctx.state = ActorState::Aborted;
log::debug!("Actor Aborted when Running");
cx.waker().wake_by_ref();
return Poll::Pending;
}
_ => {}
}
// running loop for execution
'ex: loop {
// if blocker exists in the context
// the actor is blocked
// the make the computation consistent
// the most recent blcoker has higher priority
while this.is_blocked() {
log::debug!("Actor blocked");
let bloc = this.bloc.last_mut().unwrap();
match bloc.inner.as_mut().poll(&mut this.act, &mut this.ctx, cx) {
Poll::Pending => {
//cx.waker().wake_by_ref();
return Poll::Pending;
}
Poll::Ready(()) => {
this.bloc.pop();
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Running {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
// update the incoming items
if this.update() {
continue 'ex;
}
}
}
}
// pull messages
match this.ctx.pack.poll_next(cx) {
Poll::Pending => {}
Poll::Ready(Some(msg)) => {
log::debug!("New message");
// new message has been pulled
// use it
A::action(&mut this.act, msg, &mut this.ctx);
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Running {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
// update the incoming items
if this.update() {
log::debug!("new blocker");
continue 'ex;
}
}
Poll::Ready(None) => {
log::trace!("message receiver empty");
// instinctively it suggests that the message
// channel is closed
//return Poll::
}
}
if this.is_blocked() {
log::debug!("New blocker");
continue 'ex;
}
// drive all the actor future into completion
//log::info!("runner: {:?} ", this);
let mut index = 0;
while index < this.inner.len() {
let pair = &mut this.inner[index];
match pair.inner.as_mut().poll(&mut this.act, &mut this.ctx, cx) {
// future is ready
Poll::Ready(()) => {
// remove completed futures
this.inner.swap_remove(index);
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Running {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
// to see if new blocker arrive or not
// if does go the beginning of the loop
if this.update() {
continue 'ex;
}
}
// future is not ready
Poll::Pending => {
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Running {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
// to see if new blocker arrive or not
// abort some futures if some
// if arrive, push the new blocker to
// the queue
// and go the beginning of the loop
if this.update() {
if this.is_blocked() && !this.to_stop() {
// NOTE swap the currrent item with
// the last item to exclude the
// case that polling same item
// all th time
// - it boosts the reliability
// of the runtime routine
let last = this.inner.len() - 1;
if last != index {
this.inner.swap(index, last);
}
continue 'ex;
}
}
// if not continue, go to the next item
index += 1;
}
}
}
// update the actor state
/*
*log::debug!("{:?}", &this.ctx.pack);
*log::debug!(
* "{:?}, {:?}, {:?}, {:?}, {:?}",
* this.ctx.pack.is_alive(),
* this.ctx.pack.is_closing(),
* !this.ctx.state.is_started(),
* !this.inner.is_empty(),
* !this.bloc.is_empty()
*);
*/
if !this.is_alive() {
log::debug!("Actor closing");
this.ctx.state = ActorState::Stopped;
}
return Poll::Pending;
}
}
// stopping the actor
// and reject all incoming items
// from context
// it can restored into running
// or turn into stopped status
ActorState::Stopping => {
match A::state(&mut this.act, &mut this.ctx) {
ActingState::Abort => {
// abort the actor
this.ctx.state = ActorState::Aborted;
log::debug!("Actor Aborted when Stopping");
cx.waker().wake_by_ref();
return Poll::Pending;
}
ActingState::Resume => {
// resume the actor
this.ctx.state = ActorState::Running;
log::debug!("Actor Resumed when Stopping");
cx.waker().wake_by_ref();
return Poll::Pending;
}
_ => {
// stop the actor
this.ctx.state = ActorState::Stopped;
log::debug!("Actor Stopped when Stopping");
cx.waker().wake_by_ref();
return Poll::Pending;
}
}
}
// actor is stopped, exit the program in a later
ActorState::Stopped => {
// update ContextRunner is not necessary
// since it is stopped, it is no need to
// update the new incoming blocker and futures
// TODO besides that the actor should reject
// all incoming messages/spawned futures
A::stopped(&mut this.act, &mut this.ctx);
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Stopped {
log::warn!("Actor state changed 9i09");
cx.waker().wake_by_ref();
return Poll::Pending;
}
log::debug!("Actor successfully Stopped");
// update ContextRunner is not necessary
A::close(&mut this.act, &mut this.ctx);
log::debug!("Actor successfully Closed");
Poll::Ready(())
}
// actor is aborted
// it will stop the actor immediately
ActorState::Aborted => {
// update ContextRunner is not necessary
// TODO clean-up/refresh the actor and Context
// and ContextRunner beforehand
A::aborted(&mut this.act, &mut this.ctx);
// the actor state is changed
// re-poll it
if this.ctx.state != ActorState::Aborted {
log::debug!("Actor state changed");
cx.waker().wake_by_ref();
return Poll::Pending;
}
log::debug!("Actor Aborted");
// update ContextRunner is
// not necessary here
//
// even if the actor state is changed
// after executing it
// it is ignored though anyway
// the actor will respond to state change
// before `Actor::close`
A::close(&mut this.act, &mut this.ctx);
log::debug!("Actor successfully Closed");
Poll::Ready(())
}
}
}
}