event_callback.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include "grpc_server.h"
  3. namespace NGrpc {
  4. enum class EQueueEventStatus {
  5. OK,
  6. ERROR
  7. };
  8. template<class TCallback>
  9. class TQueueEventCallback: public IQueueEvent {
  10. public:
  11. TQueueEventCallback(const TCallback& callback)
  12. : Callback(callback)
  13. {}
  14. TQueueEventCallback(TCallback&& callback)
  15. : Callback(std::move(callback))
  16. {}
  17. bool Execute(bool ok) override {
  18. Callback(ok ? EQueueEventStatus::OK : EQueueEventStatus::ERROR);
  19. return false;
  20. }
  21. void DestroyRequest() override {
  22. delete this;
  23. }
  24. private:
  25. TCallback Callback;
  26. };
  27. // Implementation of IQueueEvent that reduces allocations
  28. template<class TSelf>
  29. class TQueueFixedEvent: private IQueueEvent {
  30. using TCallback = void (TSelf::*)(EQueueEventStatus);
  31. public:
  32. TQueueFixedEvent(TSelf* self, TCallback callback)
  33. : Self(self)
  34. , Callback(callback)
  35. { }
  36. IQueueEvent* Prepare() {
  37. Self->Ref();
  38. return this;
  39. }
  40. private:
  41. bool Execute(bool ok) override {
  42. ((*Self).*Callback)(ok ? EQueueEventStatus::OK : EQueueEventStatus::ERROR);
  43. return false;
  44. }
  45. void DestroyRequest() override {
  46. Self->UnRef();
  47. }
  48. private:
  49. TSelf* const Self;
  50. TCallback const Callback;
  51. };
  52. template<class TCallback>
  53. inline IQueueEvent* MakeQueueEventCallback(TCallback&& callback) {
  54. return new TQueueEventCallback<TCallback>(std::forward<TCallback>(callback));
  55. }
  56. template<class T>
  57. inline IQueueEvent* MakeQueueEventCallback(T* self, void (T::*method)(EQueueEventStatus)) {
  58. using TPtr = TIntrusivePtr<T>;
  59. return MakeQueueEventCallback([self = TPtr(self), method] (EQueueEventStatus status) {
  60. ((*self).*method)(status);
  61. });
  62. }
  63. } // namespace NGrpc