-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathActor.hpp
More file actions
1789 lines (1382 loc) · 67.4 KB
/
Actor.hpp
File metadata and controls
1789 lines (1382 loc) · 67.4 KB
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
/*=============================================================================
Actor
This is a minimalistic implementation of the actor system aiming to rectify
some of the issues with Theron and basing it strictly on modern C++ principles.
The design goals are
1. Do not redo what C++ has as standard: This includes using the standard
memory allocation mechanism. This should also ensure full portability.
The compiler should be able to handle the magic.
2. Simplicity. The main consequence of this is that the actors are supposed
to run on one computer with shared memory
3. Respect the Theron interface. One should be able to replace the Theron main
header with this and recompile. For this reason, there is no dedicated
documentation of the API since one can simply read Theron's documentation.
Currently there is no scheduler. The operating system's thread scheduler is
used. Each actor has its own thread for executing its message handlers. This is
based on the assumption that the system has sufficient memory, and that a
thread not running is not consuming CPU. The actual scheduling of active threads
on the CPU cores should be most efficient in this way. However, one should
measure, and if the execution environment cannot cope with this policy a
thread pool and a scheduling policy can be implemented, although it currently
contradicts the second design principle.
Author and Copyright: Geir Horn, 2017-2018
License: LGPL 3.0
=============================================================================*/
#ifndef THERON_REPLACEMENT_ACTOR
#define THERON_REPLACEMENT_ACTOR
#include <string> // Strings
#include <memory> // Smart pointers
#include <queue> // For the queue of messages
#include <mutex> // To protect the queue
#include <utility> // Pairs
#include <unordered_map> // To map actor names to actors
#include <set> // Set of Presentation Layer addresses
#include <functional> // For defining handler functions
#include <list> // The list of message handlers
#include <algorithm> // Various container related utilities
#include <thread> // To execute actors
#include <condition_variable> // To synchronise threads
#include <atomic> // Thread protected variables
#include <stdexcept> // To throw standard exceptions
#include <sstream> // To provide nice exception messages
#include <type_traits> // For meta-programming
#include <iostream> // For debugging
#include <boost/core/demangle.hpp> // For reporting readable message types
namespace Theron {
// For compatibility reasons there must be a class called Framework and an actor
// has a method that returns a pointer to it. Basically the actor is fully
// replacing the framework. All compatibility classes are defined at the end.
class Framework;
// There are enumerations for a yield strategy, and since the scheduling is
// left for the operating system, these strategies will have no effect.
enum YieldStrategy
{
YIELD_STRATEGY_CONDITION = 0,
YIELD_STRATEGY_HYBRID,
YIELD_STRATEGY_SPIN,
YIELD_STRATEGY_BLOCKING = 0,
YIELD_STRATEGY_POLITE = 0,
YIELD_STRATEGY_STRONG = 1,
YIELD_STRATEGY_AGGRESSIVE = 2
};
// The EndPoint is forward declared because it is used as an argument to one of
// the Framework constructors.
class EndPoint;
// Finally the polymorphic message must be forward declared to avoid circular
// inclusion of headers.
class PolymorphicProtocolHandler;
// In this implementation everything is an actor as there is no compelling
// reason for the other Theron classes.
class Actor
{
/*=============================================================================
Actor identification
=============================================================================*/
//
// Addressing an actor in Theron requires an address object, which can exist
// with or without the existence of the actor it refers to, and the address is
// resolved to an actor only when a message is sent to this actor. Invalid
// addresses are only indicated by the negative result of a message sending.
// There is no way for an actor to detect a priori that an address is invalid,
// and as such the actor address is just like an encapsulated string. Hence,
// there must be an address class (to be defined below).
public:
class Address;
// The consequence of this model is that addresses can be used, for instance
// as keys in lookup tables, and they can outlive the actor addressed. At the
// same time one should be able to look up address by name (string) or by
// numerical ID. In order to ensure transparent actor communication, i.e. the
// actor sending a message should not need to know if the receiver is a local
// actor or a remote actor, the address does not need to point to a physical
// memory location of a local actor.
//
// Furthermore, there are temporal aspects. An actor can be known by its name
// before it is created, making it logically indistinguishable from a remote
// actor. Then when the actor is created it should no longer be taken as a
// possible remote actor, but as a know local actor. This implies that the
// remote actor address either should be transformed to a local object, or
// be removed as a known entity the moment no addresses reference the remote
// actor any more.
//
// The consequence of the transformation property is indirection: The address
// cannot refer directly to the actor address, but to another object that knows
// the actor address, and can take the right message routing decisions depending
// on whether the actor is local, remote, or does not exist. The object
// referenced by the addresses will here be called an actor Identification.
//
// This Identification should only exist as long as there is an address
// referring to it. This could be implemented with some kind of registration
// process where an address register with the Identification object when it is
// created, and then de-register when the address is deleted. The benefit of
// this approach is that the Identification object knows which addresses that
// refers to it. The downside is that this is difficult to implement in a
// multi-threaded implementation since one thread could delete an address
// referring to the Identification and if it is the last address referring
// to this Identification, it should delete the Identification if it is an
// Identification of a remote object. However, if another thread at the very
// same time creates an address referring to the same Identification, it should
// not be deleted. Even if a mutex is used to guarantee that only one address
// can register or de-register at the same time, the order of these two
// operations cannot be predicted and the Identification object can be deleted
// when the next address tries to register.
//
// A simpler implementation, implicitly doing the same registration and
// de-registration would be to consider the addresses as smart pointer to the
// Identification. The Identification object will not know the address objects
// referring to it, but when the last address is removed, the Identification
// object's destructor would be called. A local actor can then just have an
// address to itself, pointing to its Identification object, and ensuring that
// this Identification object is removed when the actor is deleted.
//
// This is a cleaner implementation, but it does not overcome the problem of
// simultaneous deletion and creation of the addresses referring to the object.
// Another form of indirection would come to our rescue: There must be a way
// to refer to an actor, local or remote, by its string name or its numerical
// ID. Hence there must be two lookup tables with references to the
// Identification object. When the object is created, the references must be
// inserted in these lookup tables, and when the object is deleted the
// references must be deleted. Hence, having a mutex for insertions and
// deletions in this lookup table will work. If the deletion event happens
// first, the Identification will be deleted, and then when the creation event
// gets the mutex it will not find any Identification for the ID or the named
// string and assumed it will be a new, remote (or future local) actor and
// create another Identification object. If the creation event is handled first,
// then there will be an address holding a reference to the Identification
// object so the deletion of the other address will just decrement the count of
// references.
//
// -----------------------------------------------------------------------------
// Identification
// -----------------------------------------------------------------------------
//
// An actor has a name and a numerical ID. The latter must be unique independent
// of how many actors that are created and destroyed over the lifetime of the
// application. The Identification object is charged with obtaining the
// numerical ID and store the name and the registration of the Identification
// during the actor's lifetime.
//
// Since an address is a smart pointer to the Identification object, it is
// necessary to be able to create the smart pointer from the object itself, and
// for this it should inherit a particular base class.
private:
class Identification : public std::enable_shared_from_this< Identification >
{
public:
// The Numerical ID of an actor must be long enough to hold the counter of all
// actors created during the application's lifetime.
using IDType = unsigned long;
// It also maintains the actor name and the actual ID assigned to this
// actor. Note that these have to be constant for the full duration of the
// actor's lifetime
const IDType NumericalID;
const std::string Name;
private:
// It maintains a global counter which should be long enough to ensure that
// there are enough IDs for actors. This is incremented by each actor to
// avoid that any two actors get the same ID
static std::atomic< IDType > TotalActorsCreated;
// There is a small function to increment the total number of actors and
// return that ID. It should be noted that since the increment is done before
// the value is returned, the real actors will be numbered from 1... and hence
// 0 is a valid address for the object Address::Null (see below).
inline static IDType GetNewID( void )
{ return ++TotalActorsCreated; }
// There is a pointer to the actor for which this is the ID. This
// will be the real actor on this endpoint, and for actors on remote
// endpoints, it will be the Presentation Layer actor which is responsible for
// the serialisation and forwarding of the message to the remote actor.
// This pointer is Null if no Presentation Layer is registered. Note the
// precedence: The Identification object is created when the first address
// object is created for a named actor. If no Presentation Layer is registered
// the pointer becomes Null, otherwise it will point to the Presentation
// Layer actor. If then an actor with the same name is created, the actor
// pointer will be set to point to this local actor. When the local actor is
// deleted, this pointer is set to Null as all addresses referencing this
// Identification object must be removed before a new Identification object
// can be created for a remote actor of the same name.
Actor * ActorPointer;
// It will also keep track of the known actors, both by name and by ID.
// All actors must have an identification, locally or remotely. It may be
// necessary to look up actors based on their name, and the best way
// to do this is using an unordered map since a lookup should be O(1).
// These maps are protected since it is the responsibility of the derived
// identity classes to ensure that the name and ID is correctly stored.
static std::unordered_map< std::string, Identification * > ActorsByName;
// In the same way there is a lookup map to find the pointer based on the
// actor's ID. This could have been a vector, but it would have been ever
// growing. Having a map allows the storage of only active actors.
static std::unordered_map< IDType, Identification * > ActorsByID;
// Since these three elements are shared among all actors, and actors can
// be created by other actors in the message handlers or otherwise, the
// elements can be operated upon from different threads. It is therefore
// necessary to ensure sequential access by locking a mutex.
static std::recursive_mutex InformationAccess;
// The addresses of the presentation layers are stored in a set to ensure
// that if there is a presentation layer available, it will be able to
// handle messages, and to be resilient against duplicate registrations.
static std::set< Address > PresentationLayerServers;
// The constructor is private and takes a name string only, and assigns a
// unique ID to the Identification object. The reason for keeping it private
// is to ensure that the generator function is used when creating an
// identification object. If the name string is not given a default name
// "ActorNN" will be assigned where the NN is the number of the actor. It
// eventually register the identification object in the two lookups.
Identification( const std::string & ActorName = std::string() );
// The smart pointer to this Identification can be created with a simple
// support function. Even though it is now fundamentally just a renaming of
// the standard mechanism, it does allow flexibility for the future where
// the function could be made virtual to obtain derived identities.
inline std::shared_ptr< Identification > GetSmartPointer( void )
{ return shared_from_this(); }
public:
// Identification objects must be created by a supporting generator function
// that checks that there is no Identification object already defined. In
// this case it will just return an address (reference) to that
// Identification object, after potentially setting its actor pointer to
// the actor. The last behaviour is needed in the case that an Identification
// is first created to an actor by name, and then the actual actor is
// constructed later. Several addresses my then refer to the actor-by-name
// (as a remote actor) already and the integrity of these must be kept. Hence
// a new Identification object cannot be created, which is why there is no
// public constructor.
static Address Create( const std::string & ActorName = std::string(),
Actor * const TheActor = nullptr );
// There are static functions to obtain an address by name or by numerical
// ID.
static Address Lookup( const std::string & ActorName );
static Address Lookup( const IDType TheID );
// Other actors may need to obtain a pointer to this actor, and this can
// only be done through a legal address object. It is not declared in-line
// since it uses the internals of the actor definition. This function will
// throw invalid_argument if the address is not for a valid and running actor.
static Actor * GetActor( const Address & ActorAddress );
// There is a static function used by the actor's destructor to clear the
// actor pointer.
static void ClearActor( const Address & ActorAddress );
// There is a simple test to see if the actor pointer is defined. Note that
// the actor pointer is only defined for actors on the local endpoint so this
// is implicitly a test that the actor is not remote.
inline bool HasActor( void )
{ return ActorPointer != nullptr; }
// A message can be routed to an actor identified by this Identification
// object only if it is a local actor, i.e. the actor pointer is set, OR
// the presentation layer is set. It is not in-line because it uses the
// address implementation to know if the presentation layer is valid.
bool AllowRouting( void );
// A static function is provided to set the presentation layer address
static
void SetPresentationLayerServer( const Address & ThePresentationLayerSever );
// It is a recurring problem to keep main() alive until all actors have done
// their work. The following function can be called to all actors have empty
// queues and no running message handlers. It should then be safe to close the
// application
static void WaitForGlobalTermination( void );
// It is not possible to copy an Identification, or copy assign an
// Identification object.
Identification( const Identification & OtherID ) = delete;
Identification & operator = ( const Identification & OtherID ) = delete;
// The destructor removes the named actor and the ID from the registries,
// and since it implies a structural change of the maps, the lock must be
// acquired. It is automatically released when the destructor terminates.
~Identification( void );
};
/*=============================================================================
Address management
=============================================================================*/
// The main address of an actor is it physical memory location. This can be
// reached only through an address object that has a pointer to the actor
// Identification of the relevant actor. From the previous discussion it may
// be that the Identification fails to point at a real actor, and there is
// no guarantee that a message can be sent to an address - it should be checked
// first, otherwise the send function may throw (see below).
public:
class Address : protected std::shared_ptr< Identification >
{
private:
// There is a standard constructor from another shared Identification pointer
Address( std::shared_ptr< Identification > & OtherAddress )
: std::shared_ptr< Identification >( OtherAddress )
{ }
// A similar constructor is needed to move the other address pointer if it
// is assigned as a temporary variable.
Address( std::shared_ptr< Identification > && OtherAddress )
: std::shared_ptr< Identification >( OtherAddress )
{ }
// The identification class is allowed to use the shared pointer constructors
friend class Identification;
public:
// The copy constructor is currently just doing the same as the shared
// pointer constructor since the address has now own data fields to be copied
inline Address( const Address & OtherAddress )
: std::shared_ptr< Identification >( OtherAddress )
{ }
// The move constructor is similarly trivial
inline Address( Address && OtherAddress )
: std::shared_ptr< Identification >( OtherAddress )
{ }
// The void constructor simply default initialises the pointer
inline Address( void )
: std::shared_ptr<Identification>()
{}
// There is constructor to find an address by name and it is suspected that
// this will be used also for the plain string defined by Theron
// (const char *const name). These will simply use the Actor identification's
// lookup, and then delegate to the above constructors.
inline Address( std::string_view Name )
: Address( Identification::Lookup( std::string( Name ) ) )
{
// The lookup may fail if no actor, either locally or remotely, exists by
// that name. In that case, it is understood that this is a reference to
// a remote actor, or to a local actor not yet created, and the
// corresponding address object is constructed and assigned to this
// address.
if ( get() == nullptr )
*this = Identification::Create( std::string( Name ) );
}
// Oddly enough, but Theron has no constructor to get an address by the
// numerical ID of the actor, however here one is provided now.
inline Address( const Identification::IDType & ID )
: Address( Identification::Lookup( ID ) )
{ }
// There is an assignment operator that basically makes a copy of the
// other Address. However, since it is called on an already existing
// address, it must assign to its own shared pointer
inline Address & operator= ( const Address & OtherAddress )
{
std::shared_ptr< Identification >::operator = ( OtherAddress );
return *this;
}
// It should have a static function Null to allow test addresses
static const Address Null( void )
{ return Address(); }
// There is an implicit conversion to a boolean to check if the address is
// valid or not. An address is valid if it points at an Identification object,
// AND the Identification object can be used for routing.
inline operator bool (void ) const
{ return (get() != nullptr) && get()->AllowRouting(); }
// There are comparison operators to allow the address to be used in standard
// containers.
inline bool operator == ( const Address & OtherAddress ) const
{
if ( get() != nullptr )
if ( OtherAddress.get() != nullptr )
return get()->NumericalID == OtherAddress->NumericalID;
else
return false; // Other address is Null
else
if ( OtherAddress.get() == nullptr )
return true; // both are Null
else
return false; // Other address is not Null, but this is
}
inline bool operator != ( const Address & OtherAddress ) const
{
if ( get() != nullptr )
if ( OtherAddress.get() != nullptr )
return get()->NumericalID != OtherAddress->NumericalID;
else
return true; // Other address is Null
else
if ( OtherAddress.get() == nullptr )
return false; // Both are Null
else
return true; // Other address is not Null, but this is
}
// The less-than operator is more interesting since the address could be
// Null and how does that compare with other addresses? It is here defined
// that a Null address will be larger than any other address since it is
// assumed that this operator defines sorting order in containers and then
// it makes sense if the Null operator comes last.
bool operator < ( const Address & OtherAddress ) const
{
if ( get() == nullptr )
return true;
else
if ( OtherAddress.get() == nullptr ) return true;
else
return get()->NumericalID < OtherAddress->NumericalID;
}
// There is another function to check if a given address is a local actor.
inline bool IsLocalActor( void ) const
{
return ( get() != nullptr ) && ( get()->HasActor() );
}
// Then it must provide access to the actor's name and ID that can be
// taken from the actor's stored information. If these are called on a Null
// address, they will NULL in some form.
inline std::string AsString( void ) const
{
if ( get() == nullptr )
return "Address::Null";
else
return get()->Name;
}
inline Identification::IDType AsInteger( void ) const
{
if ( get() == nullptr )
return Identification::IDType(0);
else
return get()->NumericalID;
}
inline Identification::IDType AsUInt64( void ) const
{ return AsInteger(); }
// There is a legacy function to obtain the numerical ID of the framework,
// which is here taken identical to the actor pointed to by this address.
inline Identification::IDType GetFramework( void ) const
{
if ( get() == nullptr )
return Identification::IDType(0);
else
return get()->NumericalID;
}
};
// The actor itself has its own ID as an address
private:
Address ActorID;
// The standard way of obtaining the address of an actor will then just return
// this address, which will be implicitly copied to some other address.
public:
inline Address GetAddress( void ) const
{
return ActorID;
}
// There is a function to check if an address corresponds to a local actor.
// The best would be to call the function on the address, but this is an
// indirect way of doing the same. It is static since it can be called
// without having an actor.
inline static bool IsLocalActor( const Address & RequestedActorID )
{
return RequestedActorID.IsLocalActor();
}
// In the same way one may look up an actor name as a string. This will then
// first make an address for that actor and then check if it is local.
inline static bool IsLocalActor( const std::string & ActorName )
{
return Address( ActorName ).IsLocalActor();
}
// The Presentation layer address needed to support external communication can
// be set with the a static function defined in the Identification class, but
// the Identification class is and should be a private class of the Actor. An
// interface is therefore provided to allow the Presentation Layer to register
// with this function.
inline static void SetPresentationLayerServer(
const Address & ThePresentationLayerSever )
{ Identification::SetPresentationLayerServer( ThePresentationLayerSever ); }
/*=============================================================================
Messages
=============================================================================*/
// One of the main reasons for doing this re-design is the message handling and
// its link to a complicated memory management and the possibility not to use
// the Run-time type information (RTTI). Understandably, this may be needed for
// embedded applications but it makes it hard to follow the message flow, and
// it is error prone. The current effort is motivated by the fact that null
// pointer messages happened frequently in a larger actor system bringing down
// the whole application and basically making Theron useless.
//
// The approach taken here is simply that each actor has its own message queue
// and that the send operation on one actor simply inserts the message into
// the message queue of the receiving actor. Thus, the message is created once,
// and deleted when it has been consumed. C++ and RTTI will have to take care
// of the polymorphic messages.
//
// The message stores the address of the sending actor, and has a method to
// be used by the queue handler when checking if it can be forwarded to the
// registered message handlers. The To address is not needed for messages sent
// to local actors, although it can be useful for debugging purposes. The To
// address is sent with the message for remote communication so that the
// remote endpoint can deliver the message to the right actor.
protected:
class GenericMessage
{
public:
const Address From, To;
inline GenericMessage( const Address & Sender, const Address & Receiver )
: From( Sender ), To( Receiver )
{ }
inline GenericMessage( void )
: From(), To()
{ }
// The copy constructor simply relay the construction to the standard
// constructor
inline GenericMessage( const GenericMessage & OtherMessage )
: GenericMessage( OtherMessage.From, OtherMessage.To )
{ }
// Communication with actors on other endpoints is supported through a
// virtual function returning a pointer to the external message. This
// function is overloaded by the typed message class below
// if the message type does support external transmission.
virtual std::shared_ptr< PolymorphicProtocolHandler >
GetPolymorphicMessagePointer(void);
// There is also a virtual function to get a printable name string indicating
// the message type. This must be provided by the specific message types
virtual std::string GetMessageTypeName( void ) const
{ return std::string( "Generic message base class" ); }
// It is important to make this class polymorphic by having at least one
// virtual method, and it must in order to ensure proper destruction of the
// derived messages.
virtual ~GenericMessage( void )
{ }
};
// -----------------------------------------------------------------------------
// Message queue
// -----------------------------------------------------------------------------
//
// Each actor has a queue of messages and add new messages to the end and
// consume from the front of the queue. It can therefore be implemented as a
// standard queue. Other Actors will place messages for this actor into this
// queue, and this actor will consume messages from this queue. Hence, this
// queue will be the a memory resource shared and accessed by several threads
// and it therefore needs proper mutex protection. The access to the standard
// queue is consequently encapsulated in a message queue class. It is a private
// class as no derived actor should need to directly invoke any of the provided
// methods.
private:
class MessageQueue : protected std::queue< std::shared_ptr< GenericMessage > >
{
private:
// The messages queue has a mutex to serialise access to the queue, and it
// supports the notification of two events: One for the arrival of a new
// message and one for the completed message handling. One for ingress
// messages and one for egress.
std::mutex QueueGuard;
std::condition_variable NewMessage, MessageDone;
// An interesting aspect with waiting for these events is that the condition
// triggering the event may have changed when the thread waiting for the event
// is started. For instance, if one is waiting for a new message on an empty
// queue, this message could already be processed by the time the thread
// waiting for this signal gets an opportunity to run. Checking the size of
// the queue would then again yield an empty queue, and there should be no
// reason to terminate the wait. This condition would not happen if the
// following requirements are fulfilled by the thread implementation:
//
// 1) A notifying all waiting threads will immediately make them ready to
// run and they will all try to lock the mutex.
// 2) Access to the mutex is given in order of request. In other words,
// all the threads woken by the notification will have locked the mutex
// before the lock would again be acquired from this thread to add or
// delete messages.
//
// It has not been possible to find any documentation for this behaviour,
// although it is reasonable.
public:
// The fundamental operations is to store a message and to delete the first
// message of the queue. The two operations will signal the corresponding
// condition variable.
void StoreMessage( const std::shared_ptr< GenericMessage > & TheMessage );
void DeleteFirstMessage( void );
// The owning actor will need to access the first message in the queue, and
// since messages in the queue can only be deleted by the owning actor when
// the message has been handled, it is a safe operation to read the first
// element and the standard 'front' function for the queue is directly used
using std::queue< std::shared_ptr< GenericMessage > >::front;
// The size type of the queue is also allowed for external access to ensure
// that other types are using the correct type
using std::queue< std::shared_ptr< GenericMessage > >::size_type;
// Reading the current size of the queue should be allowed
using std::queue< std::shared_ptr< GenericMessage > >::size;
// There is a function to check if the queue is empty, and to ensure the
// correctness of the test, it must prevent new messages from arriving while
// the test is performed. It can also be that one would like to wait for the
// next message if the queue is empty. It therefore supports two alternatives
enum class QueueEmpty
{
Return,
Wait
};
bool HasMessage( QueueEmpty Action = QueueEmpty::Return );
// It could also be that one would like to wait for the next message to
// arrive. This function will therefore block the calling thread until the
// next message arrives and the new message condition is signalled. It
// optionally takes an address of a sender to wait for and if this is given
// it will continue to wait until a message from that sender is received.
// It is up to the application to ensure that this will not block forever in
// that case; or in the case there will never be another message for this
// actor.
void WaitForNextMessage( const Address & SenderToWaitFor = Address::Null() );
// Finally, there is a method to wait for the queue to become empty. Again,
// this cannot be called from one of the actor's message handlers as that
// will create a deadlock, but it could be necessary for one actor to wait
// until another actor has processed all of its messages.
void WaitUntilEmpty( void );
// The constructor is simply a place holder for initialising the queue and
// the locks
MessageQueue( void )
: std::queue< std::shared_ptr< GenericMessage > >(),
QueueGuard(), NewMessage(), MessageDone()
{ }
// The destructor does nothing special and the default destructor is good
// enough.
} Mailbox;
// The size type is defined as it is convenient to use for anything that has
// to do with the message queue
protected:
using MessageCount = MessageQueue::size_type;
//
// -----------------------------------------------------------------------------
// Specific message type
// -----------------------------------------------------------------------------
//
// The type specific message will define the function to process the message
// by first trying to cast the handler to the handler templated for the
// actual message type, and if successful, it will invoke the handler function.
template< class MessageType >
class Message : public GenericMessage
{
public:
const std::shared_ptr< MessageType > TheMessage;
Message( const std::shared_ptr< MessageType > & MessageCopy,
const Address & From, const Address & To )
: GenericMessage( From, To ), TheMessage( MessageCopy )
{ }
Message( const Message< MessageType > & OtherMessage )
: GenericMessage( OtherMessage ), TheMessage( OtherMessage.TheMessage )
{ }
// A message that can be serialised must be derived from the Serial Message
// type, and a check for this can be done at compile time. The "if constexpr"
// is a C++17 feature that allow the compiler to compute the condition at
// compile time and not generate code if the condition is false. Prior to
// this it would require all branches to compile, and it would have been
// necessary to use std::enable_if on a template representing the two
// branches.
virtual std::shared_ptr< PolymorphicProtocolHandler >
GetPolymorphicMessagePointer( void ) override
{
if constexpr ( std::is_base_of< PolymorphicProtocolHandler, MessageType >::value )
return TheMessage;
else
return std::shared_ptr< PolymorphicProtocolHandler >();
}
// There is a support function to report the type of the message in a
// human readable form for error messages.
virtual std::string GetMessageTypeName( void ) const override
{ return boost::core::demangle( typeid( MessageType ).name() ); }
// The virtual destructor is just a place holder
virtual ~Message( void )
{ }
};
//
// -----------------------------------------------------------------------------
// Message functions
// -----------------------------------------------------------------------------
//
// Messages are queued a dedicated function that obtains a unique lock on the
// queue guard before adding the message. The return type could be used to
// indicate issues with the queuing, but the function should really throw
// an exception in case of serious errors. The function is virtual in order
// to implement transparent communication. Theron's message handlers does not
// contain the "To" address of a message because they are called on the
// receiving actor. However, if the receiving actor is remote, the message
// hander should be on the Presentation Layer for serialising the message for
// network transfer. The "To" address needs to be a part of the serialised
// message, and hence the Presentation Layer needs to catch the Generic
// Message.
protected:
virtual
bool EnqueueMessage( const std::shared_ptr< GenericMessage > & TheMessage );
// There is a utility variant of this function that can be used in the rare
// cases where an actor operates as a "man in the middle" receiving messages
// for other actors and has no message handler to manage the messages in the
// correct way.
inline bool
EnqueueMessage(const Address TheReceiver,
const std::shared_ptr<GenericMessage> & TheMessage )
{
if ( TheReceiver )
Identification::GetActor( TheReceiver )->EnqueueMessage( TheMessage );
else
{
std::ostringstream ErrorMessage;
ErrorMessage << __FILE__ << " at line " << __LINE__ << ":"
<< "Delegated message enqueue: The address of the receiving "
<< "actor must be a legal address";
throw std::invalid_argument( ErrorMessage.str() );
}
return true;
}
// There is a callback function invoked by the Postman when a new message has
// been processed. It is virtual in order to allow derived classes to be
// notified when a message has been processed.
protected:
virtual void MessageProcessed( void );
// Theron provides a function to check the number of queued messages, which
// essentially only returns the current queue size, including the message
// being handled. There is no need to acquire a lock because the function only
// reads the value and makes no structural changes to the queue.
public:
inline MessageCount GetNumQueuedMessages( void ) const
{ return Mailbox.size(); }
// -----------------------------------------------------------------------------
// Sending messages
// -----------------------------------------------------------------------------
//
// The main send function allocates a new message of the provided type and
// enqueues this with the receiving actor. This is the version of the send
// function found in the Framework in Theron.
public:
template< class MessageType >
static bool Send( const MessageType & TheMessage,
const Address & TheSender,
const Address & TheReceiver )
{
static_assert( std::is_copy_constructible< MessageType >::value,
"The message to send must be copy constructible" );
Actor * ReceivingActor;
if ( TheReceiver )
ReceivingActor = Identification::GetActor( TheReceiver );
else
{
std::ostringstream ErrorMessage;
ErrorMessage << __FILE__ << " at line " << __LINE__ << ":"
<< "Send message: The address of the receiving actor must "
<< "be a legal address";
throw std::invalid_argument( ErrorMessage.str() );
}
auto MessageCopy = std::make_shared< MessageType >( TheMessage );
return
ReceivingActor->EnqueueMessage( std::make_shared< Message< MessageType> >(
MessageCopy, TheSender, TheReceiver ));
}
// Theron's actor has a simplified version of the send function basically just
// inserting its own address for the sender's address.
protected:
template< class MessageType >
inline bool Send( const MessageType & TheMessage,
const Address & TheReceiver ) const
{
return Send( TheMessage, GetAddress(), TheReceiver );
}
/*=============================================================================
Handlers
=============================================================================*/
// The Generic Message class is only supposed to be a polymorphic place holder
// for the type specific messages constructed by the send function. It provides
// an interface for a generic message handler, and will call this if its pointer
// can be cast into the type specific handler class (see below).
private:
class GenericHandler
{
public:
enum class State
{
Normal,
Executing,
Deleted
};
protected:
State CurrentStatus;
public:
// A function to get the handler state.
inline State GetStatus( void )
{ return CurrentStatus; }
// And another one to set the status that is only used from the de-registration
// function if this this handler should be deleted.
inline void SetStatus( const State NewState )
{ CurrentStatus = NewState; }
// There is a function to execute the handler on a given message
virtual bool ProcessMessage(
std::shared_ptr< GenericMessage > & TheMessage ) = 0;
// The constructor simply sets the status to normal