executelater.h 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "actor_bootstrapped.h"
  3. #include <utility>
  4. namespace NActors {
  5. template <typename TCallback>
  6. class TExecuteLater: public TActorBootstrapped<TExecuteLater<TCallback>> {
  7. public:
  8. static constexpr char ActorName[] = "AS_EXECUTE_LATER";
  9. TExecuteLater(
  10. TCallback&& callback,
  11. IActor::EActivityType activityType,
  12. ui32 channel = 0,
  13. ui64 cookie = 0,
  14. const TActorId& reportCompletionTo = TActorId(),
  15. const TActorId& reportExceptionTo = TActorId()) noexcept
  16. : Callback(std::move(callback))
  17. , Channel(channel)
  18. , Cookie(cookie)
  19. , ReportCompletionTo(reportCompletionTo)
  20. , ReportExceptionTo(reportExceptionTo)
  21. {
  22. this->SetActivityType(activityType);
  23. }
  24. void Bootstrap(const TActorContext& ctx) noexcept {
  25. try {
  26. {
  27. /* RAII, Callback should be destroyed right before sending
  28. TEvCallbackCompletion */
  29. auto local = std::move(Callback);
  30. using T = decltype(local);
  31. if constexpr (std::is_invocable_v<T, const TActorContext&>) {
  32. local(ctx);
  33. } else {
  34. local();
  35. }
  36. }
  37. if (ReportCompletionTo) {
  38. ctx.Send(ReportCompletionTo,
  39. new TEvents::TEvCallbackCompletion(ctx.SelfID),
  40. Channel, Cookie);
  41. }
  42. } catch (...) {
  43. if (ReportExceptionTo) {
  44. const TString msg = CurrentExceptionMessage();
  45. ctx.Send(ReportExceptionTo,
  46. new TEvents::TEvCallbackException(ctx.SelfID, msg),
  47. Channel, Cookie);
  48. }
  49. }
  50. this->Die(ctx);
  51. }
  52. private:
  53. TCallback Callback;
  54. const ui32 Channel;
  55. const ui64 Cookie;
  56. const TActorId ReportCompletionTo;
  57. const TActorId ReportExceptionTo;
  58. };
  59. template <typename T>
  60. IActor* CreateExecuteLaterActor(
  61. T&& func,
  62. IActor::EActivityType activityType,
  63. ui32 channel = 0,
  64. ui64 cookie = 0,
  65. const TActorId& reportCompletionTo = TActorId(),
  66. const TActorId& reportExceptionTo = TActorId()) noexcept {
  67. return new TExecuteLater<T>(std::forward<T>(func),
  68. activityType,
  69. channel,
  70. cookie,
  71. reportCompletionTo,
  72. reportExceptionTo);
  73. }
  74. }