aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/remote_connection.h
blob: 575fbff32e3a3fe362991d13311516a98ce97f0a (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#pragma once

#include "async_result.h"
#include "defs.h"
#include "event_loop.h"
#include "left_right_buffer.h"
#include "lfqueue_batch.h"
#include "message_ptr_and_header.h"
#include "nondestroying_holder.h"
#include "remote_connection_status.h"
#include "scheduler_actor.h"
#include "socket_addr.h"
#include "storage.h"
#include "vector_swaps.h"
#include "ybus.h"
#include "misc/granup.h"
#include "misc/tokenquota.h"

#include <library/cpp/messagebus/actor/actor.h>
#include <library/cpp/messagebus/actor/executor.h>
#include <library/cpp/messagebus/actor/queue_for_actor.h>
#include <library/cpp/messagebus/actor/queue_in_actor.h>
#include <library/cpp/messagebus/scheduler/scheduler.h>

#include <util/system/atomic.h>
#include <util/system/event.h>
#include <util/thread/lfstack.h>

namespace NBus { 
    namespace NPrivate { 
        class TRemoteConnection; 

        typedef TIntrusivePtr<TRemoteConnection> TRemoteConnectionPtr; 
        typedef TIntrusivePtr<TBusSessionImpl> TRemoteSessionPtr; 

        static void* const WriteCookie = (void*)1; 
        static void* const ReadCookie = (void*)2; 

        enum { 
            WAKE_QUOTA_MSG = 0x01, 
            WAKE_QUOTA_BYTES = 0x02 
        }; 

        struct TWriterTag {}; 
        struct TReaderTag {}; 
        struct TReconnectTag {}; 
        struct TWakeReaderTag {}; 

        struct TWriterToReaderSocketMessage { 
            TSocket Socket; 
            ui32 SocketVersion; 

            TWriterToReaderSocketMessage(TSocket socket, ui32 socketVersion) 
                : Socket(socket) 
                , SocketVersion(socketVersion) 
            { 
            } 
        }; 

        class TRemoteConnection 
           : public NEventLoop::IEventHandler, 
              public ::NActor::TActor<TRemoteConnection, TWriterTag>, 
              public ::NActor::TActor<TRemoteConnection, TReaderTag>, 
              private ::NActor::TQueueInActor<TRemoteConnection, TWriterToReaderSocketMessage, TReaderTag>, 
              private ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TReconnectTag>, 
              private ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TWakeReaderTag>, 
              public TScheduleActor<TRemoteConnection, TWriterTag> { 
            friend struct TBusSessionImpl; 
            friend class TRemoteClientSession; 
            friend class TRemoteServerSession; 
            friend class ::NActor::TQueueInActor<TRemoteConnection, TWriterToReaderSocketMessage, TReaderTag>; 
            friend class ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TReconnectTag>; 
            friend class ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TWakeReaderTag>; 

        protected: 
            ::NActor::TQueueInActor<TRemoteConnection, TWriterToReaderSocketMessage, TReaderTag>* ReaderGetSocketQueue() { 
                return this; 
            } 

            ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TReconnectTag>* WriterGetReconnectQueue() { 
                return this; 
            } 

            ::NActor::TQueueInActor<TRemoteConnection, ui32, TWriterTag, TWakeReaderTag>* WriterGetWakeQueue() { 
                return this; 
            } 

        protected: 
            TRemoteConnection(TRemoteSessionPtr session, ui64 connectionId, TNetAddr addr); 
            ~TRemoteConnection() override; 

            virtual void ClearOutgoingQueue(TMessagesPtrs&, bool reconnect /* or shutdown */); 

        public: 
            void Send(TNonDestroyingAutoPtr<TBusMessage> msg); 
            void Shutdown(EMessageStatus status); 

            inline const TNetAddr& GetAddr() const noexcept; 

        private: 
            friend class TScheduleConnect; 
            friend class TWorkIO; 

        protected: 
            static size_t MessageSize(TArrayRef<TBusMessagePtrAndHeader>); 
            bool QuotaAcquire(size_t msg, size_t bytes); 
            void QuotaConsume(size_t msg, size_t bytes); 
            void QuotaReturnSelf(size_t items, size_t bytes); 
            bool QuotaReturnValues(size_t items, size_t bytes); 

            bool ReaderProcessBuffer(); 
            bool ReaderFillBuffer(); 
            void ReaderFlushMessages(); 

            void ReadQuotaWakeup(); 
            ui32 WriteWakeFlags() const; 

            virtual bool NeedInterruptRead() { 
                return false; 
            } 

        public: 
            virtual void TryConnect(); 
            void ProcessItem(TReaderTag, ::NActor::TDefaultTag, TWriterToReaderSocketMessage); 
            void ProcessItem(TWriterTag, TReconnectTag, ui32 socketVersion); 
            void ProcessItem(TWriterTag, TWakeReaderTag, ui32 awakeFlags); 
            void Act(TReaderTag); 
            inline void WriterBeforeWriteErrorMessage(TBusMessage*, EMessageStatus); 
            void ClearBeforeSendQueue(EMessageStatus reasonForQueues); 
            void ClearReplyQueue(EMessageStatus reasonForQueues); 
            inline void ProcessBeforeSendQueueMessage(TBusMessage*, TInstant now); 
            void ProcessBeforeSendQueue(TInstant now); 
            void WriterProcessStatusDown(); 
            void ReaderProcessStatusDown(); 
            void ProcessWriterDown(); 
            void DropEnqueuedData(EMessageStatus reason, EMessageStatus reasonForQueues); 
            const TRemoteConnectionWriterStatus& WriterGetStatus(); 
            virtual void WriterFillStatus(); 
            void WriterFillInFlight(); 
            virtual void BeforeTryWrite(); 
            void Act(TWriterTag); 
            void ScheduleRead(); 
            void ScheduleWrite(); 
            void ScheduleShutdownOnServerOrReconnectOnClient(EMessageStatus status, bool writer); 
            void ScheduleShutdown(EMessageStatus status); 
            void WriterFlushBuffer(); 
            void WriterFillBuffer(); 
            void ReaderSendStatus(TInstant now, bool force = false); 
            const TRemoteConnectionReaderStatus& ReaderFillStatus(); 
            void WriterRotateCounters(); 
            void WriterSendStatus(TInstant now, bool force = false); 
            void WriterSendStatusIfNecessary(TInstant now); 
            void QuotaReturnAside(size_t items, size_t bytes); 
            virtual void ReaderProcessMessageUnknownVersion(TArrayRef<const char> dataRef) = 0; 
            bool MessageRead(TArrayRef<const char> dataRef, TInstant now); 
            virtual void MessageSent(TArrayRef<TBusMessagePtrAndHeader> messages) = 0; 

            void CallSerialize(TBusMessage* msg, TBuffer& buffer) const; 
            void SerializeMessage(TBusMessage* msg, TBuffer* data, TMessageCounter* counter) const; 
            TBusMessage* DeserializeMessage(TArrayRef<const char> dataRef, const TBusHeader* header, TMessageCounter* messageCounter, EMessageStatus* status) const; 

            void ResetOneWayFlag(TArrayRef<TBusMessage*>); 

            inline ::NActor::TActor<TRemoteConnection, TWriterTag>* GetWriterActor() { 
                return this; 
            } 
            inline ::NActor::TActor<TRemoteConnection, TReaderTag>* GetReaderActor() { 
                return this; 
            } 
            inline TScheduleActor<TRemoteConnection, TWriterTag>* GetWriterSchedulerActor() { 
                return this; 
            } 

            void WriterErrorMessage(TNonDestroyingAutoPtr<TBusMessage> m, EMessageStatus status); 
            // takes ownership of ms 
            void WriterErrorMessages(const TArrayRef<TBusMessage*> ms, EMessageStatus status); 

            void FireClientConnectionEvent(TClientConnectionEvent::EType); 

            size_t GetInFlight(); 
            size_t GetConnectSyscallsNumForTest(); 

            bool IsReturnConnectFailedImmediately() { 
                return (bool)AtomicGet(ReturnConnectFailedImmediately); 
            } 

            bool IsAlive() const; 

            TRemoteSessionPtr Session; 
            TBusProtocol* const Proto; 
            TBusSessionConfig const Config; 
            bool RemovedFromSession; 
            const ui64 ConnectionId; 
            const TNetAddr PeerAddr; 
            const TBusSocketAddr PeerAddrSocketAddr; 

            const TInstant CreatedTime; 
            TInstant LastConnectAttempt; 
            TAtomic ReturnConnectFailedImmediately; 

        protected: 
            ::NActor::TQueueForActor<TBusMessage*> BeforeSendQueue; 
            TLockFreeStack<TBusHeader> WrongVersionRequests; 

            struct TWriterData { 
                TAtomic Down; 

                NEventLoop::TChannelPtr Channel; 
                ui32 SocketVersion; 

                TRemoteConnectionWriterStatus Status; 
                TInstant StatusLastSendTime; 

                TLocalTasks TimeToRotateCounters; 

                TAtomic InFlight; 

                TTimedMessages SendQueue; 
                ui32 AwakeFlags; 
                EWriterState State; 
                TLeftRightBuffer Buffer; 
                TInstant CorkUntil; 

                TSystemEvent ShutdownComplete;

                void SetChannel(NEventLoop::TChannelPtr channel); 
                void DropChannel(); 

                TWriterData(); 
                ~TWriterData(); 
            }; 

            struct TReaderData { 
                TAtomic Down; 

                NEventLoop::TChannelPtr Channel; 
                ui32 SocketVersion; 

                TRemoteConnectionReaderStatus Status; 
                TInstant StatusLastSendTime; 

                TBuffer Buffer; 
                size_t Offset;    /* offset in read buffer */ 
                size_t MoreBytes; /* more bytes required from socket */ 
                TVectorSwaps<TBusMessagePtrAndHeader> ReadMessages; 

                TSystemEvent ShutdownComplete;

                bool BufferMore() const noexcept { 
                    return MoreBytes > 0; 
                } 

                bool HasBytesInBuf(size_t bytes) noexcept; 
                void SetChannel(NEventLoop::TChannelPtr channel); 
                void DropChannel(); 

                TReaderData(); 
                ~TReaderData(); 
            }; 

            // owned by session status actor 
            struct TGranStatus { 
                TGranStatus(TDuration gran) 
                    : Writer(gran) 
                    , Reader(gran) 
                { 
                } 

                TGranUp<TRemoteConnectionWriterStatus> Writer; 
                TGranUp<TRemoteConnectionReaderStatus> Reader; 
            }; 

            TWriterData WriterData; 
            TReaderData ReaderData; 
            TGranStatus GranStatus; 
            TTokenQuota QuotaMsg; 
            TTokenQuota QuotaBytes; 

            size_t MaxBufferSize; 

            // client connection only 
            TLockFreeQueueBatch<TBusMessagePtrAndHeader, TVectorSwaps> ReplyQueue; 

            EMessageStatus ShutdownReason; 
        };

        inline const TNetAddr& TRemoteConnection::GetAddr() const noexcept { 
            return PeerAddr; 
        } 

        typedef TIntrusivePtr<TRemoteConnection> TRemoteConnectionPtr; 

    }
}