aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/tcp.cpp
blob: 80f464dac25b837c01221b87be943dda2c845f50 (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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#include "tcp.h"

#include "details.h"
#include "factory.h"
#include "location.h"
#include "pipequeue.h"
#include "utils.h"

#include <library/cpp/coroutine/listener/listen.h>
#include <library/cpp/coroutine/engine/events.h>
#include <library/cpp/coroutine/engine/sockpool.h>
#include <library/cpp/dns/cache.h>

#include <util/ysaveload.h>
#include <util/generic/buffer.h>
#include <util/generic/guid.h>
#include <util/generic/hash.h>
#include <util/generic/intrlist.h>
#include <util/generic/ptr.h>
#include <util/generic/vector.h>
#include <util/system/yassert.h>
#include <util/system/unaligned_mem.h>
#include <util/stream/buffered.h>
#include <util/stream/mem.h>

using namespace NDns;
using namespace NNeh;

using TNehMessage = TMessage;

template <>
struct TSerializer<TGUID> {
    static inline void Save(IOutputStream* out, const TGUID& g) {
        out->Write(&g.dw, sizeof(g.dw));
    }

    static inline void Load(IInputStream* in, TGUID& g) {
        in->Load(&g.dw, sizeof(g.dw));
    }
};

namespace {
    namespace NNehTCP {
        typedef IOutputStream::TPart TPart;

        static inline ui64 LocalGuid(const TGUID& g) {
            return ReadUnaligned<ui64>(g.dw);
        }

        static inline TString LoadStroka(IInputStream& input, size_t len) {
            TString tmp;

            tmp.ReserveAndResize(len);
            input.Load(tmp.begin(), tmp.size());

            return tmp;
        }

        struct TParts: public TVector<TPart> {
            template <class T>
            inline void Push(const T& t) {
                Push(TPart(t));
            }

            inline void Push(const TPart& part) {
                if (part.len) {
                    push_back(part);
                }
            }

            inline void Clear() noexcept {
                clear();
            }
        };

        template <class T>
        struct TMessageQueue {
            inline TMessageQueue(TContExecutor* e)
                : Ev(e)
            {
            }

            template <class TPtr>
            inline void Enqueue(TPtr p) noexcept {
                L.PushBack(p.Release());
                Ev.Signal();
            }

            template <class TPtr>
            inline bool Dequeue(TPtr& p) noexcept {
                do {
                    if (TryDequeue(p)) {
                        return true;
                    }
                } while (Ev.WaitI() != ECANCELED);

                return false;
            }

            template <class TPtr>
            inline bool TryDequeue(TPtr& p) noexcept {
                if (L.Empty()) {
                    return false;
                }

                p.Reset(L.PopFront());

                return true;
            }

            inline TContExecutor* Executor() const noexcept {
                return Ev.Executor();
            }

            TIntrusiveListWithAutoDelete<T, TDelete> L;
            TContSimpleEvent Ev;
        };

        template <class Q, class C>
        inline bool Dequeue(Q& q, C& c, size_t len) {
            typename C::value_type t;
            size_t slen = 0;

            if (q.Dequeue(t)) {
                slen += t->Length();
                c.push_back(t);

                while (slen < len && q.TryDequeue(t)) {
                    slen += t->Length();
                    c.push_back(t);
                }

                return true;
            }

            return false;
        }

        struct TServer: public IRequester, public TContListener::ICallBack {
            struct TLink;
            typedef TIntrusivePtr<TLink> TLinkRef;

            struct TResponce: public TIntrusiveListItem<TResponce> {
                inline TResponce(const TLinkRef& link, TData& data, TStringBuf reqid)
                    : Link(link)
                {
                    Data.swap(data);

                    TMemoryOutput out(Buf, sizeof(Buf));

                    ::Save(&out, (ui32)(reqid.size() + Data.size()));
                    out.Write(reqid.data(), reqid.size());

                    Y_ASSERT(reqid.size() == 16);

                    Len = out.Buf() - Buf;
                }

                inline void Serialize(TParts& parts) {
                    parts.Push(TStringBuf(Buf, Len));
                    parts.Push(TStringBuf(Data.data(), Data.size()));
                }

                inline size_t Length() const noexcept {
                    return Len + Data.size();
                }

                TLinkRef Link;
                TData Data;
                char Buf[32];
                size_t Len;
            };

            typedef TAutoPtr<TResponce> TResponcePtr;

            struct TRequest: public IRequest {
                inline TRequest(const TLinkRef& link, IInputStream& in, size_t len)
                    : Link(link)
                {
                    Buf.Proceed(len);
                    in.Load(Buf.Data(), Buf.Size());
                    if ((ServiceBegin() - Buf.Data()) + ServiceLen() > Buf.Size()) {
                        throw yexception() << "invalid request (service len)";
                    }
                }

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

                TString RemoteHost() const override {
                    return Link->RemoteHost;
                }

                TStringBuf Service() const override {
                    return TStringBuf(ServiceBegin(), ServiceLen());
                }

                TStringBuf Data() const override {
                    return TStringBuf(Service().end(), Buf.End());
                }

                TStringBuf RequestId() const override {
                    return TStringBuf(Buf.Data(), 16);
                }

                bool Canceled() const override {
                    //TODO
                    return false;
                }

                void SendReply(TData& data) override {
                    Link->P->Schedule(new TResponce(Link, data, RequestId()));
                }

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

                size_t ServiceLen() const noexcept {
                    const char* ptr = RequestId().end();
                    return *(ui32*)ptr;
                }

                const char* ServiceBegin() const noexcept {
                    return RequestId().end() + sizeof(ui32);
                }

                TBuffer Buf;
                TLinkRef Link;
            };

            struct TLink: public TAtomicRefCount<TLink> {
                inline TLink(TServer* parent, const TAcceptFull& a)
                    : P(parent)
                    , MQ(Executor())
                {
                    S.Swap(*a.S);
                    SetNoDelay(S, true);

                    RemoteHost = PrintHostByRfc(*GetPeerAddr(S));

                    TLinkRef self(this);

                    Executor()->Create<TLink, &TLink::RecvCycle>(this, "recv");
                    Executor()->Create<TLink, &TLink::SendCycle>(this, "send");

                    Executor()->Running()->Yield();
                }

                inline void Enqueue(TResponcePtr res) {
                    MQ.Enqueue(res);
                }

                inline TContExecutor* Executor() const noexcept {
                    return P->E.Get();
                }

                void SendCycle(TCont* c) {
                    TLinkRef self(this);

                    try {
                        DoSendCycle(c);
                    } catch (...) {
                        Cdbg << "neh/tcp/1: " << CurrentExceptionMessage() << Endl;
                    }
                }

                inline void DoSendCycle(TCont* c) {
                    TVector<TResponcePtr> responses;
                    TParts parts;

                    while (Dequeue(MQ, responses, 7000)) {
                        for (size_t i = 0; i < responses.size(); ++i) {
                            responses[i]->Serialize(parts);
                        }

                        {
                            TContIOVector iovec(parts.data(), parts.size());
                            NCoro::WriteVectorI(c, S, &iovec);
                        }

                        parts.Clear();
                        responses.clear();
                    }
                }

                void RecvCycle(TCont* c) {
                    TLinkRef self(this);

                    try {
                        DoRecvCycle(c);
                    } catch (...) {
                        if (!c->Cancelled()) {
                            Cdbg << "neh/tcp/2: " << CurrentExceptionMessage() << Endl;
                        }
                    }
                }

                inline void DoRecvCycle(TCont* c) {
                    TContIO io(S, c);
                    TBufferedInput input(&io, 8192 * 4);

                    while (true) {
                        ui32 len;

                        try {
                            ::Load(&input, len);
                        } catch (TLoadEOF&) {
                            return;
                        }

                        P->CB->OnRequest(new TRequest(this, input, len));
                    }
                }

                TServer* P;
                TMessageQueue<TResponce> MQ;
                TSocketHolder S;
                TString RemoteHost;
            };

            inline TServer(IOnRequest* cb, ui16 port)
                : CB(cb)
                , Addr(port)
            {
                Thrs.push_back(Spawn<TServer, &TServer::Run>(this));
            }

            ~TServer() override {
                Schedule(nullptr);

                for (size_t i = 0; i < Thrs.size(); ++i) {
                    Thrs[i]->Join();
                }
            }

            void Run() {
                E = MakeHolder<TContExecutor>(RealStackSize(32000));
                THolder<TContListener> L(new TContListener(this, E.Get(), TContListener::TOptions().SetDeferAccept(true)));
                //SetHighestThreadPriority();
                L->Bind(Addr);
                E->Create<TServer, &TServer::RunDispatcher>(this, "dispatcher");
                L->Listen();
                E->Execute();
            }

            void OnAcceptFull(const TAcceptFull& a) override {
                //I love such code
                new TLink(this, a);
            }

            void OnError() override {
                Cerr << CurrentExceptionMessage() << Endl;
            }

            inline void Schedule(TResponcePtr res) {
                PQ.EnqueueSafe(res);
            }

            void RunDispatcher(TCont* c) {
                while (true) {
                    TResponcePtr res;

                    PQ.DequeueSafe(c, res);

                    if (!res) {
                        break;
                    }

                    TLinkRef link = res->Link;

                    link->Enqueue(res);
                }

                c->Executor()->Abort();
            }
            THolder<TContExecutor> E;
            IOnRequest* CB;
            TNetworkAddress Addr;
            TOneConsumerPipeQueue<TResponce> PQ;
            TVector<TThreadRef> Thrs;
        };

        struct TClient {
            struct TRequest: public TIntrusiveListItem<TRequest> {
                inline TRequest(const TSimpleHandleRef& hndl, const TNehMessage& msg)
                    : Hndl(hndl)
                    , Msg(msg)
                    , Loc(Msg.Addr)
                    , RI(CachedThrResolve(TResolveInfo(Loc.Host, Loc.GetPort())))
                {
                    CreateGuid(&Guid);
                }

                inline void Serialize(TParts& parts) {
                    TMemoryOutput out(Buf, sizeof(Buf));

                    ::Save(&out, (ui32)MsgLen());
                    ::Save(&out, Guid);
                    ::Save(&out, (ui32) Loc.Service.size());

                    if (Loc.Service.size() > out.Avail()) {
                        parts.Push(TStringBuf(Buf, out.Buf()));
                        parts.Push(Loc.Service);
                    } else {
                        out.Write(Loc.Service.data(), Loc.Service.size());
                        parts.Push(TStringBuf(Buf, out.Buf()));
                    }

                    parts.Push(Msg.Data);
                }

                inline size_t Length() const noexcept {
                    return sizeof(ui32) + MsgLen();
                }

                inline size_t MsgLen() const noexcept {
                    return sizeof(Guid.dw) + sizeof(ui32) + Loc.Service.size() + Msg.Data.size();
                }

                void OnError(const TString& errText) {
                    Hndl->NotifyError(errText);
                }

                TSimpleHandleRef Hndl;
                TNehMessage Msg;
                TGUID Guid;
                const TParsedLocation Loc;
                const TResolvedHost* RI;
                char Buf[128];
            };

            typedef TAutoPtr<TRequest> TRequestPtr;

            struct TChannel {
                struct TLink: public TIntrusiveListItem<TLink>, public TSimpleRefCount<TLink> {
                    inline TLink(TChannel* parent)
                        : P(parent)
                    {
                        Executor()->Create<TLink, &TLink::SendCycle>(this, "send");
                    }

                    void SendCycle(TCont* c) {
                        TIntrusivePtr<TLink> self(this);

                        try {
                            DoSendCycle(c);
                            OnError("shutdown");
                        } catch (...) {
                            OnError(CurrentExceptionMessage());
                        }

                        Unlink();
                    }

                    inline void DoSendCycle(TCont* c) {
                        if (int ret = NCoro::ConnectI(c, S, P->RI->Addr)) {
                            ythrow TSystemError(ret) << "can't connect";
                        }
                        SetNoDelay(S, true);
                        Executor()->Create<TLink, &TLink::RecvCycle>(this, "recv");

                        TVector<TRequestPtr> reqs;
                        TParts parts;

                        while (Dequeue(P->Q, reqs, 7000)) {
                            for (size_t i = 0; i < reqs.size(); ++i) {
                                TRequestPtr& req = reqs[i];

                                req->Serialize(parts);
                                InFly[LocalGuid(req->Guid)] = req;
                            }

                            {
                                TContIOVector vec(parts.data(), parts.size());
                                NCoro::WriteVectorI(c, S, &vec);
                            }

                            reqs.clear();
                            parts.Clear();
                        }
                    }

                    void RecvCycle(TCont* c) {
                        TIntrusivePtr<TLink> self(this);

                        try {
                            DoRecvCycle(c);
                            OnError("service close connection");
                        } catch (...) {
                            OnError(CurrentExceptionMessage());
                        }
                    }

                    inline void DoRecvCycle(TCont* c) {
                        TContIO io(S, c);
                        TBufferedInput input(&io, 8192 * 4);

                        while (true) {
                            ui32 len;
                            TGUID g;

                            try {
                                ::Load(&input, len);
                            } catch (TLoadEOF&) {
                                return;
                            }
                            ::Load(&input, g);
                            const TString data(LoadStroka(input, len - sizeof(g.dw)));

                            TInFly::iterator it = InFly.find(LocalGuid(g));

                            if (it == InFly.end()) {
                                continue;
                            }

                            TRequestPtr req = it->second;

                            InFly.erase(it);
                            req->Hndl->NotifyResponse(data);
                        }
                    }

                    inline TContExecutor* Executor() const noexcept {
                        return P->Q.Executor();
                    }

                    void OnError(const TString& errText) {
                        for (auto& it : InFly) {
                            it.second->OnError(errText);
                        }
                        InFly.clear();

                        TRequestPtr req;
                        while (P->Q.TryDequeue(req)) {
                            req->OnError(errText);
                        }
                    }

                    TChannel* P;
                    TSocketHolder S;
                    typedef THashMap<ui64, TRequestPtr> TInFly;
                    TInFly InFly;
                };

                inline TChannel(TContExecutor* e, const TResolvedHost* ri)
                    : Q(e)
                    , RI(ri)
                {
                }

                inline void Enqueue(TRequestPtr req) {
                    Q.Enqueue(req);

                    if (Links.Empty()) {
                        for (size_t i = 0; i < 1; ++i) {
                            SpawnLink();
                        }
                    }
                }

                inline void SpawnLink() {
                    Links.PushBack(new TLink(this));
                }

                TMessageQueue<TRequest> Q;
                TIntrusiveList<TLink> Links;
                const TResolvedHost* RI;
            };

            typedef TAutoPtr<TChannel> TChannelPtr;

            inline TClient() {
                Thr = Spawn<TClient, &TClient::RunExecutor>(this);
            }

            inline ~TClient() {
                Reqs.Enqueue(nullptr);
                Thr->Join();
            }

            inline THandleRef Schedule(const TNehMessage& msg, IOnRecv* fallback, TServiceStatRef& ss) {
                TSimpleHandleRef ret(new TSimpleHandle(fallback, msg, !ss ? nullptr : new TStatCollector(ss)));

                Reqs.Enqueue(new TRequest(ret, msg));

                return ret.Get();
            }

            void RunExecutor() {
                //SetHighestThreadPriority();
                TContExecutor e(RealStackSize(32000));

                e.Create<TClient, &TClient::RunDispatcher>(this, "dispatcher");
                e.Execute();
            }

            void RunDispatcher(TCont* c) {
                TRequestPtr req;

                while (true) {
                    Reqs.DequeueSafe(c, req);

                    if (!req) {
                        break;
                    }

                    TChannelPtr& ch = Channels.Get(req->RI->Id);

                    if (!ch) {
                        ch.Reset(new TChannel(c->Executor(), req->RI));
                    }

                    ch->Enqueue(req);
                }

                c->Executor()->Abort();
            }

            TThreadRef Thr;
            TOneConsumerPipeQueue<TRequest> Reqs;
            TSocketMap<TChannelPtr> Channels;
        };

        struct TMultiClient {
            inline TMultiClient()
                : Next(0)
            {
                for (size_t i = 0; i < 2; ++i) {
                    Clients.push_back(new TClient());
                }
            }

            inline THandleRef Schedule(const TNehMessage& msg, IOnRecv* fallback, TServiceStatRef& ss) {
                return Clients[AtomicIncrement(Next) % Clients.size()]->Schedule(msg, fallback, ss);
            }

            TVector<TAutoPtr<TClient>> Clients;
            TAtomic Next;
        };

#if 0
    static inline TMultiClient* Client() {
        return Singleton<NNehTCP::TMultiClient>();
    }
#else
        static inline TClient* Client() {
            return Singleton<NNehTCP::TClient>();
        }
#endif

        class TTcpProtocol: public IProtocol {
        public:
            inline TTcpProtocol() {
                InitNetworkSubSystem();
            }

            IRequesterRef CreateRequester(IOnRequest* cb, const TParsedLocation& loc) override {
                return new TServer(cb, loc.GetPort());
            }

            THandleRef ScheduleRequest(const TNehMessage& msg, IOnRecv* fallback, TServiceStatRef& ss) override {
                return Client()->Schedule(msg, fallback, ss);
            }

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

IProtocol* NNeh::TcpProtocol() {
    return Singleton<NNehTCP::TTcpProtocol>();
}