aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/neh.h
blob: b5e8cc291f44a42ec4478911eb6c6e768ecef915 (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
#pragma once

#include "wfmo.h"
#include "stat.h"

#include <library/cpp/http/io/headers.h>

#include <util/generic/ptr.h>
#include <util/generic/string.h>
#include <util/datetime/base.h>

#include <utility>

namespace NNeh {
    struct TMessage {
        TMessage() = default;

        inline TMessage(TString addr, TString data)
            : Addr(std::move(addr))
            , Data(std::move(data))
        {
        }

        static TMessage FromString(TStringBuf request);

        TString Addr;
        TString Data;
    };

    using TMessageRef = TAutoPtr<TMessage>;

    struct TError {
    public:
        enum TType {
            UnknownType,
            Cancelled,
            ProtocolSpecific
        };

        TError(TString text, TType type = UnknownType, i32 code = 0, i32 systemCode = 0)
            : Type(std::move(type))
            , Code(code)
            , Text(text)
            , SystemCode(systemCode)
        {
        }

        TType Type = UnknownType;
        i32 Code = 0; // protocol specific code (example(http): 404)
        TString Text;
        i32 SystemCode = 0; // system error code
    };

    using TErrorRef = TAutoPtr<TError>;

    struct TResponse;
    using TResponseRef = TAutoPtr<TResponse>;

    struct TResponse {
        inline TResponse(TMessage req,
                         TString data,
                         const TDuration duration)
            : TResponse(std::move(req), std::move(data), duration, {} /* firstLine */, {} /* headers */, {} /* error */)
        {
        }

        inline TResponse(TMessage req,
                         TString data,
                         const TDuration duration,
                         TString firstLine,
                         THttpHeaders headers)
            : TResponse(std::move(req), std::move(data), duration, std::move(firstLine), std::move(headers), {} /* error */)
        {
        }

        inline TResponse(TMessage req,
                         TString data,
                         const TDuration duration,
                         TString firstLine,
                         THttpHeaders headers,
                         TErrorRef error)
            : Request(std::move(req))
            , Data(std::move(data))
            , Duration(duration)
            , FirstLine(std::move(firstLine))
            , Headers(std::move(headers))
            , Error_(std::move(error))
        {
        }

        inline static TResponseRef FromErrorText(TMessage msg, TString error, const TDuration duration) {
            return new TResponse(std::move(msg), {} /* data */, duration, {} /* firstLine */, {} /* headers */, new TError(std::move(error)));
        }

        inline static TResponseRef FromError(TMessage msg, TErrorRef error, const TDuration duration) {
            return new TResponse(std::move(msg), {} /* data */, duration, {} /* firstLine */, {} /* headers */, error);
        }

        inline static TResponseRef FromError(TMessage msg, TErrorRef error, const TDuration duration,
                                             TString data, TString firstLine, THttpHeaders headers)
        {
            return new TResponse(std::move(msg), std::move(data), duration, std::move(firstLine), std::move(headers), error);
        }

        inline static TResponseRef FromError(
            TMessage msg,
            TErrorRef error,
            TString data,
            const TDuration duration,
            TString firstLine,
            THttpHeaders headers)
        {
            return new TResponse(std::move(msg), std::move(data), duration, std::move(firstLine), std::move(headers), error);
        }

        inline bool IsError() const {
            return Error_.Get();
        }

        inline TError::TType GetErrorType() const {
            return Error_.Get() ? Error_->Type : TError::UnknownType;
        }

        inline i32 GetErrorCode() const {
            return Error_.Get() ? Error_->Code : 0;
        }

        inline i32 GetSystemErrorCode() const {
            return Error_.Get() ? Error_->SystemCode : 0;
        }

        inline TString GetErrorText() const {
            return Error_.Get() ? Error_->Text : TString();
        }

        const TMessage Request;
        const TString Data;
        const TDuration Duration;
        const TString FirstLine;
        THttpHeaders Headers;

    private:
        THolder<TError> Error_;
    };

    class THandle;

    class IOnRecv {
    public:
        virtual ~IOnRecv() = default;

        virtual void OnNotify(THandle&) {
        } //callback on receive response
        virtual void OnEnd() {
        }                                       //response was extracted by Wait() method, - OnRecv() will not be called
        virtual void OnRecv(THandle& resp) = 0; //callback on destroy handler
    };

    class THandle: public TThrRefBase, public TWaitHandle {
    public:
        inline THandle(IOnRecv* f, TStatCollector* s = nullptr) noexcept
            : F_(f)
            , Stat_(s)
        {
        }

        ~THandle() override {
            if (F_) {
                try {
                    F_->OnRecv(*this);
                } catch (...) {
                }
            }
        }

        virtual bool MessageSendedCompletely() const noexcept {
            //TODO
            return true;
        }

        virtual void Cancel() noexcept {
            //TODO
            if (!!Stat_)
                Stat_->OnCancel();
        }

        inline const TResponse* Response() const noexcept {
            return R_.Get();
        }

        //method MUST be called only after success Wait() for this handle or from callback IOnRecv::OnRecv()
        //else exist chance for memory leak (race between Get()/Notify())
        inline TResponseRef Get() noexcept {
            return R_;
        }

        inline bool Wait(TResponseRef& msg, const TInstant deadLine) {
            if (WaitForOne(*this, deadLine)) {
                if (F_) {
                    F_->OnEnd();
                    F_ = nullptr;
                }
                msg = Get();

                return true;
            }

            return false;
        }

        inline bool Wait(TResponseRef& msg, const TDuration timeOut) {
            return Wait(msg, timeOut.ToDeadLine());
        }

        inline bool Wait(TResponseRef& msg) {
            return Wait(msg, TInstant::Max());
        }

        inline TResponseRef Wait(const TInstant  deadLine) {
            TResponseRef ret;

            Wait(ret, deadLine);

            return ret;
        }

        inline TResponseRef Wait(const TDuration  timeOut) {
            return Wait(timeOut.ToDeadLine());
        }

        inline TResponseRef Wait() {
            return Wait(TInstant::Max());
        }

    protected:
        inline void Notify(TResponseRef resp) {
            if (!!Stat_) {
                if (!resp || resp->IsError()) {
                    Stat_->OnFail();
                } else {
                    Stat_->OnSuccess();
                }
            }
            R_.Swap(resp);
            if (F_) {
                try {
                    F_->OnNotify(*this);
                } catch (...) {
                }
            }
            Signal();
        }

        IOnRecv* F_;

    private:
        TResponseRef R_;
        THolder<TStatCollector> Stat_;
    };

    using THandleRef = TIntrusivePtr<THandle>;

    THandleRef Request(const TMessage& msg, IOnRecv* fallback);

    inline THandleRef Request(const TMessage& msg) {
        return Request(msg, nullptr);
    }

    THandleRef Request(const TString& req, IOnRecv* fallback);

    inline THandleRef Request(const TString& req) {
        return Request(req, nullptr);
    }

    class IMultiRequester {
    public:
        virtual ~IMultiRequester() = default;

        virtual void Add(const THandleRef& req) = 0;
        virtual void Del(const THandleRef& req) = 0;
        virtual bool Wait(THandleRef& req, TInstant deadLine) = 0;
        virtual bool IsEmpty() const = 0;

        inline void Schedule(const TString& req) {
            Add(Request(req));
        }

        inline bool Wait(THandleRef& req, TDuration timeOut) {
            return Wait(req, timeOut.ToDeadLine());
        }

        inline bool Wait(THandleRef& req) {
            return Wait(req, TInstant::Max());
        }

        inline bool Wait(TResponseRef& resp, TInstant deadLine) {
            THandleRef req;

            while (Wait(req, deadLine)) {
                resp = req->Get();

                if (!!resp) {
                    return true;
                }
            }

            return false;
        }

        inline bool Wait(TResponseRef& resp) {
            return Wait(resp, TInstant::Max());
        }
    };

    using IMultiRequesterRef = TAutoPtr<IMultiRequester>;

    IMultiRequesterRef CreateRequester();

    bool SetProtocolOption(TStringBuf protoOption, TStringBuf value);
}