-
Notifications
You must be signed in to change notification settings - Fork 2
/
actor_impl.go
1540 lines (1304 loc) · 39.7 KB
/
actor_impl.go
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
package actorkit
import (
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/gokit/errors"
"github.com/gokit/es"
"github.com/gokit/xid"
)
const (
defaultWaitDuration = time.Second * 4
defaultDeadLockTicker = time.Second * 5
)
var (
// ErrActorBusyState is returned when an actor is processing a state request when another is made.
ErrActorBusyState = errors.New("Actor is busy with state (STOP|STOPCHILDREN|DESTROY|DESTROY)")
// ErrActorMustBeRunning is returned when an operation is to be done and the giving actor is not started.
ErrActorMustBeRunning = errors.New("Actor must be running")
// ErrActorHasNoBehaviour is returned when an is to start with no attached behaviour.
ErrActorHasNoBehaviour = errors.New("Actor must be running")
// ErrActorHasNoDiscoveryService is returned when actor has no discovery server.
ErrActorHasNoDiscoveryService = errors.New("Actor does not support discovery")
)
//********************************************************
// Behaviour Function
//********************************************************
// BehaviourFunc defines a function type which is wrapped by a
// type implementing the Behaviour interface to be used in a
// actor.
type BehaviourFunc func(Addr, Envelope)
// FromBehaviourFunc returns a new Behaviour from the function.
func FromBehaviourFunc(b BehaviourFunc) Behaviour {
return &behaviourFunctioner{fn: b}
}
type behaviourFunctioner struct {
fn BehaviourFunc
}
func (bh *behaviourFunctioner) Action(addr Addr, env Envelope) {
bh.fn(addr, env)
}
//********************************************************
// signal dummy
//********************************************************
var _ Signals = &signalDummy{}
type signalDummy struct{}
func (signalDummy) SignalState(_ Addr, _ Signal) {}
//********************************************************
// Actor Constructors
//********************************************************
// ActorOption defines a function which is runned against a pointer to a
// Prop which will be used for generating a actor's underline behaviour.
type ActorOption func(*Prop)
// ActorSpawner defines a function interface which takes a giving set of
// options returns a new instantiated Actor.
type ActorSpawner func(...ActorOption) Actor
// FromPartial returns a ActorSpawner which will be used for spawning new Actor using
// provided options both from the call to FromPartial and those passed to the returned function.
func FromPartial(namespace string, protocol string, ops ...ActorOption) ActorSpawner {
return func(more ...ActorOption) Actor {
var prop = new(Prop)
for _, op := range ops {
op(prop)
}
for _, op := range more {
op(prop)
}
return NewActorImpl(namespace, protocol, *prop)
}
}
// FromPartialFunc defines a giving function which can be supplied a function which will
// be called with provided ActorOption to be used for generating new actors for
// giving options.
func FromPartialFunc(partial func(string, string, ...ActorOption) Actor, pre ...ActorOption) func(string, string, ...ActorOption) Actor {
return func(namespace string, protocol string, ops ...ActorOption) Actor {
var prop = new(Prop)
for _, op := range pre {
op(prop)
}
for _, op := range ops {
op(prop)
}
return partial(namespace, protocol, pre...)
}
}
// From returns a new spawned and not yet started Actor based on provided ActorOptions.
func From(namespace string, protocol string, ops ...ActorOption) Actor {
var prop = new(Prop)
for _, op := range ops {
op(prop)
}
return NewActorImpl(namespace, protocol, *prop)
}
// FromFunc returns a new actor based on provided function.
func FromFunc(namespace string, protocol string, fn BehaviourFunc, ops ...ActorOption) Actor {
var prop = new(Prop)
for _, op := range ops {
op(prop)
}
prop.Behaviour = FromBehaviourFunc(fn)
actor := NewActorImpl(namespace, protocol, *prop)
return actor
}
// Func returns a Actor generating function which uses provided BehaviourFunc.
func Func(fn BehaviourFunc) func(string, string, ...ActorOption) Actor {
return FromPartialFunc(func(ns string, pr string, options ...ActorOption) Actor {
var prop = new(Prop)
for _, op := range options {
op(prop)
}
prop.Behaviour = FromBehaviourFunc(fn)
actor := NewActorImpl(ns, pr, *prop)
return actor
})
}
// Ancestor create an actor with a default DeadLetter behaviour, where this actor
// is the root node in a tree of actors. It is the entity by which all children
// spawned or discovered from it will be connected to, and allows a group control
// over them.
//
// Usually you always have one root or system actor per namespace (i.e host:port, ipv6, ..etc),
// then build off your child actors from of it, so do ensure to minimize the
// use of multiple system or ancestor actor roots.
//
// Remember all child actors spawned from an ancestor always takes its protocol and
// namespace.
func Ancestor(protocol string, namespace string, prop Prop) (Addr, error) {
if prop.Behaviour == nil {
prop.Behaviour = &DeadLetterBehaviour{}
}
actor := NewActorImpl(namespace, protocol, prop)
return AccessOf(actor), actor.Start()
}
// UseMailbox sets the mailbox to be used by the actor.
func UseMailbox(m Mailbox) ActorOption {
return func(ac *Prop) {
ac.Mailbox = m
}
}
// UseSignal applies giving signals to be used by
// generated actor.
func UseSignal(signal Signals) ActorOption {
return func(ac *Prop) {
ac.Signals = signal
}
}
// UseSentinel sets giving Sentinel provider for a actor.
func UseSentinel(sn Sentinel) ActorOption {
return func(ac *Prop) {
ac.Sentinel = sn
}
}
// UseDeadLetter sets giving deadletter as processor for death mails.
func UseDeadLetter(ml DeadLetter) ActorOption {
return func(ac *Prop) {
ac.DeadLetters = ml
}
}
// UseContextLog sets the Logs to be used by the actor.
func UseContextLog(cl ContextLogs) ActorOption {
return func(ac *Prop) {
ac.ContextLogs = cl
}
}
// UseSupervisor sets the supervisor to be used by the actor.
func UseSupervisor(s Supervisor) ActorOption {
return func(ac *Prop) {
ac.Supervisor = s
}
}
// UseEventStream sets the event stream to be used by the actor.
func UseEventStream(es EventStream) ActorOption {
return func(ac *Prop) {
ac.Event = es
}
}
// UseMailInvoker sets the mail invoker to be used by the actor.
func UseMailInvoker(mi MailInvoker) ActorOption {
return func(ac *Prop) {
ac.MailInvoker = mi
}
}
// UseBehaviour sets the behaviour to be used by a given actor.
func UseBehaviour(bh Behaviour) ActorOption {
return func(ac *Prop) {
ac.Behaviour = bh
}
}
// UseStateInvoker sets the state invoker to be used by the actor.
func UseStateInvoker(st StateInvoker) ActorOption {
return func(ac *Prop) {
ac.StateInvoker = st
}
}
// UseMessageInvoker sets the message invoker to be used by the actor.
func UseMessageInvoker(st MessageInvoker) ActorOption {
return func(ac *Prop) {
ac.MessageInvoker = st
}
}
//********************************************************
// ActorImpl
//********************************************************
var _ Actor = &ActorImpl{}
type actorSub struct {
Actor Actor
Sub Subscription
}
// BusyDuration defines the acceptable wait time for an actor
// to allow for calls to giving state functions like Restart, Stop
// Kill, Destroy before timeout, as an actor could be busy handling a
// different state transition request.
//BusyDuration time.Duration
// DeadLockDuration defines the custom duration to be used for the deadlock
// go-routine asleep issue, which may occur if all actor goroutines become idle.
// The default used is 5s, but if it brings performance costs, then this can be
// increased or decreased as desired for optimum performance.
//DeadLockDuration time.Duration
// ActorImpl implements the Actor interface.
type ActorImpl struct {
accessAddr Addr
props Prop
parent Actor
id xid.ID
namespace string
protocol string
state uint32
logger Logs
tree *ActorTree
deadLockDur time.Duration
busyDur time.Duration
death time.Time
created time.Time
failedDeliveryCount int64
failedRestartCount int64
restartedCount int64
deliveryCount int64
processedCount int64
stoppedCount int64
killedCount int64
registered int64
addActor chan Actor
rmActor chan Actor
signal chan struct{}
sentinelChan chan Addr
killChan chan chan error
stopChan chan chan error
destroyChan chan chan error
killChildrenChan chan chan error
restartChildrenChan chan chan error
stopChildrenChan chan chan error
destroyChildrenChan chan chan error
started *SwitchImpl
starting *SwitchImpl
destruction *SwitchImpl
processable *SwitchImpl
proc sync.WaitGroup
messages sync.WaitGroup
routines sync.WaitGroup
preStop PreStop
postStop PostStop
preRestart PreRestart
postRestart PostRestart
preStart PreStart
postStart PostStart
preDestroy PreDestroy
postDestroy PostDestroy
gsub *es.Subscription
sentinelSubs map[Addr]Subscription
subs map[Actor]Subscription
}
// NewActorImpl returns a new instance of an ActorImpl assigned giving protocol and service name.
func NewActorImpl(namespace string, protocol string, props Prop) *ActorImpl {
if namespace == "" {
namespace = "localhost"
}
if protocol == "" {
protocol = "kit"
}
if props.Behaviour == nil {
panic("Can have nil Behaviour")
}
ac := &ActorImpl{}
ac.protocol = protocol
ac.logger = &DrainLog{}
ac.namespace = namespace
ac.state = uint32(INACTIVE)
ac.deadLockDur = defaultDeadLockTicker
ac.busyDur = defaultWaitDuration
// add event provider.
if props.Event == nil {
props.Event = NewEventer()
}
if props.DeadLetters == nil {
props.DeadLetters = eventDeathMails
}
if props.Signals == nil {
props.Signals = &signalDummy{}
}
if tm, ok := props.Behaviour.(PreStart); ok {
ac.preStart = tm
} else {
ac.preStart = nil
}
if tm, ok := props.Behaviour.(PostStart); ok {
ac.postStart = tm
} else {
ac.postStart = nil
}
if tm, ok := props.Behaviour.(PreDestroy); ok {
ac.preDestroy = tm
} else {
ac.preDestroy = nil
}
if tm, ok := props.Behaviour.(PostDestroy); ok {
ac.postDestroy = tm
} else {
ac.postDestroy = nil
}
if tm, ok := props.Behaviour.(PreRestart); ok {
ac.preRestart = tm
} else {
ac.preRestart = nil
}
if tm, ok := props.Behaviour.(PostRestart); ok {
ac.postRestart = tm
} else {
ac.postRestart = nil
}
if tm, ok := props.Behaviour.(PreStop); ok {
ac.preStop = tm
} else {
ac.preStop = nil
}
if tm, ok := props.Behaviour.(PostStop); ok {
ac.postStop = tm
} else {
ac.postStop = nil
}
// add unbouned mailbox.
if props.Mailbox == nil {
props.Mailbox = UnboundedBoxQueue(props.MailInvoker)
}
// if we have no set provider then use a one-for-one strategy.
if props.Supervisor == nil {
props.Supervisor = &OneForOneSupervisor{
Max: 30,
Invoker: &EventSupervisingInvoker{
Event: ac.props.Event,
},
Decider: func(tm interface{}) Directive {
switch tm.(type) {
case PanicEvent:
return PanicDirective
default:
return RestartDirective
}
},
}
}
ac.props = props
ac.rmActor = make(chan Actor, 0)
ac.addActor = make(chan Actor, 0)
ac.signal = make(chan struct{}, 1)
ac.sentinelChan = make(chan Addr, 1)
ac.stopChan = make(chan chan error, 1)
ac.killChan = make(chan chan error, 1)
ac.destroyChan = make(chan chan error, 1)
ac.stopChildrenChan = make(chan chan error, 1)
ac.killChildrenChan = make(chan chan error, 1)
ac.restartChildrenChan = make(chan chan error, 1)
ac.destroyChildrenChan = make(chan chan error, 1)
ac.id = xid.New()
ac.started = NewSwitch()
ac.starting = NewSwitch()
ac.destruction = NewSwitch()
ac.accessAddr = AccessOf(ac)
ac.processable = NewSwitch()
ac.subs = map[Actor]Subscription{}
ac.tree = NewActorTree(10)
ac.processable.On()
// if we have ContextLogs, get a logger for yourself.
if props.ContextLogs != nil {
ac.logger = props.ContextLogs.Get(ac)
}
return ac
}
// Wait implements the Waiter interface.
func (ati *ActorImpl) Wait() {
ati.proc.Wait()
}
// State returns the current state of giving actor in a safe-concurrent
// manner.
func (ati *ActorImpl) State() Signal {
return Signal(atomic.LoadUint32(&ati.state))
}
// setState sets the new state for the actor.
func (ati *ActorImpl) setState(ns Signal) {
atomic.StoreUint32(&ati.state, uint32(ns))
}
func (ati *ActorImpl) resetState() {
atomic.StoreUint32(&ati.state, 0)
}
// ID returns associated string version of id.
func (ati *ActorImpl) ID() string {
return ati.id.String()
}
// Mailbox returns actors underline mailbox.
func (ati *ActorImpl) Mailbox() Mailbox {
return ati.props.Mailbox
}
// GetAddr returns the child of this actor which has this address string version.
//
// This method is more specific and will not respect or handle a address which
// the root ID is not this actor's identification ID. It heavily relies on walking
// the address tree till it finds the target actor or there is found no matching actor
//
func (ati *ActorImpl) GetAddr(addr string) (Addr, error) {
return nil, nil
}
// GetChild returns the child of this actor which has this matching id.
//
// If the sub is provided, then the function will drill down the provided
// target actor getting the child actor of that actor which matches the
// next string ID till it finds the last target string ID or fails to
// find it.
func (ati *ActorImpl) GetChild(id string, subID ...string) (Addr, error) {
parent, err := ati.tree.GetActor(id)
if err != nil {
return nil, err
}
if len(subID) == 0 {
return AccessOf(parent), nil
}
return parent.GetChild(subID[0], subID[1:]...)
}
// Watch adds provided function as a subscriber to be called
// on events published by actor, it returns a subscription which
// can be used to end giving subscription.
func (ati *ActorImpl) Watch(fn func(interface{})) Subscription {
return ati.props.Event.Subscribe(fn, nil)
}
// DeathWatch asks this actor sentinel to advice on behaviour or operation to
// be performed for the provided actor's states (i.e Stopped, Restarted, Killed, Destroyed).
// being watched for.
//
// If actor has no Sentinel then an error is returned.
// Sentinels are required to advice on action for watched actors by watching actor.
func (ati *ActorImpl) DeathWatch(addr Addr) error {
if ati.props.Sentinel == nil {
return errors.New("Actor does not have a sentinel")
}
select {
case ati.sentinelChan <- addr:
return nil
case <-time.After(ati.busyDur):
return errors.WrapOnly(ErrActorBusyState)
}
}
// Publish publishes an event into the actor event notification system.
func (ati *ActorImpl) Publish(message interface{}) {
ati.props.Event.Publish(message)
}
// Receive adds giving Envelope into actor's mailbox.
func (ati *ActorImpl) Receive(a Addr, e Envelope) error {
// if we cant process, then return error.
if !ati.processable.IsOn() {
return errors.New("actor is stopped and hence can't handle message")
}
if ati.props.MessageInvoker != nil {
ati.props.MessageInvoker.InvokedRequest(a, e)
}
ati.messages.Add(1)
return ati.props.Mailbox.Push(a, e)
}
// Discover returns actor's Addr from this actor's
// discovery chain, else passing up the service till it
// reaches the actors root where no possible discovery can be done.
//
// The returned address is not added to this actor's death watch, so user
// if desiring this must add it themselves.
//
// The method will return an error if Actor is not already running.
func (ati *ActorImpl) Discover(service string, ancestral bool) (Addr, error) {
if !ati.started.IsOn() && !ati.starting.IsOn() {
return nil, errors.WrapOnly(ErrActorMustBeRunning)
}
if ati.parent != nil && ati.props.Discovery == nil && ancestral {
return ati.parent.Discover(service, ancestral)
}
addr, err := ati.props.Discovery.Discover(service)
if err != nil {
if ati.parent != nil && ancestral {
return ati.parent.Discover(service, ancestral)
}
return nil, errors.WrapOnly(err)
}
return addr, nil
}
// Spawn spawns a new actor under this parents tree returning address of
// created actor.
//
// The method will return an error if Actor is not already running.
func (ati *ActorImpl) Spawn(service string, prop Prop) (Addr, error) {
if !ati.started.IsOn() && !ati.starting.IsOn() {
return nil, errors.WrapOnly(ErrActorMustBeRunning)
}
if prop.ContextLogs == nil {
prop.ContextLogs = ati.props.ContextLogs
}
if ati.props.Signals != nil {
prop.Signals = ati.props.Signals
}
if prop.MessageInvoker == nil {
prop.MessageInvoker = ati.props.MessageInvoker
}
if prop.Sentinel == nil {
prop.Sentinel = ati.props.Sentinel
}
if prop.StateInvoker == nil {
prop.StateInvoker = ati.props.StateInvoker
}
if prop.MailInvoker == nil {
prop.MailInvoker = ati.props.MailInvoker
}
if prop.DeadLetters == nil {
prop.DeadLetters = ati.props.DeadLetters
}
am := NewActorImpl(ati.namespace, ati.protocol, prop)
am.parent = ati
if err := ati.manageChild(am); err != nil {
return nil, err
}
return AddressOf(am, service), nil
}
// Stats returns giving actor stat associated with
// actor.
func (ati *ActorImpl) Stats() Stat {
return Stat{
Death: ati.death,
Creation: ati.created,
Killed: atomic.LoadInt64(&ati.killedCount),
Stopped: atomic.LoadInt64(&ati.stoppedCount),
Delivered: atomic.LoadInt64(&ati.deliveryCount),
Processed: atomic.LoadInt64(&ati.processedCount),
Restarted: atomic.LoadInt64(&ati.restartedCount),
FailedRestarts: atomic.LoadInt64(&ati.failedRestartCount),
FailedDelivery: atomic.LoadInt64(&ati.failedDeliveryCount),
}
}
// Addr returns a url-like representation of giving service by following two giving
// patterns:
//
// 1. If Actor is the highest ancestor then it will return address in form:
//
// Protocol@Namespace/ID
//
// 2. If Actor is the a child of another, then it will return address in form:
//
// AncestorAddress/ID
//
// where AncestorAddress is "Protocol@Namespace/ID"
//
// In either case, the protocol of both ancestor and parent is maintained.
// Namespace provides a field area which can define specific information that
// is specific to giving protocol e.g ip v4/v6 address.
//
func (ati *ActorImpl) Addr() string {
if ati.parent == nil {
return FormatAddr(ati.protocol, ati.namespace, ati.id.String())
}
return FormatAddrChild(ati.parent.Addr(), ati.id.String())
}
// ProtocolAddr returns the Actors.Protocol and Actors.Namespace
// values in the format:
//
// Protocol@Namespace.
//
func (ati *ActorImpl) ProtocolAddr() string {
return FormatNamespace(ati.protocol, ati.namespace)
}
// Protocol returns actor's protocol.
func (ati *ActorImpl) Protocol() string {
return ati.protocol
}
// Namespace returns actor's namespace.
func (ati *ActorImpl) Namespace() string {
return ati.namespace
}
// Escalate sends giving error that occur to actor's supervisor
// which can make necessary decision on actions to be done, either
// to escalate to parent's supervisor or restart/stop or handle
// giving actor as dictated by it's algorithm.
func (ati *ActorImpl) Escalate(err interface{}, addr Addr) {
go ati.props.Supervisor.Handle(err, addr, ati, ati.parent)
}
// Ancestor returns the root parent of giving Actor ancestral tree.
func (ati *ActorImpl) Ancestor() Actor {
if ati.parent == nil {
return ati
}
return ati.parent.Ancestor()
}
// Parent returns the parent of giving Actor.
func (ati *ActorImpl) Parent() Actor {
if ati.parent == nil {
return ati
}
return ati.parent
}
// Children returns a slice of all addresses of all child actors.
// All address have attached service name "access" for returned address,
// to indicate we are accessing this actors.
func (ati *ActorImpl) Children() []Addr {
addrs := make([]Addr, 0, ati.tree.Length())
ati.tree.Each(func(actor Actor) bool {
addrs = append(addrs, AccessOf(actor))
return true
})
return addrs
}
// Start starts off or resumes giving actor operations for processing
// received messages.
func (ati *ActorImpl) Start() error {
if ati.started.IsOn() {
return nil
}
return ati.runSystem(false)
}
// RestartChildren restarts all children of giving actor without applying same
// operation to parent.
func (ati *ActorImpl) RestartChildren() error {
res := make(chan error, 1)
select {
case ati.restartChildrenChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
// Restart restarts the actors message processing operations. It
// will immediately resume operations from pending messages within
// mailbox. This will also restarts actors children.
func (ati *ActorImpl) Restart() error {
if !ati.started.IsOn() {
return ati.Start()
}
if err := ati.Stop(); err != nil {
return err
}
if err := ati.runSystem(true); err != nil {
return err
}
return nil
}
// Stop stops the operations of the actor on processing received messages.
// All pending messages will be kept, so the actor can continue once started.
// To both stop and clear all messages, use ActorImpl.Kill().
func (ati *ActorImpl) Stop() error {
if !ati.started.IsOn() {
return nil
}
res := make(chan error, 1)
select {
case ati.stopChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
err := <-res
ati.proc.Wait()
return err
}
// StopChildren immediately stops all children of actor.
func (ati *ActorImpl) StopChildren() error {
if !ati.started.IsOn() {
return nil
}
res := make(chan error, 1)
select {
case ati.stopChildrenChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
// Kill immediately stops the actor and clears all pending messages.
func (ati *ActorImpl) Kill() error {
if !ati.started.IsOn() {
return nil
}
res := make(chan error, 1)
select {
case ati.killChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
// KillChildren immediately kills giving children of actor.
func (ati *ActorImpl) KillChildren() error {
if !ati.started.IsOn() {
return nil
}
res := make(chan error, 1)
select {
case ati.killChildrenChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
// Destroy stops giving actor and emits a destruction event which
// will remove giving actor from it's ancestry trees.
func (ati *ActorImpl) Destroy() error {
if !ati.started.IsOn() {
return nil
}
res := make(chan error, 1)
select {
case ati.destroyChan <- res:
return <-res
case <-time.After(ati.busyDur):
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
// DestroyChildren immediately destroys giving children of actor.
func (ati *ActorImpl) DestroyChildren() error {
if !ati.started.IsOn() {
return nil
}
ati.logger.Emit(DEBUG, OpMessage{Detail: "Sending destruction signal"})
res := make(chan error, 1)
select {
case ati.destroyChildrenChan <- res:
ati.logger.Emit(DEBUG, OpMessage{Detail: "Awaiting destruction response"})
return <-res
case <-time.After(ati.busyDur):
ati.logger.Emit(ERROR, OpMessage{Detail: "Failed to deliver destruction signal", Data: ErrActorBusyState})
res <- errors.WrapOnly(ErrActorBusyState)
}
return <-res
}
//****************************************************************
// internal functions
//****************************************************************
func (ati *ActorImpl) runSystem(restart bool) error {
ati.setState(STARTING)
defer ati.setState(RUNNING)
ati.starting.On()
defer ati.starting.Off()
ati.proc.Add(1)
ati.routines.Add(1)
ati.initRoutines()
ati.processable.On()
if restart {
atomic.AddInt64(&ati.restartedCount, 1)
ati.props.Event.Publish(ActorSignal{
Signal: RESTARTING,
Addr: ati.accessAddr,
})
ati.props.Signals.SignalState(ati.accessAddr, RESTARTING)
if ati.preRestart != nil {
if err := ati.preRestart.PreRestart(ati.accessAddr); err != nil {
atomic.AddInt64(&ati.failedRestartCount, 1)
return err
}
}
} else {
ati.props.Event.Publish(ActorSignal{
Signal: STARTING,
Addr: ati.accessAddr,
})
ati.props.Signals.SignalState(ati.accessAddr, STARTING)
if ati.preStart != nil {
if err := ati.preStart.PreStart(ati.accessAddr); err != nil {
return err
}
}
}
if restart {
if ati.postRestart != nil {
if err := ati.postRestart.PostRestart(ati.accessAddr); err != nil {
ati.Stop()
return err
}
}
ati.props.Signals.SignalState(ati.accessAddr, RESTARTED)
ati.props.Event.Publish(ActorSignal{
Addr: ati.accessAddr,
Signal: RESTARTED,
})
} else {
if ati.postStart != nil {
if err := ati.postStart.PostStart(ati.accessAddr); err != nil {
ati.Stop()
return err
}
}
ati.props.Signals.SignalState(ati.accessAddr, RUNNING)
ati.props.Event.Publish(ActorSignal{
Addr: ati.accessAddr,
Signal: RUNNING,
})
}
ati.started.On()
return nil
}
func (ati *ActorImpl) initRoutines() {
waitTillRunned(ati.manageLifeCycle)
waitTillRunned(ati.readMessages)
}
func (ati *ActorImpl) exhaustMessages() {
for !ati.props.Mailbox.IsEmpty() {
if nextAddr, next, err := ati.props.Mailbox.Pop(); err == nil {
ati.messages.Done()
dm := DeadMail{To: nextAddr, Message: next}
ati.props.DeadLetters.RecoverMail(dm)
}
}
}
func (ati *ActorImpl) preDestroySystem() {
ati.destruction.On()
ati.setState(DESTRUCTING)
ati.props.Signals.SignalState(ati.accessAddr, DESTRUCTING)
ati.props.Event.Publish(ActorSignal{
Addr: ati.accessAddr,
Signal: DESTRUCTING,
})
if ati.preDestroy != nil {
ati.preDestroy.PreDestroy(ati.accessAddr)
}
}
func (ati *ActorImpl) preMidDestroySystem() {
// clean out all subscription first.