aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/interconnect/handshake_broker.h
blob: f53ab4edd29dbe79b63603744aa9fd2d4053e0dd (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
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
#pragma once

#include <library/cpp/actors/core/actor.h>
#include <library/cpp/actors/core/hfunc.h>
#include <library/cpp/actors/interconnect/events_local.h>

#include <deque>

namespace NActors {
    class TBrokerLeaseHolder {
    public:
        TBrokerLeaseHolder(TActorId waiterId, TActorId brokerId)
            : WaiterId(waiterId)
            , BrokerId(brokerId) {
            if (TActivationContext::Send(new IEventHandle(BrokerId, WaiterId, new TEvHandshakeBrokerTake()))) {
                LeaseRequested = true;
            }
        }

        ~TBrokerLeaseHolder() {
            if (LeaseRequested) {
                TActivationContext::Send(new IEventHandle(BrokerId, WaiterId, new TEvHandshakeBrokerFree()));
            }
        }

        bool IsLeaseRequested() {
            return LeaseRequested;
        }

        void ForgetLease() {
            // only call when TDtorException was caught
            LeaseRequested = false;
        }

    private:
        TActorId WaiterId;
        TActorId BrokerId;
        bool LeaseRequested = false;
    };

    class THandshakeBroker : public TActor<THandshakeBroker> {
    private:
        enum class ESelectionStrategy {
            FIFO = 0,
            LIFO,
            Random,
        };

    private:
        void PermitNext() {
            if (Capacity == 0 && !Waiters.empty()) {
                TActorId waiter;

                switch (SelectionStrategy) {
                case ESelectionStrategy::FIFO:
                    waiter = Waiters.front();
                    Waiters.pop_front();
                    SelectionStrategy = ESelectionStrategy::LIFO;
                    break;

                case ESelectionStrategy::LIFO:
                    waiter = Waiters.back();
                    Waiters.pop_back();
                    SelectionStrategy = ESelectionStrategy::Random;
                    break;

                case ESelectionStrategy::Random: {
                    const auto it = WaiterLookup.begin();
                    waiter = it->first;
                    Waiters.erase(it->second);
                    SelectionStrategy = ESelectionStrategy::FIFO;
                    break;
                }

                default:
                    Y_FAIL("Unimplimented selection strategy");
                }

                const size_t n = WaiterLookup.erase(waiter);
                Y_VERIFY(n == 1);

                Send(waiter, new TEvHandshakeBrokerPermit());
                PermittedLeases.insert(waiter);
            } else {
                Capacity += 1;
            }
        }

    private:
        using TWaiters = std::list<TActorId>;
        TWaiters Waiters;
        std::unordered_map<TActorId, TWaiters::iterator> WaiterLookup;
        std::unordered_set<TActorId> PermittedLeases;

        ESelectionStrategy SelectionStrategy = ESelectionStrategy::FIFO;

        ui32 Capacity;

        void Handle(TEvHandshakeBrokerTake::TPtr &ev) {
            const TActorId sender = ev->Sender;
            if (Capacity > 0) {
                Capacity -= 1;
                PermittedLeases.insert(sender);
                Send(sender, new TEvHandshakeBrokerPermit());
            } else {
                const auto [it, inserted] = WaiterLookup.try_emplace(sender,
                        Waiters.insert(Waiters.end(), sender));
                Y_VERIFY(inserted);
            }
        }

        void Handle(TEvHandshakeBrokerFree::TPtr& ev) {
            const TActorId sender = ev->Sender;
            if (!PermittedLeases.erase(sender)) {
                // Lease was not permitted yet, remove sender from Waiters queue
                const auto it = WaiterLookup.find(sender);
                Y_VERIFY(it != WaiterLookup.end());
                Waiters.erase(it->second);
                WaiterLookup.erase(it);
            }
            PermitNext();
        }

    public:
        THandshakeBroker(ui32 inflightLimit)
            : TActor(&TThis::StateFunc)
            , Capacity(inflightLimit)
        {
        }

        static constexpr char ActorName[] = "HANDSHAKE_BROKER_ACTOR";

        STFUNC(StateFunc) {
            switch (ev->GetTypeRewrite()) {
                hFunc(TEvHandshakeBrokerTake, Handle);
                hFunc(TEvHandshakeBrokerFree, Handle);

            default:
                Y_FAIL("unexpected event 0x%08" PRIx32, ev->GetTypeRewrite());
            }
        }

        void Bootstrap() {
            Become(&TThis::StateFunc);
        };
    };

    inline IActor* CreateHandshakeBroker(ui32 maxCapacity) {
        return new THandshakeBroker(maxCapacity);
    }

    inline TActorId MakeHandshakeBrokerOutId() {
        char x[12] = {'I', 'C', 'H', 's', 'h', 'k', 'B', 'r', 'k', 'O', 'u', 't'};
        return TActorId(0, TStringBuf(std::begin(x), std::end(x)));
    }
};