aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/grpc/server/event_callback.h
blob: d0b700b3c9286df09166aad40300045889be2ef1 (plain) (blame)
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
#pragma once

#include "grpc_server.h"

namespace NGrpc {

enum class EQueueEventStatus {
    OK,
    ERROR
};

template<class TCallback>
class TQueueEventCallback: public IQueueEvent {
public:
    TQueueEventCallback(const TCallback& callback)
        : Callback(callback)
    {}

    TQueueEventCallback(TCallback&& callback)
        : Callback(std::move(callback))
    {}

    bool Execute(bool ok) override {
        Callback(ok ? EQueueEventStatus::OK : EQueueEventStatus::ERROR);
        return false;
    }

    void DestroyRequest() override {
        delete this;
    }

private:
    TCallback Callback;
};

// Implementation of IQueueEvent that reduces allocations
template<class TSelf>
class TQueueFixedEvent: private IQueueEvent {
    using TCallback = void (TSelf::*)(EQueueEventStatus);

public:
    TQueueFixedEvent(TSelf* self, TCallback callback)
        : Self(self)
        , Callback(callback)
    { }

    IQueueEvent* Prepare() {
        Self->Ref();
        return this;
    }

private:
    bool Execute(bool ok) override {
        ((*Self).*Callback)(ok ? EQueueEventStatus::OK : EQueueEventStatus::ERROR);
        return false;
    }

    void DestroyRequest() override {
        Self->UnRef();
    }

private:
    TSelf* const Self;
    TCallback const Callback;
};

template<class TCallback>
inline IQueueEvent* MakeQueueEventCallback(TCallback&& callback) {
    return new TQueueEventCallback<TCallback>(std::forward<TCallback>(callback));
}

template<class T>
inline IQueueEvent* MakeQueueEventCallback(T* self, void (T::*method)(EQueueEventStatus)) {
    using TPtr = TIntrusivePtr<T>;
    return MakeQueueEventCallback([self = TPtr(self), method] (EQueueEventStatus status) {
        ((*self).*method)(status);
    });
}

} // namespace NGrpc