aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/remote_server_session.cpp
blob: 98ca6436f6c045289b6678eec89359d26ae361e7 (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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include "remote_server_session.h"

#include "remote_connection.h"
#include "remote_server_connection.h"

#include <library/cpp/messagebus/actor/temp_tls_vector.h>

#include <util/generic/cast.h>
#include <util/stream/output.h>
#include <util/system/yassert.h>

#include <typeinfo>

using namespace NActor;
using namespace NBus;
using namespace NBus::NPrivate;

TRemoteServerSession::TRemoteServerSession(TBusMessageQueue* queue,
                                           TBusProtocol* proto, IBusServerHandler* handler,
                                           const TBusServerSessionConfig& config, const TString& name)
    : TBusSessionImpl(false, queue, proto, handler, config, name)
    , ServerOwnedMessages(config.MaxInFlight, config.MaxInFlightBySize, "ServerOwnedMessages")
    , ServerHandler(handler)
{
    if (config.PerConnectionMaxInFlightBySize > 0) {
        if (config.PerConnectionMaxInFlightBySize < config.MaxMessageSize)
            ythrow yexception()
                << "too low PerConnectionMaxInFlightBySize value";
    }
}

namespace NBus {
    namespace NPrivate {
        class TInvokeOnMessage: public IWorkItem {
        private:
            TRemoteServerSession* RemoteServerSession;
            TBusMessagePtrAndHeader Request;
            TIntrusivePtr<TRemoteServerConnection> Connection;

        public:
            TInvokeOnMessage(TRemoteServerSession* session, TBusMessagePtrAndHeader& request, TIntrusivePtr<TRemoteServerConnection>& connection)
                : RemoteServerSession(session)
            {
                Y_ASSERT(!!connection);
                Connection.Swap(connection);

                Request.Swap(request);
            }

            void DoWork() override {
                THolder<TInvokeOnMessage> holder(this);
                RemoteServerSession->InvokeOnMessage(Request, Connection);
                // TODO: TRemoteServerSessionSemaphore should be enough
                RemoteServerSession->JobCount.Decrement();
            }
        };

    }
}

void TRemoteServerSession::OnMessageReceived(TRemoteConnection* c, TVectorSwaps<TBusMessagePtrAndHeader>& messages) {
    AcquireInWorkRequests(messages);

    bool executeInPool = Config.ExecuteOnMessageInWorkerPool;

    TTempTlsVector< ::IWorkItem*> workQueueTemp;

    if (executeInPool) {
        workQueueTemp.GetVector()->reserve(messages.size());
    }

    for (auto& message : messages) {
        // TODO: incref once
        TIntrusivePtr<TRemoteServerConnection> connection(CheckedCast<TRemoteServerConnection*>(c));
        if (executeInPool) {
            workQueueTemp.GetVector()->push_back(new TInvokeOnMessage(this, message, connection));
        } else {
            InvokeOnMessage(message, connection);
        }
    }

    if (executeInPool) {
        JobCount.Add(workQueueTemp.GetVector()->size());
        Queue->EnqueueWork(*workQueueTemp.GetVector());
    }
}

void TRemoteServerSession::InvokeOnMessage(TBusMessagePtrAndHeader& request, TIntrusivePtr<TRemoteServerConnection>& conn) {
    if (Y_UNLIKELY(AtomicGet(Down))) {
        ReleaseInWorkRequests(*conn.Get(), request.MessagePtr.Get());
        InvokeOnError(request.MessagePtr.Release(), MESSAGE_SHUTDOWN);
    } else {
        TWhatThreadDoesPushPop pp("OnMessage");

        TBusIdentity ident;

        ident.Connection.Swap(conn);
        request.MessagePtr->GetIdentity(ident);

        Y_ASSERT(request.MessagePtr->LocalFlags & MESSAGE_IN_WORK);
        DoSwap(request.MessagePtr->LocalFlags, ident.LocalFlags);

        ident.RecvTime = request.MessagePtr->RecvTime;

#ifndef NDEBUG
        auto& message = *request.MessagePtr;
        ident.SetMessageType(typeid(message));
#endif

        TOnMessageContext context(request.MessagePtr.Release(), ident, this);
        ServerHandler->OnMessage(context);
    }
}

EMessageStatus TRemoteServerSession::ForgetRequest(const TBusIdentity& ident) {
    ReleaseInWork(const_cast<TBusIdentity&>(ident));

    return MESSAGE_OK;
}

EMessageStatus TRemoteServerSession::SendReply(const TBusIdentity& ident, TBusMessage* reply) {
    reply->CheckClean();

    ConvertInWork(const_cast<TBusIdentity&>(ident), reply);

    reply->RecvTime = ident.RecvTime;

    ident.Connection->Send(reply);

    return MESSAGE_OK;
}

int TRemoteServerSession::GetInFlight() const noexcept {
    return ServerOwnedMessages.GetCurrentCount();
}

void TRemoteServerSession::FillStatus() {
    TBusSessionImpl::FillStatus();

    // TODO: weird
    StatusData.Status.InFlightCount = ServerOwnedMessages.GetCurrentCount();
    StatusData.Status.InFlightSize = ServerOwnedMessages.GetCurrentSize();
    StatusData.Status.InputPaused = ServerOwnedMessages.IsLocked();
}

void TRemoteServerSession::AcquireInWorkRequests(TArrayRef<const TBusMessagePtrAndHeader> messages) {
    TAtomicBase size = 0;
    for (auto message = messages.begin(); message != messages.end(); ++message) {
        Y_ASSERT(!(message->MessagePtr->LocalFlags & MESSAGE_IN_WORK));
        message->MessagePtr->LocalFlags |= MESSAGE_IN_WORK;
        size += message->MessagePtr->GetHeader()->Size;
    }

    ServerOwnedMessages.IncrementMultiple(messages.size(), size);
}

void TRemoteServerSession::ReleaseInWorkResponses(TArrayRef<const TBusMessagePtrAndHeader> responses) {
    TAtomicBase size = 0;
    for (auto response = responses.begin(); response != responses.end(); ++response) {
        Y_ASSERT((response->MessagePtr->LocalFlags & MESSAGE_REPLY_IS_BEGING_SENT));
        response->MessagePtr->LocalFlags &= ~MESSAGE_REPLY_IS_BEGING_SENT;
        size += response->MessagePtr->RequestSize;
    }

    ServerOwnedMessages.ReleaseMultiple(responses.size(), size);
}

void TRemoteServerSession::ReleaseInWorkRequests(TRemoteConnection& con, TBusMessage* request) {
    Y_ASSERT((request->LocalFlags & MESSAGE_IN_WORK));
    request->LocalFlags &= ~MESSAGE_IN_WORK;

    const size_t size = request->GetHeader()->Size;

    con.QuotaReturnAside(1, size);
    ServerOwnedMessages.ReleaseMultiple(1, size);
}

void TRemoteServerSession::ReleaseInWork(TBusIdentity& ident) {
    ident.SetInWork(false);
    ident.Connection->QuotaReturnAside(1, ident.Size);

    ServerOwnedMessages.ReleaseMultiple(1, ident.Size);
}

void TRemoteServerSession::ConvertInWork(TBusIdentity& req, TBusMessage* reply) {
    reply->SetIdentity(req);

    req.SetInWork(false);
    Y_ASSERT(!(reply->LocalFlags & MESSAGE_REPLY_IS_BEGING_SENT));
    reply->LocalFlags |= MESSAGE_REPLY_IS_BEGING_SENT;
    reply->RequestSize = req.Size;
}

void TRemoteServerSession::Shutdown() {
    ServerOwnedMessages.Stop();
    TBusSessionImpl::Shutdown();
}

void TRemoteServerSession::PauseInput(bool pause) {
    ServerOwnedMessages.PauseByUsed(pause);
}

unsigned TRemoteServerSession::GetActualListenPort() {
    Y_ABORT_UNLESS(Config.ListenPort > 0, "state check");
    return Config.ListenPort;
}