-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathActorRef.cs
1125 lines (982 loc) · 39 KB
/
ActorRef.cs
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
//-----------------------------------------------------------------------
// <copyright file="ActorRef.cs" company="Akka.NET Project">
// Copyright (C) 2009-2022 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2025 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor.Internal;
using Akka.Actor.Scheduler;
using Akka.Annotations;
using Akka.Dispatch.SysMsg;
using Akka.Event;
using Akka.Util;
using Akka.Util.Internal;
using Akka.Util.Internal.Collections;
namespace Akka.Actor
{
/// <summary>
/// INTERNAL API
///
/// All ActorRefs have a scope which describes where they live. Since it is often
/// necessary to distinguish between local and non-local references, this is the only
/// method provided on the scope.
/// </summary>
[InternalApi]
public interface IActorRefScope
{
/// <summary>
/// Returns <c>true</c> if the actor is local to this <see cref="ActorSystem"/>.
/// Returns <c>false</c> if the actor is remote.
/// </summary>
bool IsLocal { get; }
}
/// <summary>
/// Marker interface for Actors that are deployed within local scope,
/// i.e. <see cref="IActorRefScope.IsLocal"/> always returns <c>true</c>.
/// </summary>
internal interface ILocalRef : IActorRefScope { }
/// <summary>
/// INTERNAL API
///
/// RepointableActorRef (and potentially others) may change their locality at
/// runtime, meaning that isLocal might not be stable. RepointableActorRef has
/// the feature that it starts out "not fully started" (but you can send to it),
/// which is why <see cref="IsStarted"/> features here; it is not improbable that cluster
/// actor refs will have the same behavior.
/// </summary>
public interface IRepointableRef : IActorRefScope
{
/// <summary>
/// Returns <c>true</c> if this actor has started yet. <c>false</c> otherwise.
/// </summary>
bool IsStarted { get; }
}
/// <summary>
/// INTERNAL API.
///
/// ActorRef implementation used for one-off tasks.
/// </summary>
public class FutureActorRef<T> : MinimalActorRef
{
private readonly TaskCompletionSource<T> _result;
private readonly ActorPath _path;
private readonly IActorRefProvider _provider;
/// <summary>
/// INTERNAL API
/// </summary>
/// <param name="result">TBD</param>
/// <param name="path">TBD</param>
/// <param name="provider">TBD</param>
public FutureActorRef(TaskCompletionSource<T> result, ActorPath path, IActorRefProvider provider)
{
_result = result;
_path = path;
_provider = provider;
}
/// <summary>
/// TBD
/// </summary>
public override ActorPath Path => _path;
/// <summary>
/// TBD
/// </summary>
public override IActorRefProvider Provider => _provider;
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <param name="sender">TBD</param>
protected override void TellInternal(object message, IActorRef sender)
{
var handled = false;
switch (message)
{
case ISystemMessage msg:
handled = _result.TrySetException(new InvalidOperationException($"system message of type '{msg.GetType().Name}' is invalid for {nameof(FutureActorRef<T>)}"));
break;
case T t:
handled = _result.TrySetResult(t);
break;
case null:
handled = _result.TrySetResult(default);
break;
case Status.Failure f:
handled = _result.TrySetException(f.Cause
?? new TaskCanceledException("Task cancelled by actor via Failure message."));
break;
#pragma warning disable CS0618
// for backwards compatibility
case Failure f:
handled = _result.TrySetException(f.Exception
?? new TaskCanceledException("Task cancelled by actor via Failure message."));
#pragma warning restore CS0618
break;
default:
_ = _result.TrySetException(new ArgumentException(
$"Received message of type [{message.GetType()}] - Ask expected message of type [{typeof(T)}]"));
break;
}
//ignore canceled ask and put unhandled answers into deadletter
if (!handled && !_result.Task.IsCanceled)
_provider.DeadLetters.Tell(message ?? default(T), this);
}
public virtual void DeliverAsk(object message, ICanTell destination){
destination.Tell(message, this);
}
}
/// <summary>
/// INTERNAL API.
/// </summary>
internal static class ActorRefSender
{
/// <summary>
/// Gets the current actor, if any. Otherwise <see cref="ActorRefs.NoSender"/>.
/// </summary>
/// <returns>The current <see cref="IActorRef"/>, if applicable. If not, <see cref="ActorRefs.NoSender"/>.</returns>
public static IActorRef GetSelfOrNoSender()
{
var actorCell = ActorCell.Current;
return actorCell != null ? actorCell.Self : ActorRefs.NoSender;
}
}
/// <summary>
/// An actor reference. Acts as a handle to an actor. Used to send messages to an actor, whether an actor is local or remote.
/// If you receive a reference to an actor, that actor is guaranteed to have existed at some point
/// in the past. However, an actor can always be terminated in the future.
///
/// If you want to be notified about an actor terminating, call <see cref="ICanWatch.Watch(IActorRef)">IActorContext.Watch</see>
/// on this actor and you'll receive a <see cref="Terminated"/> message when the actor dies or if it
/// is already dead.
/// </summary>
/// <remarks>Actor references can be serialized and passed over the network.</remarks>
public interface IActorRef : ICanTell, IEquatable<IActorRef>, IComparable<IActorRef>, ISurrogated, IComparable
{
/// <summary>
/// The path of this actor. Can be used to extract information about whether or not this actor is local or remote.
/// </summary>
ActorPath Path { get; }
}
/// <summary>
/// Extension method class. Used to deliver messages to <see cref="IActorRef"/> instances
/// via <see cref="Tell"/> and <see cref="Forward"/> and pass along information about the current sender.
/// </summary>
public static class ActorRefImplicitSenderExtensions
{
/// <summary>
/// Asynchronously tells a message to an <see cref="IActorRef"/>.
/// </summary>
/// <param name="receiver">The actor who will receive the message.</param>
/// <param name="message">The message.</param>
/// <remarks>Will automatically resolve the current sender using the current <see cref="ActorCell"/>, if any.</remarks>
public static void Tell(this IActorRef receiver, object message)
{
var sender = ActorCell.GetCurrentSelfOrNoSender();
receiver.Tell(message, sender);
}
/// <summary>
/// Forwards the message using the current Sender
/// </summary>
/// <param name="receiver">The actor that receives the forward</param>
/// <param name="message">The message to forward</param>
public static void Forward(this IActorRef receiver, object message)
{
var sender = ActorCell.GetCurrentSenderOrNoSender();
receiver.Tell(message, sender);
}
}
/// <summary>
/// Utility class for working with built-in actor references
/// </summary>
public static class ActorRefs
{
/// <summary>
/// Use this value to represent a non-existent actor.
/// </summary>
public static readonly Nobody Nobody = Nobody.Instance;
/// <summary>
/// Use this value as an argument to <see cref="ICanTell.Tell"/> if there is not actor to
/// reply to (e.g. when sending from non-actor code).
/// </summary>
#nullable enable
public static readonly IActorRef? NoSender = null;
#nullable restore
}
/// <summary>
/// Base implementation for <see cref="IActorRef"/> implementations.
/// </summary>
public abstract class ActorRefBase : IActorRef
{
/// <summary>
/// This class represents a surrogate of a <see cref="ActorRefBase"/> router.
/// Its main use is to help during the serialization process.
/// </summary>
public class Surrogate : ISurrogate
{
/// <summary>
/// TBD
/// </summary>
/// <param name="path">TBD</param>
public Surrogate(string path)
{
Path = path;
}
/// <summary>
/// TBD
/// </summary>
public string Path { get; }
/// <summary>
/// Creates an <see cref="ActorRefBase"/> encapsulated by this surrogate.
/// </summary>
/// <param name="system">The actor system that contains this <see cref="ActorRefBase"/>.</param>
/// <returns>The <see cref="ActorRefBase"/> encapsulated by this surrogate.</returns>
public ISurrogated FromSurrogate(ActorSystem system)
{
return ((ActorSystemImpl)system).Provider.ResolveActorRef(Path);
}
}
/// <summary>
/// TBD
/// </summary>
public abstract ActorPath Path { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <param name="sender">TBD</param>
public void Tell(object message, IActorRef sender)
{
if (sender == null)
{
sender = ActorRefs.NoSender;
}
TellInternal(message, sender);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <param name="sender">TBD</param>
protected abstract void TellInternal(object message, IActorRef sender);
public override string ToString()
{
if (Path.Uid == ActorCell.UndefinedUid) return $"[{Path}]";
return $"[{Path}#{Path.Uid}]";
}
public override bool Equals(object obj)
{
if (obj is IActorRef other)
return Equals(other);
return false;
}
public override int GetHashCode()
{
unchecked
{
var hash = 17;
hash = hash * 23 + Path.Uid.GetHashCode();
hash = hash * 23 + Path.GetHashCode();
return hash;
}
}
/// <exception cref="ArgumentException">
/// This exception is thrown if the given <paramref name="obj"/> isn't an <see cref="IActorRef"/>.
/// </exception>
public int CompareTo(object obj)
{
if (obj is null) return 1;
if (!(obj is IActorRef other))
throw new ArgumentException($"Object must be of type IActorRef, found {obj.GetType()} instead.", nameof(obj));
return CompareTo(other);
}
/// <summary>
/// Checks equality between this instance and another object.
/// </summary>
/// <param name="other"></param>
/// <returns>
/// <c>true</c> if this <see cref="IActorRef"/> instance have the same reference
/// as the <paramref name="other"/> instance, if this <see cref="ActorPath"/> of
/// this <see cref="IActorRef"/> instance is equal to the <paramref name="other"/> instance,
/// and <paramref name="other"/> is not <c>null</c>; otherwise <c>false</c>.
/// </returns>
public bool Equals(IActorRef other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Path.Uid == other.Path.Uid
&& Path.Equals(other.Path);
}
public int CompareTo(IActorRef other)
{
if (other is null) return 1;
var pathComparisonResult = Path.CompareTo(other.Path);
if (pathComparisonResult != 0) return pathComparisonResult;
if (Path.Uid < other.Path.Uid) return -1;
return Path.Uid == other.Path.Uid ? 0 : 1;
}
/// <summary>
/// Creates a surrogate representation of the current <see cref="ActorRefBase"/>.
/// </summary>
/// <param name="system">The actor system that references this <see cref="ActorRefBase"/>.</param>
/// <returns>The surrogate representation of the current <see cref="ActorRefBase"/>.</returns>
public virtual ISurrogate ToSurrogate(ActorSystem system)
{
return new Surrogate(Serialization.Serialization.SerializedActorPath(this));
}
}
/// <summary>
/// INTERNAL API.
///
/// Used by built-in <see cref="IActorRef"/> implementations for handling
/// internal operations that are not exposed directly to end-users.
/// </summary>
[InternalApi]
public interface IInternalActorRef : IActorRef, IActorRefScope
{
/// <summary>
/// The parent of this actor.
/// </summary>
IInternalActorRef Parent { get; }
/// <summary>
/// The <see cref="IActorRefProvider"/> used by the <see cref="ActorSystem"/>
/// to which this actor belongs.
/// </summary>
IActorRefProvider Provider { get; }
/// <summary>
/// Obsolete. Use <see cref="Watch"/> or <see cref="ReceiveActor.Receive{T}(Action{T}, Predicate{T})">Receive<<see cref="Akka.Actor.Terminated"/>></see>
/// </summary>
[Obsolete("Use Context.Watch and Receive<Terminated> [1.1.0]")]
bool IsTerminated { get; }
/// <summary>
/// Obtain a child given the paths element to that actor, by possibly traversing the actor tree or
/// looking it up at some provider-specific location.
/// A path element of ".." signifies the parent, a trailing "" element must be disregarded.
/// If the requested path does not exist, returns <see cref="Nobody"/>.
/// </summary>
/// <param name="name">The path elements.</param>
/// <returns>The <see cref="IActorRef"/>, or if the requested path does not exist, returns <see cref="Nobody"/>.</returns>
IActorRef GetChild(IReadOnlyList<string> name);
/// <summary>
/// Resumes an actor if it has been suspended.
/// </summary>
/// <param name="causedByFailure">Optional. Passed in if the actor is resuming as a result of recovering from failure.</param>
void Resume(Exception causedByFailure = null);
/// <summary>
/// Start a newly created actor.
/// </summary>
void Start();
/// <summary>
/// Stop the actor. Terminates it permanently.
/// </summary>
void Stop();
/// <summary>
/// Restart the actor.
/// </summary>
/// <param name="cause">The exception that caused the actor to fail in the first place.</param>
void Restart(Exception cause);
/// <summary>
/// Suspend the actor. Actor will not process any more messages until <see cref="Resume"/> is called.
/// </summary>
void Suspend();
/// <summary>
/// Obsolete. Use <see cref="SendSystemMessage(ISystemMessage)"/> instead.
/// </summary>
/// <param name="message">N/A</param>
/// <param name="sender">N/A</param>
[Obsolete("Use SendSystemMessage(message) [1.1.0]")]
void SendSystemMessage(ISystemMessage message, IActorRef sender);
/// <summary>
/// Sends an <see cref="ISystemMessage"/> to the underlying actor.
/// </summary>
/// <param name="message">The system message we're sending.</param>
void SendSystemMessage(ISystemMessage message);
}
/// <summary>
/// INTERNAL API.
///
/// Abstract implementation of <see cref="IInternalActorRef"/>.
/// </summary>
[InternalApi]
public abstract class InternalActorRefBase : ActorRefBase, IInternalActorRef
{
/// <inheritdoc cref="IInternalActorRef"/>
public abstract IInternalActorRef Parent { get; }
/// <inheritdoc cref="IInternalActorRef"/>
public abstract IActorRefProvider Provider { get; }
/// <inheritdoc cref="IInternalActorRef"/>
public abstract IActorRef GetChild(IReadOnlyList<string> name); //TODO: Refactor this to use an IEnumerator instead as this will be faster instead of enumerating multiple times over name, as the implementations currently do.
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void Resume(Exception causedByFailure = null);
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void Start();
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void Stop();
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void Restart(Exception cause);
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void Suspend();
/// <inheritdoc cref="IInternalActorRef"/>
public abstract bool IsTerminated { get; }
/// <inheritdoc cref="IInternalActorRef"/>
public abstract bool IsLocal { get; }
/// <inheritdoc cref="IInternalActorRef"/>
[Obsolete("Use SendSystemMessage(message) instead [1.1.0]")]
public void SendSystemMessage(ISystemMessage message, IActorRef sender)
{
SendSystemMessage(message);
}
/// <inheritdoc cref="IInternalActorRef"/>
public abstract void SendSystemMessage(ISystemMessage message);
}
/// <summary>
/// INTERNAL API.
///
/// Barebones <see cref="IActorRef"/> with no backing actor or <see cref="ActorCell"/>.
/// </summary>
[InternalApi]
public abstract class MinimalActorRef : InternalActorRefBase, ILocalRef
{
/// <inheritdoc cref="InternalActorRefBase"/>
public override IInternalActorRef Parent
{
get { return ActorRefs.Nobody; }
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override IActorRef GetChild(IReadOnlyList<string> name)
{
if (name.All(x => string.IsNullOrEmpty(x)))
return this;
return ActorRefs.Nobody;
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void Resume(Exception causedByFailure = null)
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void Start()
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void Stop()
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void Restart(Exception cause)
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void Suspend()
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
protected override void TellInternal(object message, IActorRef sender)
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override void SendSystemMessage(ISystemMessage message)
{
}
/// <inheritdoc cref="InternalActorRefBase"/>
public override bool IsLocal
{
get { return true; }
}
/// <inheritdoc cref="InternalActorRefBase"/>
[Obsolete("Use Context.Watch and Receive<Terminated> [1.1.0]")]
#pragma warning disable CS0809
public override bool IsTerminated { get { return false; } }
#pragma warning restore CS0809
}
/// <summary>
/// An ActorRef that ignores any incoming messages.
/// </summary>
internal sealed class IgnoreActorRef : MinimalActorRef
{
/// <summary>
/// A surrogate for serializing <see cref="IgnoreActorRef"/>.
/// </summary>
public class IgnoreActorRefSurrogate : ISurrogate
{
/// <summary>
/// Converts the <see cref="ISurrogate"/> into a <see cref="IActorRef"/>.
/// </summary>
/// <param name="system">The actor system.</param>
/// <returns>TBD</returns>
public ISurrogated FromSurrogate(ActorSystem system)
{
return new IgnoreActorRef(system.AsInstanceOf<ExtendedActorSystem>().Provider);
}
}
private static readonly IgnoreActorRefSurrogate SurrogateInstance = new();
private const string fakeSystemName = "local";
private static readonly ActorPath path = new RootActorPath(new Address("akka", fakeSystemName)) / "ignore";
private static readonly string pathString = path.ToString();
public static ActorPath StaticPath => path;
public IgnoreActorRef(IActorRefProvider provider)
{
Provider = provider;
}
public override ActorPath Path => path;
public override IActorRefProvider Provider { get; }
/// <summary>
/// Check if the passed `otherPath` is the same as IgnoreActorRef.path
/// </summary>
/// <param name="otherPath"></param>
/// <returns></returns>
public static bool IsIgnoreRefPath(string otherPath) =>
pathString.Equals(otherPath);
/// <summary>
/// Check if the passed `otherPath` is the same as IgnoreActorRef.path
/// </summary>
/// <param name="otherPath"></param>
/// <returns></returns>
public static bool IsIgnoreRefPath(ActorPath otherPath) =>
path.Equals(otherPath);
public override ISurrogate ToSurrogate(ActorSystem system)
{
return SurrogateInstance;
}
}
/// <summary> This is an internal look-up failure token, not useful for anything else.</summary>
public sealed class Nobody : MinimalActorRef
{
/// <summary>
/// A surrogate for serializing <see cref="Nobody"/>.
/// </summary>
public class NobodySurrogate : ISurrogate
{
/// <summary>
/// Converts the <see cref="ISurrogate"/> into a <see cref="IActorRef"/>.
/// </summary>
/// <param name="system">The actor system.</param>
/// <returns>TBD</returns>
public ISurrogated FromSurrogate(ActorSystem system)
{
return Nobody.Instance;
}
}
/// <summary>
/// Singleton instance of <see cref="Nobody"/>.
/// </summary>
public static Nobody Instance = new();
private static readonly NobodySurrogate SurrogateInstance = new();
private readonly ActorPath _path = new RootActorPath(Address.AllSystems, "/Nobody");
private Nobody() { }
/// <inheritdoc cref="InternalActorRefBase"/>
public override ActorPath Path { get { return _path; } }
/// <summary>N/A</summary>
/// <exception cref="NotSupportedException">
/// This exception is automatically thrown since this actor doesn't have a provider.
/// </exception>
public override IActorRefProvider Provider
{
get { throw new NotSupportedException("Nobody does not provide"); }
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public override ISurrogate ToSurrogate(ActorSystem system)
{
return SurrogateInstance;
}
}
/// <summary>
/// INTERNAL API
///
/// Used to power actors that use an <see cref="ActorCell"/>, which is the majority of them.
/// </summary>
[InternalApi]
public abstract class ActorRefWithCell : InternalActorRefBase
{
/// <summary>
/// The <see cref="ActorCell"/>.
/// </summary>
public abstract ICell Underlying { get; }
/// <summary>
/// An iterable collection of the actor's children. Empty if there are none.
/// </summary>
public abstract IEnumerable<IActorRef> Children { get; }
/// <summary>
/// Fetches a reference to a single child actor.
/// </summary>
/// <param name="name">The name of the child we're trying to fetch.</param>
/// <returns>If the child exists, it returns the child actor. Otherwise, we return <see cref="ActorRefs.Nobody"/>.</returns>
public abstract IInternalActorRef GetSingleChild(string name);
private IEnumerable<IActorRef> SelfAndChildren()
{
yield return this;
foreach (var child in Children.SelectMany(x =>
{
switch (x)
{
case ActorRefWithCell cell:
return cell.SelfAndChildren();
default:
return new[] { x };
}
}))
{
yield return child;
}
}
}
/// <summary>
/// TBD
/// </summary>
internal class VirtualPathContainer : MinimalActorRef
{
private readonly IInternalActorRef _parent;
private readonly ILoggingAdapter _log;
private readonly IActorRefProvider _provider;
private readonly ActorPath _path;
private readonly ConcurrentDictionary<string, IInternalActorRef> _children = new();
/// <summary>
/// TBD
/// </summary>
/// <param name="provider">TBD</param>
/// <param name="path">TBD</param>
/// <param name="parent">TBD</param>
/// <param name="log">TBD</param>
public VirtualPathContainer(IActorRefProvider provider, ActorPath path, IInternalActorRef parent, ILoggingAdapter log)
{
_parent = parent;
_log = log;
_provider = provider;
_path = path;
}
/// <summary>
/// TBD
/// </summary>
public override IActorRefProvider Provider
{
get { return _provider; }
}
/// <summary>
/// TBD
/// </summary>
public override IInternalActorRef Parent
{
get { return _parent; }
}
/// <summary>
/// TBD
/// </summary>
public override ActorPath Path
{
get { return _path; }
}
/// <summary>
/// TBD
/// </summary>
public ILoggingAdapter Log
{
get { return _log; }
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <param name="child">TBD</param>
/// <returns>TBD</returns>
protected bool TryGetChild(string name, out IInternalActorRef child)
{
return _children.TryGetValue(name, out child);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <param name="actor">TBD</param>
public void AddChild(string name, IInternalActorRef actor)
{
_children.AddOrUpdate(name, actor, (_, v) =>
{
Log.Warning("{0} replacing child {1} ({2} -> {3})", name, actor, v, actor);
return v;
});
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public void RemoveChild(string name)
{
IInternalActorRef tmp;
if (!_children.TryRemove(name, out tmp))
{
Log.Warning("{0} trying to remove non-child {1}", Path, name);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <param name="child">TBD</param>
public void RemoveChild(string name, IActorRef child)
{
IInternalActorRef tmp;
if (!_children.TryRemove(name, out tmp))
{
Log.Warning("{0} trying to remove non-child {1}", Path, name);
}
}
/*
override def getChild(name: Iterator[String]): InternalActorRef = {
if (name.isEmpty) this
else {
val n = name.next()
if (n.isEmpty) this
else children.get(n) match {
case null ⇒ Nobody
case some ⇒
if (name.isEmpty) some
else some.getChild(name)
}
}
}
*/
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public override IActorRef GetChild(IReadOnlyList<string> name)
{
//Using enumerator to avoid multiple enumerations of name.
if (name.Count == 0)
return this;
var firstName = name[0];
if (string.IsNullOrEmpty(firstName))
return this;
if (_children.TryGetValue(firstName, out var child))
return child.GetChild(name.NoCopySlice(1));
return ActorRefs.Nobody;
}
/// <summary>
/// Returns <c>true</c> if the <see cref="VirtualPathContainer"/> contains any children,
/// <c>false</c> otherwise.
/// </summary>
public bool HasChildren
{
get
{
return !_children.IsEmpty;
}
}
/// <summary>
/// Executes an action for each child in the current collection.
/// </summary>
/// <param name="action">A lambda which takes a reference to the internal child actor as an argument.</param>
public void ForEachChild(Action<IInternalActorRef> action)
{
foreach (IInternalActorRef child in _children.Values)
{
action(child);
}
}
/// <summary>
/// An enumerable that continues where the supplied enumerator is positioned
/// </summary>
private class Enumerable<T> : IEnumerable<T>
{
private readonly IEnumerator<T> _enumerator;
public Enumerable(IEnumerator<T> enumerator)
{
_enumerator = enumerator;
}
public IEnumerator<T> GetEnumerator()
{
return _enumerator;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
/// <summary>
/// INTERNAL API
///
/// This kind of ActorRef passes all received messages to the given function for
/// performing a non-blocking side-effect. The intended use is to transform the
/// message before sending to the real target actor. Such references can be created
/// by calling <see cref="ActorCell.AddFunctionRef(Action{IActorRef, object}, string)"/> and must be deregistered when no longer
/// needed by calling <see cref="ActorCell.RemoveFunctionRef(FunctionRef)"/>. FunctionRefs do not count
/// towards the live children of an actor, they do not receive the Terminate command
/// and do not prevent the parent from terminating. FunctionRef is properly
/// registered for remote lookup and ActorSelection.
///
/// When using the <see cref="ICanWatch.Watch"/> feature you must ensure that upon reception of the
/// Terminated message the watched actorRef is <see cref="ICanWatch.Unwatch"/>ed.
/// </summary>
internal sealed class FunctionRef : MinimalActorRef
{
private readonly EventStream _eventStream;
private readonly Action<IActorRef, object> _tell;
private ImmutableHashSet<IActorRef> _watching = ImmutableHashSet<IActorRef>.Empty;
private ImmutableHashSet<IActorRef> _watchedBy = ImmutableHashSet<IActorRef>.Empty;
public FunctionRef(ActorPath path, IActorRefProvider provider, EventStream eventStream, Action<IActorRef, object> tell)
{
_eventStream = eventStream;
_tell = tell;
Path = path;
Provider = provider;
}
public override ActorPath Path { get; }
public override IActorRefProvider Provider { get; }
public override bool IsTerminated => Volatile.Read(ref _watchedBy) == null;
/// <summary>
/// Have this FunctionRef watch the given Actor. This method must not be
/// called concurrently from different threads, it should only be called by
/// its parent Actor.
///
/// Upon receiving the Terminated message, <see cref="Unwatch"/> must be called from a
/// safe context (i.e. normally from the parent Actor).
/// </summary>
public void Watch(IActorRef actorRef)
{
_watching = _watching.Add(actorRef);
var internalRef = (IInternalActorRef)actorRef;
internalRef.SendSystemMessage(new Watch(internalRef, this));
}
/// <summary>
/// Have this FunctionRef unwatch the given Actor. This method must not be
/// called concurrently from different threads, it should only be called by
/// its parent Actor.
/// </summary>
public void Unwatch(IActorRef actorRef)
{
_watching = _watching.Remove(actorRef);
var internalRef = (IInternalActorRef)actorRef;
internalRef.SendSystemMessage(new Unwatch(internalRef, this));
}
/// <summary>
/// Query whether this FunctionRef is currently watching the given Actor. This
/// method must not be called concurrently from different threads, it should
/// only be called by its parent Actor.
/// </summary>
public bool IsWatching(IActorRef actorRef) => _watching.Contains(actorRef);
protected override void TellInternal(object message, IActorRef sender) => _tell(sender, message);
public override void SendSystemMessage(ISystemMessage message)
{