forked from Tochemey/goakt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid.go
1545 lines (1324 loc) · 41.7 KB
/
pid.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
/*
* MIT License
*
* Copyright (c) 2022-2024 Tochemey
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package actors
import (
"context"
"errors"
"fmt"
stdhttp "net/http"
"os"
"strings"
"sync"
"time"
"connectrpc.com/connect"
"github.com/flowchartsman/retry"
"go.uber.org/atomic"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/tochemey/goakt/v2/address"
"github.com/tochemey/goakt/v2/future"
"github.com/tochemey/goakt/v2/goaktpb"
"github.com/tochemey/goakt/v2/internal/errorschain"
"github.com/tochemey/goakt/v2/internal/eventstream"
"github.com/tochemey/goakt/v2/internal/http"
"github.com/tochemey/goakt/v2/internal/internalpb"
"github.com/tochemey/goakt/v2/internal/internalpb/internalpbconnect"
"github.com/tochemey/goakt/v2/internal/slice"
"github.com/tochemey/goakt/v2/internal/types"
"github.com/tochemey/goakt/v2/log"
)
// specifies the state in which the PID is
// regarding message processing
type processingState int32
const (
// idle means there are no messages to process
idle processingState = iota
// processing means the PID is processing messages
processing
)
// watcher is used to handle parent child relationship.
// This helps handle error propagation from a child actor using any of supervisory strategies
type watcher struct {
WatcherID *PID // the WatcherID of the actor watching
ErrChan chan error // ErrChan the channel where to pass error message
Done chan types.Unit // Done when watching is completed
}
// taskCompletion is used to track completions' taskCompletion
// to pipe the result to the appropriate PID
type taskCompletion struct {
Receiver *PID
Task future.Task
}
// PID specifies an actor unique process
// With the PID one can send a ReceiveContext to the actor
type PID struct {
// specifies the message processor
actor Actor
// specifies the actor address
address *address.Address
// helps determine whether the actor should handle public or not.
running atomic.Bool
latestReceiveTime atomic.Time
latestReceiveDuration atomic.Duration
// specifies at what point in time to passivate the actor.
// when the actor is passivated it is stopped which means it does not consume
// any further resources like memory and cpu. The default value is 120 seconds
passivateAfter atomic.Duration
// specifies how long the sender of a mail should wait to receiveLoop a reply
// when using Ask. The default value is 5s
askTimeout atomic.Duration
// specifies the maximum of retries to attempt when the actor
// initialization fails. The default value is 5
initMaxRetries atomic.Int32
// specifies the init timeout.
// the default initialization timeout is 1s
initTimeout atomic.Duration
// shutdownTimeout specifies the graceful shutdown timeout
// the default value is 5 seconds
shutdownTimeout atomic.Duration
// specifies the actor mailbox
mailbox Mailbox
haltPassivationLnr chan types.Unit
// hold the watchersList watching the given actor
watchersList *slice.Safe[*watcher]
// hold the list of the children
children *syncMap
// hold the list of watched actors
watchedList *syncMap
// the actor system
system ActorSystem
// specifies the logger to use
logger log.Logger
// fieldsLocker that helps synchronize the pid in a concurrent environment
// this helps protect the pid fields accessibility
fieldsLocker *sync.RWMutex
stopLocker *sync.Mutex
processingTimeLocker *sync.Mutex
// supervisor strategy
supervisorDirective SupervisorDirective
// http client
httpClient *stdhttp.Client
// specifies the actor behavior stack
behaviorStack *behaviorStack
// stash settings
stashBuffer *UnboundedMailbox
stashLocker *sync.Mutex
// define an events stream
eventsStream *eventstream.EventsStream
// set the metrics settings
restartCount *atomic.Int64
childrenCount *atomic.Int64
processedCount *atomic.Int64
watcherNotificationChan chan error
watchersNotificationStopSignal chan types.Unit
receiveSignal chan types.Unit
receiveStopSignal chan types.Unit
// atomic flag indicating whether the actor is processing messages
processingMessages atomic.Int32
}
// newPID creates a new pid
func newPID(ctx context.Context, address *address.Address, actor Actor, opts ...pidOption) (*PID, error) {
// actor address is required
if address == nil {
return nil, errors.New("address is required")
}
// validate the address
if err := address.Validate(); err != nil {
return nil, err
}
pid := &PID{
actor: actor,
latestReceiveTime: atomic.Time{},
haltPassivationLnr: make(chan types.Unit, 1),
logger: log.New(log.ErrorLevel, os.Stderr),
children: newSyncMap(),
supervisorDirective: DefaultSupervisoryStrategy,
watchersList: slice.NewSafe[*watcher](),
watchedList: newSyncMap(),
address: address,
fieldsLocker: new(sync.RWMutex),
stopLocker: new(sync.Mutex),
httpClient: http.NewClient(),
mailbox: NewUnboundedMailbox(),
stashBuffer: nil,
stashLocker: &sync.Mutex{},
eventsStream: nil,
restartCount: atomic.NewInt64(0),
childrenCount: atomic.NewInt64(0),
processedCount: atomic.NewInt64(0),
processingTimeLocker: new(sync.Mutex),
watcherNotificationChan: make(chan error, 1),
watchersNotificationStopSignal: make(chan types.Unit, 1),
receiveSignal: make(chan types.Unit, 1),
receiveStopSignal: make(chan types.Unit, 1),
}
pid.initMaxRetries.Store(DefaultInitMaxRetries)
pid.shutdownTimeout.Store(DefaultShutdownTimeout)
pid.latestReceiveDuration.Store(0)
pid.running.Store(false)
pid.passivateAfter.Store(DefaultPassivationTimeout)
pid.askTimeout.Store(DefaultAskTimeout)
pid.initTimeout.Store(DefaultInitTimeout)
for _, opt := range opts {
opt(pid)
}
behaviorStack := newBehaviorStack()
behaviorStack.Push(pid.actor.Receive)
pid.behaviorStack = behaviorStack
if err := pid.init(ctx); err != nil {
return nil, err
}
pid.receiveLoop()
pid.notifyWatchers()
if pid.passivateAfter.Load() > 0 {
go pid.passivationLoop()
}
receiveContext := contextFromPool()
receiveContext.build(ctx, NoSender, pid, new(goaktpb.PostStart), true)
pid.doReceive(receiveContext)
return pid, nil
}
// ID is a convenient method that returns the actor unique identifier
// An actor unique identifier is its address in the actor system.
func (pid *PID) ID() string {
return pid.Address().String()
}
// Name returns the actor given name
func (pid *PID) Name() string {
return pid.Address().Name()
}
// Equals is a convenient method to compare two PIDs
func (pid *PID) Equals(to *PID) bool {
return strings.EqualFold(pid.ID(), to.ID())
}
// Actor returns the underlying Actor
func (pid *PID) Actor() Actor {
return pid.actor
}
// Child returns the named child actor if it is alive
func (pid *PID) Child(name string) (*PID, error) {
if !pid.IsRunning() {
return nil, ErrDead
}
childAddress := address.New(name, pid.Address().System(), pid.Address().Host(), pid.Address().Port()).WithParent(pid.Address())
if cid, ok := pid.children.Get(childAddress); ok {
pid.childrenCount.Inc()
return cid, nil
}
return nil, ErrActorNotFound(childAddress.String())
}
// Parents returns the list of all direct parents of a given actor.
// Only alive actors are included in the list or an empty list is returned
func (pid *PID) Parents() []*PID {
pid.fieldsLocker.Lock()
watchers := pid.watchersList
pid.fieldsLocker.Unlock()
var parents []*PID
if watchers.Len() > 0 {
for _, item := range watchers.Items() {
watcher := item
if watcher != nil {
pid := watcher.WatcherID
if pid.IsRunning() {
parents = append(parents, pid)
}
}
}
}
return parents
}
// Children returns the list of all the direct children of the given actor
// Only alive actors are included in the list or an empty list is returned
func (pid *PID) Children() []*PID {
pid.fieldsLocker.RLock()
children := pid.children.List()
pid.fieldsLocker.RUnlock()
cids := make([]*PID, 0, len(children))
for _, child := range children {
if child.IsRunning() {
cids = append(cids, child)
}
}
return cids
}
// Stop forces the child Actor under the given name to terminate after it finishes processing its current message.
// Nothing happens if child is already stopped.
func (pid *PID) Stop(ctx context.Context, cid *PID) error {
if !pid.IsRunning() {
return ErrDead
}
if cid == nil || cid == NoSender {
return ErrUndefinedActor
}
pid.fieldsLocker.RLock()
children := pid.children
pid.fieldsLocker.RUnlock()
if cid, ok := children.Get(cid.Address()); ok {
if err := cid.Shutdown(ctx); err != nil {
return err
}
return nil
}
return ErrActorNotFound(cid.Address().String())
}
// IsRunning returns true when the actor is alive ready to process messages and false
// when the actor is stopped or not started at all
func (pid *PID) IsRunning() bool {
return pid.running.Load()
}
// Returns interface to mailbox
func (pid *PID) Mailbox() Mailbox {
return pid.mailbox
}
// ActorSystem returns the actor system
func (pid *PID) ActorSystem() ActorSystem {
pid.fieldsLocker.RLock()
sys := pid.system
pid.fieldsLocker.RUnlock()
return sys
}
// Address returns address of the actor
func (pid *PID) Address() *address.Address {
pid.fieldsLocker.RLock()
path := pid.address
pid.fieldsLocker.RUnlock()
return path
}
// Restart restarts the actor.
// During restart all messages that are in the mailbox and not yet processed will be ignored
func (pid *PID) Restart(ctx context.Context) error {
if pid == nil || pid.Address() == nil {
return ErrUndefinedActor
}
pid.logger.Debugf("restarting actor=(%s)", pid.address.String())
if pid.IsRunning() {
if err := pid.Shutdown(ctx); err != nil {
return err
}
ticker := time.NewTicker(10 * time.Millisecond)
tickerStopSig := make(chan types.Unit, 1)
go func() {
for range ticker.C {
if !pid.IsRunning() {
tickerStopSig <- types.Unit{}
return
}
}
}()
<-tickerStopSig
ticker.Stop()
}
pid.resetBehavior()
if err := pid.init(ctx); err != nil {
return err
}
pid.receiveLoop()
pid.notifyWatchers()
if pid.passivateAfter.Load() > 0 {
go pid.passivationLoop()
}
pid.restartCount.Inc()
if pid.eventsStream != nil {
pid.eventsStream.Publish(eventsTopic, &goaktpb.ActorRestarted{
Address: pid.Address().Address,
RestartedAt: timestamppb.Now(),
})
}
return nil
}
// RestartCount returns the total number of re-starts by the given PID
func (pid *PID) RestartCount() int {
count := pid.restartCount.Load()
return int(count)
}
// ChildrenCount returns the total number of children for the given PID
func (pid *PID) ChildrenCount() int {
count := pid.childrenCount.Load()
return int(count)
}
// ProcessedCount returns the total number of messages processed at a given time
func (pid *PID) ProcessedCount() int {
count := pid.processedCount.Load()
return int(count)
}
// LatestProcessedDuration returns the duration of the latest message processed
func (pid *PID) LatestProcessedDuration() time.Duration {
pid.latestReceiveDuration.Store(time.Since(pid.latestReceiveTime.Load()))
return pid.latestReceiveDuration.Load()
}
// SpawnChild creates a child actor and start watching it for error
// When the given child actor already exists its PID will only be returned
func (pid *PID) SpawnChild(ctx context.Context, name string, actor Actor, opts ...SpawnOption) (*PID, error) {
if !pid.IsRunning() {
return nil, ErrDead
}
childAddress := address.New(name, pid.Address().System(), pid.Address().Host(), pid.Address().Port()).WithParent(pid.Address())
pid.fieldsLocker.RLock()
children := pid.children
pid.fieldsLocker.RUnlock()
if cid, ok := children.Get(childAddress); ok {
return cid, nil
}
pid.fieldsLocker.RLock()
// create the child actor options child inherit parent's options
pidOptions := []pidOption{
withInitMaxRetries(int(pid.initMaxRetries.Load())),
withPassivationAfter(pid.passivateAfter.Load()),
withAskTimeout(pid.askTimeout.Load()),
withCustomLogger(pid.logger),
withActorSystem(pid.system),
withSupervisorDirective(pid.supervisorDirective),
withEventsStream(pid.eventsStream),
withInitTimeout(pid.initTimeout.Load()),
withShutdownTimeout(pid.shutdownTimeout.Load()),
}
spawnConfig := newSpawnConfig(opts...)
if spawnConfig.mailbox != nil {
pidOptions = append(pidOptions, withMailbox(spawnConfig.mailbox))
}
cid, err := newPID(ctx,
childAddress,
actor,
pidOptions...,
)
if err != nil {
pid.fieldsLocker.RUnlock()
return nil, err
}
pid.children.Set(cid)
eventsStream := pid.eventsStream
pid.fieldsLocker.RUnlock()
pid.Watch(cid)
if eventsStream != nil {
eventsStream.Publish(eventsTopic, &goaktpb.ActorChildCreated{
Address: cid.Address().Address,
CreatedAt: timestamppb.Now(),
Parent: pid.Address().Address,
})
}
// set the actor in the given actor system registry
if pid.ActorSystem() != nil {
pid.ActorSystem().setActor(cid)
}
return cid, nil
}
// StashSize returns the stash buffer size
func (pid *PID) StashSize() uint64 {
if pid.stashBuffer == nil {
return 0
}
return uint64(pid.stashBuffer.Len())
}
// PipeTo processes a long-running task and pipes the result to the provided actor.
// The successful result of the task will be put onto the provided actor mailbox.
// This is useful when interacting with external services.
// It’s common that you would like to use the value of the response in the actor when the long-running task is completed
func (pid *PID) PipeTo(ctx context.Context, to *PID, task future.Task) error {
if task == nil {
return ErrUndefinedTask
}
if !to.IsRunning() {
return ErrDead
}
go pid.handleCompletion(ctx, &taskCompletion{
Receiver: to,
Task: task,
})
return nil
}
// Ask sends a synchronous message to another actor and expect a response.
// This block until a response is received or timed out.
func (pid *PID) Ask(ctx context.Context, to *PID, message proto.Message) (response proto.Message, err error) {
if !to.IsRunning() {
return nil, ErrDead
}
receiveContext := contextFromPool()
receiveContext.build(ctx, pid, to, message, false)
to.doReceive(receiveContext)
timeout := pid.askTimeout.Load()
select {
case result := <-receiveContext.response:
return result, nil
case <-time.After(timeout):
err = ErrRequestTimeout
pid.toDeadletterQueue(receiveContext, err)
return nil, err
}
}
// Tell sends an asynchronous message to another PID
func (pid *PID) Tell(ctx context.Context, to *PID, message proto.Message) error {
if !to.IsRunning() {
return ErrDead
}
receiveContext := contextFromPool()
receiveContext.build(ctx, pid, to, message, true)
to.doReceive(receiveContext)
return nil
}
// SendAsync sends an asynchronous message to a given actor.
// The location of the given actor is transparent to the caller.
func (pid *PID) SendAsync(ctx context.Context, actorName string, message proto.Message) error {
if !pid.IsRunning() {
return ErrDead
}
addr, cid, err := pid.ActorSystem().ActorOf(ctx, actorName)
if err != nil {
return err
}
if cid != nil {
return pid.Tell(ctx, cid, message)
}
return pid.RemoteTell(ctx, addr, message)
}
// SendSync sends a synchronous message to another actor and expect a response.
// The location of the given actor is transparent to the caller.
// This block until a response is received or timed out.
func (pid *PID) SendSync(ctx context.Context, actorName string, message proto.Message) (response proto.Message, err error) {
if !pid.IsRunning() {
return nil, ErrDead
}
addr, cid, err := pid.ActorSystem().ActorOf(ctx, actorName)
if err != nil {
return nil, err
}
if cid != nil {
return pid.Ask(ctx, cid, message)
}
reply, err := pid.RemoteAsk(ctx, addr, message)
if err != nil {
return nil, err
}
return reply.UnmarshalNew()
}
// BatchTell sends an asynchronous bunch of messages to the given PID
// The messages will be processed one after the other in the order they are sent.
// This is a design choice to follow the simple principle of one message at a time processing by actors.
// When BatchTell encounter a single message it will fall back to a Tell call.
func (pid *PID) BatchTell(ctx context.Context, to *PID, messages ...proto.Message) error {
for _, message := range messages {
if err := pid.Tell(ctx, to, message); err != nil {
return err
}
}
return nil
}
// BatchAsk sends a synchronous bunch of messages to the given PID and expect responses in the same order as the messages.
// The messages will be processed one after the other in the order they are sent.
// This is a design choice to follow the simple principle of one message at a time processing by actors.
func (pid *PID) BatchAsk(ctx context.Context, to *PID, messages ...proto.Message) (responses chan proto.Message, err error) {
responses = make(chan proto.Message, len(messages))
defer close(responses)
for i := 0; i < len(messages); i++ {
response, err := pid.Ask(ctx, to, messages[i])
if err != nil {
return nil, err
}
responses <- response
}
return
}
// RemoteLookup look for an actor address on a remote node.
func (pid *PID) RemoteLookup(ctx context.Context, host string, port int, name string) (addr *goaktpb.Address, err error) {
remoteClient := pid.remotingClient(host, port)
request := connect.NewRequest(&internalpb.RemoteLookupRequest{
Host: host,
Port: int32(port),
Name: name,
})
response, err := remoteClient.RemoteLookup(ctx, request)
if err != nil {
code := connect.CodeOf(err)
if code == connect.CodeNotFound {
return nil, nil
}
return nil, err
}
return response.Msg.GetAddress(), nil
}
// RemoteTell sends a message to an actor remotely without expecting any reply
func (pid *PID) RemoteTell(ctx context.Context, to *address.Address, message proto.Message) error {
marshaled, err := anypb.New(message)
if err != nil {
return err
}
remoteService := pid.remotingClient(to.GetHost(), int(to.GetPort()))
sender := &goaktpb.Address{
Host: pid.Address().Host(),
Port: int32(pid.Address().Port()),
Name: pid.Address().Name(),
Id: pid.Address().ID(),
}
request := &internalpb.RemoteTellRequest{
RemoteMessage: &internalpb.RemoteMessage{
Sender: sender,
Receiver: to.Address,
Message: marshaled,
},
}
pid.logger.Debugf("sending a message to remote=(%s:%d)", to.GetHost(), to.GetPort())
stream := remoteService.RemoteTell(ctx)
if err := stream.Send(request); err != nil {
if eof(err) {
if _, err := stream.CloseAndReceive(); err != nil {
return err
}
return nil
}
fmtErr := fmt.Errorf("failed to send message to remote=(%s:%d): %w", to.GetHost(), to.GetPort(), err)
pid.logger.Error(fmtErr)
return fmtErr
}
if _, err := stream.CloseAndReceive(); err != nil {
fmtErr := fmt.Errorf("failed to send message to remote=(%s:%d): %w", to.GetHost(), to.GetPort(), err)
pid.logger.Error(fmtErr)
return fmtErr
}
pid.logger.Debugf("message successfully sent to remote=(%s:%d)", to.GetHost(), to.GetPort())
return nil
}
// RemoteAsk sends a synchronous message to another actor remotely and expect a response.
func (pid *PID) RemoteAsk(ctx context.Context, to *address.Address, message proto.Message) (response *anypb.Any, err error) {
marshaled, err := anypb.New(message)
if err != nil {
return nil, err
}
remoteService := pid.remotingClient(to.GetHost(), int(to.GetPort()))
senderAddress := pid.Address()
sender := &goaktpb.Address{
Host: senderAddress.Host(),
Port: int32(senderAddress.Port()),
Name: senderAddress.Name(),
Id: senderAddress.ID(),
}
request := &internalpb.RemoteAskRequest{
RemoteMessage: &internalpb.RemoteMessage{
Sender: sender,
Receiver: to.Address,
Message: marshaled,
},
}
stream := remoteService.RemoteAsk(ctx)
errc := make(chan error, 1)
go func() {
defer close(errc)
for {
resp, err := stream.Receive()
if err != nil {
errc <- err
return
}
response = resp.GetMessage()
}
}()
err = stream.Send(request)
if err != nil {
return nil, err
}
if err := stream.CloseRequest(); err != nil {
return nil, err
}
err = <-errc
if eof(err) {
return response, nil
}
if err != nil {
return nil, err
}
return
}
// RemoteBatchTell sends a batch of messages to a remote actor in a way fire-and-forget manner
// Messages are processed one after the other in the order they are sent.
func (pid *PID) RemoteBatchTell(ctx context.Context, to *address.Address, messages ...proto.Message) error {
if len(messages) == 1 {
return pid.RemoteTell(ctx, to, messages[0])
}
sender := &goaktpb.Address{
Host: pid.Address().Host(),
Port: int32(pid.Address().Port()),
Name: pid.Address().Name(),
Id: pid.Address().ID(),
}
var requests []*internalpb.RemoteTellRequest
for _, message := range messages {
packed, err := anypb.New(message)
if err != nil {
return ErrInvalidRemoteMessage(err)
}
requests = append(requests, &internalpb.RemoteTellRequest{
RemoteMessage: &internalpb.RemoteMessage{
Sender: sender,
Receiver: to.Address,
Message: packed,
},
})
}
remoteService := pid.remotingClient(to.GetHost(), int(to.GetPort()))
stream := remoteService.RemoteTell(ctx)
for _, request := range requests {
if err := stream.Send(request); err != nil {
if eof(err) {
if _, err := stream.CloseAndReceive(); err != nil {
return err
}
return nil
}
return err
}
}
// close the connection
if _, err := stream.CloseAndReceive(); err != nil {
return err
}
return nil
}
// RemoteBatchAsk sends a synchronous bunch of messages to a remote actor and expect responses in the same order as the messages.
// Messages are processed one after the other in the order they are sent.
// This can hinder performance if it is not properly used.
func (pid *PID) RemoteBatchAsk(ctx context.Context, to *address.Address, messages ...proto.Message) (responses []*anypb.Any, err error) {
sender := &goaktpb.Address{
Host: pid.Address().Host(),
Port: int32(pid.Address().Port()),
Name: pid.Address().Name(),
Id: pid.Address().ID(),
}
var requests []*internalpb.RemoteAskRequest
for _, message := range messages {
packed, err := anypb.New(message)
if err != nil {
return nil, ErrInvalidRemoteMessage(err)
}
requests = append(requests, &internalpb.RemoteAskRequest{
RemoteMessage: &internalpb.RemoteMessage{
Sender: sender,
Receiver: to.Address,
Message: packed,
},
})
}
remoteService := pid.remotingClient(to.GetHost(), int(to.GetPort()))
stream := remoteService.RemoteAsk(ctx)
errc := make(chan error, 1)
go func() {
defer close(errc)
for {
resp, err := stream.Receive()
if err != nil {
errc <- err
return
}
responses = append(responses, resp.GetMessage())
}
}()
for _, request := range requests {
err := stream.Send(request)
if err != nil {
return nil, err
}
}
if err := stream.CloseRequest(); err != nil {
return nil, err
}
err = <-errc
if eof(err) {
return responses, nil
}
if err != nil {
return nil, err
}
return
}
// RemoteStop stops an actor on a remote node
func (pid *PID) RemoteStop(ctx context.Context, host string, port int, name string) error {
remoteService := pid.remotingClient(host, port)
request := connect.NewRequest(&internalpb.RemoteStopRequest{
Host: host,
Port: int32(port),
Name: name,
})
if _, err := remoteService.RemoteStop(ctx, request); err != nil {
code := connect.CodeOf(err)
if code == connect.CodeNotFound {
return nil
}
return err
}
return nil
}
// RemoteSpawn creates an actor on a remote node. The given actor needs to be registered on the remote node using the Register method of ActorSystem
func (pid *PID) RemoteSpawn(ctx context.Context, host string, port int, name, actorType string) error {
remoteService := pid.remotingClient(host, port)
request := connect.NewRequest(&internalpb.RemoteSpawnRequest{
Host: host,
Port: int32(port),
ActorName: name,
ActorType: actorType,
})
if _, err := remoteService.RemoteSpawn(ctx, request); err != nil {
code := connect.CodeOf(err)
if code == connect.CodeFailedPrecondition {
connectErr := err.(*connect.Error)
e := connectErr.Unwrap()
// TODO: find a better way to use errors.Is with connect.Error
if strings.Contains(e.Error(), ErrTypeNotRegistered.Error()) {
return ErrTypeNotRegistered
}
}
return err
}
return nil
}
// RemoteReSpawn restarts an actor on a remote node.
func (pid *PID) RemoteReSpawn(ctx context.Context, host string, port int, name string) error {
remoteService := pid.remotingClient(host, port)
request := connect.NewRequest(&internalpb.RemoteReSpawnRequest{
Host: host,
Port: int32(port),
Name: name,
})
if _, err := remoteService.RemoteReSpawn(ctx, request); err != nil {
code := connect.CodeOf(err)
if code == connect.CodeNotFound {
return nil
}
return err
}
return nil
}
// Shutdown gracefully shuts down the given actor
// All current messages in the mailbox will be processed before the actor shutdown after a period of time
// that can be configured. All child actors will be gracefully shutdown.
func (pid *PID) Shutdown(ctx context.Context) error {
pid.stopLocker.Lock()
pid.logger.Info("Shutdown process has started...")
if !pid.running.Load() {
pid.logger.Infof("Actor=%s is offline. Maybe it has been passivated or stopped already", pid.Address().String())
pid.stopLocker.Unlock()
return nil
}
if pid.passivateAfter.Load() > 0 {
pid.logger.Debug("sending a signal to stop passivation listener....")
pid.haltPassivationLnr <- types.Unit{}
}
if err := pid.doStop(ctx); err != nil {
pid.logger.Errorf("failed to cleanly stop actor=(%s)", pid.ID())
pid.stopLocker.Unlock()
return err
}
if pid.eventsStream != nil {
pid.eventsStream.Publish(eventsTopic, &goaktpb.ActorStopped{
Address: pid.Address().Address,
StoppedAt: timestamppb.Now(),
})
}
pid.stopLocker.Unlock()
pid.logger.Infof("Actor=%s successfully shutdown", pid.ID())