COROIO: coroio/actors/actor.hpp Source File
COROIO
Loading...
Searching...
No Matches
actor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <assert.h>
4#include <memory>
6#include <coroio/notifier.hpp>
7#include "messages.hpp"
8#include "actorid.hpp"
9
108
109namespace NNet {
110namespace NActors {
111
112class TActorSystem;
113class IActor;
114
129
130using TEvent = std::pair<unsigned, TTime>;
131
147class TActorContext
148{
149public:
150 using TPtr = std::unique_ptr<TActorContext>;
151
153 TActorId Sender() const {
154 return Sender_;
155 }
156
158 TActorId Self() const {
159 return Self_;
160 }
161
162#ifndef _WIN32
164 std::unique_ptr<INotifier> CreateNotifier();
165#endif
166
173 void Send(TActorId to, TMessageId messageId, TBlob blob);
174
181 void Forward(TActorId to, TMessageId messageId, TBlob blob);
182
197 template<typename T, typename... Args>
198 void Send(TActorId to, Args&&... args);
199
211 template<typename T, typename... Args>
212 void Forward(TActorId to, Args&&... args);
213
221 void SendAs(TActorId from, TActorId to, TMessageId messageId, TBlob blob);
222
233 template<typename T, typename... Args>
234 void SendAs(TActorId from, TActorId to, Args&&... args);
235
245 TEvent Schedule(TTime when, TActorId sender, TActorId recipient, TMessageId messageId, TBlob blob);
246
256 template<typename T, typename... Args>
257 TEvent Schedule(TTime when, TActorId sender, TActorId recipient, Args&&... args);
258
263 void Cancel(TEvent event);
264
270 TActorId Register(std::unique_ptr<IActor> actor);
271
282 TFuture<void> Sleep(TTime until);
283
298 template<typename Rep, typename Period>
299 TFuture<void> Sleep(std::chrono::duration<Rep,Period> duration);
300
318 template<typename T, typename TQuestion>
319 TFuture<T> Ask(TActorId recipient, TQuestion&& question);
320
328 struct TAsync {
329 TAsync(TActorSystem* actorSystem, TLocalActorId actorId)
330 : ActorSystem_(actorSystem)
331 , ActorId_(actorId)
332 { }
333
334 void Commit(TFuture<void>&& future);
335
336 private:
337 TLocalActorId ActorId_;
338 TActorSystem* ActorSystem_;
339 };
340
346
347 static void* operator new(size_t) = delete;
348 static void* operator new(size_t size, TActorSystem* actorSystem);
349 static void operator delete(void* ptr);
350
351private:
352 TActorContext(TActorId sender, TActorId self, TActorSystem* actorSystem)
353 : Sender_(sender)
354 , Self_(self)
355 , ActorSystem(actorSystem)
356 { }
357
358 TActorId Sender_;
359 TActorId Self_;
360 TActorSystem* ActorSystem = nullptr;
361
362 friend class TActorSystem;
363 friend class TMockActorContext;
364};
365
372class TMockActorContext : public TActorContext {
373public:
374 TMockActorContext(TActorId sender, TActorId self, TActorSystem* actorSystem)
375 : TActorContext(sender, self, actorSystem)
376 { }
377};
378
389class IActor {
390public:
391 using TPtr = std::unique_ptr<IActor>;
392 friend class TActorSystem;
393
394 IActor() = default;
395 virtual ~IActor() = default;
396
407 virtual void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) = 0;
408
415 virtual void AfterRegister(TActorContext::TPtr) { }
416
423 virtual void BeforeUnregister(TActorContext::TPtr) { }
424};
425
447class ICoroActor : public IActor {
448public:
455 void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final;
456
470 virtual TFuture<void> CoReceive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) = 0;
471};
472
481public:
482 virtual ~IBehavior() = default;
483
490 virtual void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) = 0;
491};
492
524template<typename TBaseBehavior, typename... TMessages>
525class TBehavior : public IBehavior
526{
527public:
537 void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final {
538 bool handled = (TryHandleMessage<TMessages>(
539 messageId,
540 blob,
541 ctx
542 ) || ...);
543
544 if (!handled) {
545 static_cast<TBaseBehavior*>(this)->HandleUnknownMessage(messageId, std::move(blob), std::move(ctx));
546 }
547 }
548
549private:
550 template<typename TMessage>
551 bool TryHandleMessage(TMessageId messageId, TBlob& blob, TActorContext::TPtr& ctx) {
552 if (TMessage::MessageId == messageId) {
553 if (blob.Type == TBlob::PointerType::Near) {
554 auto&& mes = DeserializeNear<TMessage>(blob);
555 HandleMessage<TMessage>(
556 std::move(mes),
557 std::move(blob),
558 std::move(ctx)
559 );
560 } else if constexpr (is_local_message_v<TMessage>) {
561 return false;
562 } else {
563 auto&& mes = DeserializeFar<TMessage>(blob);
564 HandleMessage<TMessage>(
565 std::move(mes),
566 std::move(blob),
567 std::move(ctx)
568 );
569 }
570 return true;
571 }
572 return false;
573 }
574
575 template<typename TMessage>
576 void HandleMessage(TMessage&& message, TBlob blob, TActorContext::TPtr ctx)
577 {
578 using ReturnType = decltype(static_cast<TBaseBehavior*>(this)->Receive(
579 std::declval<TMessage>(),
580 std::declval<TBlob>(),
581 std::declval<TActorContext::TPtr>()
582 ));
583
584 if constexpr (std::is_same_v<ReturnType, void>) {
585 static_cast<TBaseBehavior*>(this)->Receive(
586 std::move(message),
587 std::move(blob),
588 std::move(ctx)
589 );
590 } else {
591 auto async = ctx->StartAsync();
592 auto future = static_cast<TBaseBehavior*>(this)->Receive(
593 std::move(message),
594 std::move(blob),
595 std::move(ctx)
596 );
597 if (!future.done()) {
598 async.Commit(std::move(future));
599 }
600 }
601 }
602};
603
642class IBehaviorActor : public IActor {
643public:
653 void Become(IBehavior* behavior) {
654 CurrentBehavior_ = behavior;
655 }
656
663 void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final {
664 assert(CurrentBehavior_);
665 CurrentBehavior_->Receive(messageId, std::move(blob), std::move(ctx));
666 }
667
668private:
669 IBehavior* CurrentBehavior_ = nullptr;
670};
671
672} // namespace NActors
673} // namespace NNet
Base interface for all actors in the system.
Definition actor.hpp:389
virtual void BeforeUnregister(TActorContext::TPtr)
Called once on PoisonPill, right before the actor is destroyed.
Definition actor.hpp:423
virtual void AfterRegister(TActorContext::TPtr)
Called once right after the actor is registered in the system.
Definition actor.hpp:415
virtual void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx)=0
Process an incoming message.
Actor that delegates message handling to a pluggable behavior.
Definition actor.hpp:642
void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final
Delegate message handling to the current behavior.
Definition actor.hpp:663
void Become(IBehavior *behavior)
Switch to a new behavior.
Definition actor.hpp:653
Base interface for actor behaviors.
Definition actor.hpp:480
virtual void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx)=0
Process an incoming message according to this behavior.
Coroutine-based actor interface for asynchronous message processing.
Definition actor.hpp:447
void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final
IActor bridge — invokes CoReceive and parks pending futures.
Definition actor.cpp:7
virtual TFuture< void > CoReceive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx)=0
Asynchronous message handler (override in subclass).
TActorId Self() const
Get this actor's ID.
Definition actor.hpp:158
void SendAs(TActorId from, TActorId to, TMessageId messageId, TBlob blob)
Send a message with an explicitly specified sender.
Definition actorsystem.cpp:41
void Forward(TActorId to, TMessageId messageId, TBlob blob)
Forward a message to another actor (preserves original sender).
Definition actorsystem.cpp:36
TFuture< void > Sleep(TTime until)
Suspend the current handler until a specific time.
Definition actorsystem.hpp:524
TActorId Register(std::unique_ptr< IActor > actor)
Registers a new actor in the same actor system.
Definition actorsystem.cpp:56
TFuture< T > Ask(TActorId recipient, TQuestion &&question)
Send a request and suspend until a reply of type T arrives.
Definition actorsystem.hpp:534
std::unique_ptr< INotifier > CreateNotifier()
Creates a notifier bound to the actor system's poller, on the poller thread.
Definition actorsystem.cpp:26
void Cancel(TEvent event)
Cancel a previously scheduled message.
Definition actorsystem.cpp:51
void Send(TActorId to, TMessageId messageId, TBlob blob)
Send a message to another actor.
Definition actorsystem.cpp:31
TAsync StartAsync()
Start an asynchronous operation context.
Definition actor.cpp:16
TEvent Schedule(TTime when, TActorId sender, TActorId recipient, TMessageId messageId, TBlob blob)
Schedule a message to be delivered at a specific time.
Definition actorsystem.cpp:46
TActorId Sender() const
Get the sender of the current message.
Definition actor.hpp:153
Globally unique identifier for actors across a distributed system.
Definition actorid.hpp:34
Single-threaded actor runtime.
Definition actorsystem.hpp:101
Template for type-safe behavior implementations.
Definition actor.hpp:526
void Receive(TMessageId messageId, TBlob blob, TActorContext::TPtr ctx) final
Process incoming message with automatic type dispatch.
Definition actor.hpp:537
Message envelope containing routing and payload information.
Definition actor.hpp:122
TActorId Recipient
Actor that should receive the message.
Definition actor.hpp:125
TBlob Blob
Serialized message data.
Definition actor.hpp:127
TActorId Sender
Actor that sent the message.
Definition actor.hpp:124
TMessageId MessageId
Type identifier of the message.
Definition actor.hpp:126
Mock actor context for testing purposes.
Definition actor.hpp:372
Implementation of a promise/future system for coroutines.
Helper class for managing asynchronous operations in actors.
Definition actor.hpp:328
Opaque message payload with Near/Far duality.
Definition messages.hpp:101
@ Near
Live object pointer — valid only within the same process.
Definition messages.hpp:106
Owned coroutine handle that carries a result of type T.
Definition corochain.hpp:185