aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/netliba.cpp
blob: f69906f3ba6d444a5b4f09284fa2e98472e6d0ae (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#include "details.h"
#include "factory.h"
#include "http_common.h"
#include "location.h"
#include "multi.h"
#include "netliba.h"
#include "netliba_udp_http.h"
#include "lfqueue.h"
#include "utils.h"

#include <library/cpp/dns/cache.h>

#include <util/generic/hash.h>
#include <util/generic/singleton.h>
#include <util/generic/vector.h>
#include <util/generic/yexception.h>
#include <util/string/cast.h>
#include <util/system/yassert.h>

#include <atomic>

using namespace NDns;
using namespace NNeh;
namespace NNeh {
    size_t TNetLibaOptions::ClientThreads = 4;
    TDuration TNetLibaOptions::AckTailEffect = TDuration::Seconds(30);

    bool TNetLibaOptions::Set(TStringBuf name, TStringBuf value) {
#define NETLIBA_TRY_SET(optType, optName)     \
    if (name == TStringBuf(#optName)) {      \
        optName = FromString<optType>(value); \
    }

        NETLIBA_TRY_SET(size_t, ClientThreads)
        else NETLIBA_TRY_SET(TDuration, AckTailEffect) else {
            return false;
        }
        return true;
    }
}

namespace {
    namespace NNetLiba {
        using namespace NNetliba;
        using namespace NNehNetliba;

        typedef NNehNetliba::IRequester INetLibaRequester;
        typedef TAutoPtr<TUdpHttpRequest> TUdpHttpRequestPtr;
        typedef TAutoPtr<TUdpHttpResponse> TUdpHttpResponsePtr;

        static inline const addrinfo* FindIPBase(const TNetworkAddress* addr, int family) {
            for (TNetworkAddress::TIterator it = addr->Begin(); it != addr->End(); ++it) {
                if (it->ai_family == family) {
                    return &*it;
                }
            }

            return nullptr;
        }

        static inline const sockaddr_in6& FindIP(const TNetworkAddress* addr) {
            //prefer ipv6
            const addrinfo* ret = FindIPBase(addr, AF_INET6);

            if (!ret) {
                ret = FindIPBase(addr, AF_INET);
            }

            if (!ret) {
                ythrow yexception() << "ip not supported by " << *addr;
            }

            return *(const sockaddr_in6*)(ret->ai_addr);
        }

        class TLastAckTimes {
            struct TTimeVal {
                TTimeVal()
                    : Val(0)
                {
                }

                std::atomic<TInstant::TValue> Val;
            };

        public:
            TInstant::TValue Get(size_t idAddr) {
                return Tm_.Get(idAddr).Val.load(std::memory_order_acquire);
            }

            void Set(size_t idAddr) {
                Tm_.Get(idAddr).Val.store(TInstant::Now().GetValue(), std::memory_order_release);
            }

            static TLastAckTimes& Common() {
                return *Singleton<TLastAckTimes>();
            }

        private:
            NNeh::NHttp::TLockFreeSequence<TTimeVal> Tm_;
        };

        class TRequest: public TSimpleHandle {
        public:
            inline TRequest(TIntrusivePtr<INetLibaRequester>& r, size_t idAddr, const TMessage& msg, IOnRecv* cb, TStatCollector* s)
                : TSimpleHandle(cb, msg, s)
                , R_(r)
                , IdAddr_(idAddr)
                , Notified_(false)
            {
                CreateGuid(&Guid_);
            }

            void Cancel() noexcept override {
                TSimpleHandle::Cancel();
                R_->CancelRequest(Guid_);
            }

            inline const TString& Addr() const noexcept {
                return Message().Addr;
            }

            inline const TGUID& Guid() const noexcept {
                return Guid_;
            }

            //return false if already notifie
            inline bool SetNotified() noexcept {
                bool ret = Notified_;
                Notified_ = true;
                return !ret;
            }

            void OnSend() {
                if (TNetLibaOptions::AckTailEffect.GetValue() && TLastAckTimes::Common().Get(IdAddr_) + TNetLibaOptions::AckTailEffect.GetValue() > TInstant::Now().GetValue()) {
                    //fake(predicted) completing detection
                    SetSendComplete();
                }
            }

            void OnRequestAck() {
                if (TNetLibaOptions::AckTailEffect.GetValue()) {
                    TLastAckTimes::Common().Set(IdAddr_);
                }
                SetSendComplete();
            }

        private:
            TIntrusivePtr<INetLibaRequester> R_;
            size_t IdAddr_;
            TGUID Guid_;
            bool Notified_;
        };

        typedef TIntrusivePtr<TRequest> TRequestRef;

        class TNetLibaBus {
            class TEventsHandler: public IEventsCollector {
                typedef THashMap<TGUID, TRequestRef, TGUIDHash> TInFly;

            public:
                inline void OnSend(TRequestRef& req) {
                    Q_.Enqueue(req);
                    req->OnSend();
                }

            private:
                void UpdateInFly() {
                    TRequestRef req;

                    while (Q_.Dequeue(&req)) {
                        if (!req) {
                            return;
                        }

                        InFly_[req->Guid()] = req;
                    }
                }

                void AddRequest(TUdpHttpRequest* req) override {
                    //ignore received requests in client
                    delete req;
                }

                void AddResponse(TUdpHttpResponse* resp) override {
                    TUdpHttpResponsePtr ptr(resp);

                    UpdateInFly();
                    TInFly::iterator it = InFly_.find(resp->ReqId);

                    Y_VERIFY(it != InFly_.end(), "incorrect incoming message");

                    TRequestRef& req = it->second;

                    if (req->SetNotified()) {
                        if (resp->Ok == TUdpHttpResponse::OK) {
                            req->NotifyResponse(TString(resp->Data.data(), resp->Data.size()));
                        } else {
                            if (resp->Ok == TUdpHttpResponse::CANCELED) {
                                req->NotifyError(new TError(resp->Error, TError::Cancelled));
                            } else {
                                req->NotifyError(new TError(resp->Error));
                            }
                        }
                    }

                    InFly_.erase(it);
                }

                void AddCancel(const TGUID& guid) override {
                    UpdateInFly();
                    TInFly::iterator it = InFly_.find(guid);

                    if (it != InFly_.end() && it->second->SetNotified()) {
                        it->second->NotifyError("Canceled (before ack)");
                    }
                }

                void AddRequestAck(const TGUID& guid) override {
                    UpdateInFly();
                    TInFly::iterator it = InFly_.find(guid);

                    Y_VERIFY(it != InFly_.end(), "incorrect complete notification");

                    it->second->OnRequestAck();
                }

            private:
                TLockFreeQueue<TRequestRef> Q_;
                TInFly InFly_;
            };

            struct TClientThread {
                TClientThread(int physicalCpu)
                    : EH_(new TEventsHandler())
                    , R_(CreateHttpUdpRequester(0, IEventsCollectorRef(EH_.Get()), physicalCpu))
                {
                    R_->EnableReportRequestAck();
                }

                ~TClientThread() {
                    R_->StopNoWait();
                }

                TIntrusivePtr<TEventsHandler> EH_;
                TIntrusivePtr<INetLibaRequester> R_;
            };

        public:
            TNetLibaBus() {
                for (size_t i = 0; i < TNetLibaOptions::ClientThreads; ++i) {
                    Clnt_.push_back(new TClientThread(i));
                }
            }

            inline THandleRef Schedule(const TMessage& msg, IOnRecv* cb, TServiceStatRef& ss) {
                TParsedLocation loc(msg.Addr);
                TUdpAddress addr;

                const TResolvedHost* resHost = CachedResolve(TResolveInfo(loc.Host, loc.GetPort()));
                GetUdpAddress(&addr, FindIP(&resHost->Addr));

                TClientThread& clnt = *Clnt_[resHost->Id % Clnt_.size()];
                TIntrusivePtr<INetLibaRequester> rr = clnt.R_;
                TRequestRef req(new TRequest(rr, resHost->Id, msg, cb, !ss ? nullptr : new TStatCollector(ss)));

                clnt.EH_->OnSend(req);
                rr->SendRequest(addr, ToString(loc.Service), msg.Data, req->Guid());

                return THandleRef(req.Get());
            }

        private:
            TVector<TAutoPtr<TClientThread>> Clnt_;
        };

        //server
        class TRequester: public TThrRefBase {
            struct TSrvRequestState: public TAtomicRefCount<TSrvRequestState> {
                TSrvRequestState()
                    : Canceled(false)
                {
                }

                TAtomicBool Canceled;
            };

            class TRequest: public IRequest {
            public:
                inline TRequest(TAutoPtr<TUdpHttpRequest> req, TIntrusivePtr<TSrvRequestState> state, TRequester* parent)
                    : R_(req)
                    , S_(state)
                    , P_(parent)
                {
                }

                ~TRequest() override {
                    if (!!P_) {
                        P_->RequestProcessed(this);
                    }
                }

                TStringBuf Scheme() const override {
                    return TStringBuf("netliba");
                }

                TString RemoteHost() const override {
                    if (!H_) {
                        TUdpAddress tmp(R_->PeerAddress);
                        tmp.Scope = 0; //discard scope from serialized addr

                        TString addr = GetAddressAsString(tmp);

                        TStringBuf host, port;

                        TStringBuf(addr).RSplit(':', host, port);
                        H_ = host;
                    }
                    return H_;
                }

                TStringBuf Service() const override {
                    return TStringBuf(R_->Url.c_str(), R_->Url.length());
                }

                TStringBuf Data() const override {
                    return TStringBuf((const char*)R_->Data.data(), R_->Data.size());
                }

                TStringBuf RequestId() const override {
                    const TGUID& g = R_->ReqId;

                    return TStringBuf((const char*)g.dw, sizeof(g.dw));
                }

                bool Canceled() const override {
                    return S_->Canceled;
                }

                void SendReply(TData& data) override {
                    TIntrusivePtr<TRequester> p;
                    p.Swap(P_);
                    if (!!p) {
                        if (!Canceled()) {
                            p->R_->SendResponse(R_->ReqId, &data);
                        }
                        p->RequestProcessed(this);
                    }
                }

                void SendError(TResponseError, const TString&) override {
                    // TODO
                }

                inline const TGUID& RequestGuid() const noexcept {
                    return R_->ReqId;
                }

            private:
                TAutoPtr<TUdpHttpRequest> R_;
                mutable TString H_;
                TIntrusivePtr<TSrvRequestState> S_;
                TIntrusivePtr<TRequester> P_;
            };

            class TEventsHandler: public IEventsCollector {
            public:
                TEventsHandler(TRequester* parent)
                {
                    P_.store(parent, std::memory_order_release);
                }

                void RequestProcessed(const TRequest* r) {
                    FinishedReqs_.Enqueue(r->RequestGuid());
                }

                //thread safe method for disable proxy callbacks to parent (OnRequest(...))
                void SyncStop() {
                    P_.store(nullptr, std::memory_order_release);
                    while (!RequesterPtrPotector_.TryAcquire()) {
                        Sleep(TDuration::MicroSeconds(100));
                    }
                    RequesterPtrPotector_.Release();
                }

            private:
                typedef THashMap<TGUID, TIntrusivePtr<TSrvRequestState>, TGUIDHash> TStatesInProcessRequests;

                void AddRequest(TUdpHttpRequest* req) override {
                    TUdpHttpRequestPtr ptr(req);

                    TSrvRequestState* state = new TSrvRequestState();

                    InProcess_[req->ReqId] = state;
                    try {
                        TGuard<TSpinLock> m(RequesterPtrPotector_);
                        if (TRequester* p = P_.load(std::memory_order_acquire)) {
                            p->OnRequest(ptr, state); //move req. owning to parent
                        }
                    } catch (...) {
                        Cdbg << "ignore exc.: " << CurrentExceptionMessage() << Endl;
                    }
                }

                void AddResponse(TUdpHttpResponse*) override {
                    Y_FAIL("unexpected response in neh netliba server");
                }

                void AddCancel(const TGUID& guid) override {
                    UpdateInProcess();
                    TStatesInProcessRequests::iterator ustate = InProcess_.find(guid);
                    if (ustate != InProcess_.end())
                        ustate->second->Canceled = true;
                }

                void AddRequestAck(const TGUID&) override {
                    Y_FAIL("unexpected acc in neh netliba server");
                }

                void UpdateInProcess() {
                    TGUID guid;

                    while (FinishedReqs_.Dequeue(&guid)) {
                        InProcess_.erase(guid);
                    }
                }

            private:
                TLockFreeStack<TGUID> FinishedReqs_; //processed requests (responded or destroyed)
                TStatesInProcessRequests InProcess_;
                TSpinLock RequesterPtrPotector_;
                std::atomic<TRequester*> P_;
            };

        public:
            inline TRequester(IOnRequest* cb, ui16 port)
                : CB_(cb)
                , EH_(new TEventsHandler(this))
                , R_(CreateHttpUdpRequester(port, EH_.Get()))
            {
                R_->EnableReportRequestCancel();
            }

            ~TRequester() override {
                Shutdown();
            }

            void Shutdown() noexcept {
                if (!Shutdown_) {
                    Shutdown_ = true;
                    R_->StopNoWait();
                    EH_->SyncStop();
                }
            }

            void OnRequest(TUdpHttpRequestPtr req, TSrvRequestState* state) {
                CB_->OnRequest(new TRequest(req, state, this));
            }

            void RequestProcessed(const TRequest* r) {
                EH_->RequestProcessed(r);
            }

        private:
            IOnRequest* CB_;
            TIntrusivePtr<TEventsHandler> EH_;
            TIntrusivePtr<INetLibaRequester> R_;
            bool Shutdown_ = false;
        };

        typedef TIntrusivePtr<TRequester> TRequesterRef;

        class TRequesterAutoShutdown: public NNeh::IRequester {
        public:
            TRequesterAutoShutdown(const TRequesterRef& r)
                : R_(r)
            {
            }

            ~TRequesterAutoShutdown() override {
                R_->Shutdown();
            }

        private:
            TRequesterRef R_;
        };

        class TProtocol: public IProtocol {
        public:
            THandleRef ScheduleRequest(const TMessage& msg, IOnRecv* fallback, TServiceStatRef& ss) override {
                return Singleton<TNetLibaBus>()->Schedule(msg, fallback, ss);
            }

            NNeh::IRequesterRef CreateRequester(IOnRequest* cb, const TParsedLocation& loc) override {
                TRequesterRef r(new TRequester(cb, loc.GetPort()));
                return new TRequesterAutoShutdown(r);
            }

            TStringBuf Scheme() const noexcept override {
                return TStringBuf("netliba");
            }
        };
    }
}

IProtocol* NNeh::NetLibaProtocol() {
    return Singleton<NNetLiba::TProtocol>();
}