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
|
#include "multiclient.h"
#include "utils.h"
#include <library/cpp/containers/intrusive_rb_tree/rb_tree.h>
#include <atomic>
namespace {
using namespace NNeh;
struct TCompareDeadline {
template <class T>
static inline bool Compare(const T& l, const T& r) noexcept {
return l.Deadline() < r.Deadline() || (l.Deadline() == r.Deadline() && &l < &r);
}
};
class TMultiClient: public IMultiClient, public TThrRefBase {
class TRequestSupervisor: public TRbTreeItem<TRequestSupervisor, TCompareDeadline>, public IOnRecv, public TThrRefBase, public TNonCopyable {
private:
TRequestSupervisor() {
} //disable
public:
inline TRequestSupervisor(const TRequest& request, TMultiClient* mc) noexcept
: MC_(mc)
, Request_(request)
, Maked_(0)
, FinishOnMakeRequest_(0)
, Handled_(0)
, Dequeued_(false)
{
}
inline TInstant Deadline() const noexcept {
return Request_.Deadline;
}
//not thread safe (can be called at some time from TMultiClient::Request() and TRequestSupervisor::OnNotify())
void OnMakeRequest(THandleRef h) noexcept {
//request can be mark as maked only once, so only one/first call set handle
if (AtomicCas(&Maked_, 1, 0)) {
H_.Swap(h);
//[paranoid mode on] make sure handle be initiated before return
AtomicSet(FinishOnMakeRequest_, 1);
} else {
while (!AtomicGet(FinishOnMakeRequest_)) {
SpinLockPause();
}
//[paranoid mode off]
}
}
void FillEvent(TEvent& ev) noexcept {
ev.Hndl = H_;
FillEventUserData(ev);
}
void FillEventUserData(TEvent& ev) noexcept {
ev.UserData = Request_.UserData;
}
void ResetRequest() noexcept { //destroy keepaliving cross-ref TRequestSupervisor<->THandle
H_.Drop();
}
//method OnProcessRequest() & OnProcessResponse() executed from Wait() context (thread)
void OnEndProcessRequest() {
Dequeued_ = true;
if (Y_UNLIKELY(IsHandled())) {
ResetRequest(); //race - response already handled before processing request from queue
} else {
MC_->RegisterRequest(this);
}
}
void OnEndProcessResponse() {
if (Y_LIKELY(Dequeued_)) {
UnLink();
ResetRequest();
} //else request yet not dequeued/registered, so we not need unlink request
//(when we later dequeue request OnEndProcessRequest()...IsHandled() return true and we reset request)
}
//IOnRecv interface
void OnNotify(THandle& h) override {
if (Y_LIKELY(MarkAsHandled())) {
THandleRef hr(&h);
OnMakeRequest(hr); //fix race with receiving response before return control from NNeh::Request()
MC_->ScheduleResponse(this, hr);
}
}
void OnRecv(THandle&) noexcept override {
UnRef();
}
void OnEnd() noexcept override {
UnRef();
}
//
//request can be handled only once, so only one/first call MarkAsHandled() return true
bool MarkAsHandled() noexcept {
return AtomicCas(&Handled_, 1, 0);
}
bool IsHandled() const noexcept {
return AtomicGet(Handled_);
}
private:
TIntrusivePtr<TMultiClient> MC_;
TRequest Request_;
THandleRef H_;
TAtomic Maked_;
TAtomic FinishOnMakeRequest_;
TAtomic Handled_;
bool Dequeued_;
};
typedef TRbTree<TRequestSupervisor, TCompareDeadline> TRequestsSupervisors;
typedef TIntrusivePtr<TRequestSupervisor> TRequestSupervisorRef;
public:
TMultiClient()
: Interrupt_(false)
, NearDeadline_(TInstant::Max().GetValue())
, E_(::TSystemEvent::rAuto)
, Shutdown_(false)
{
}
struct TResetRequest {
inline void operator()(TRequestSupervisor& rs) const noexcept {
rs.ResetRequest();
}
};
void Shutdown() {
//reset THandleRef's for all exist supervisors and jobs queue (+prevent creating new)
//- so we break crossref-chain, which prevent destroy this object THande->TRequestSupervisor->TMultiClient)
Shutdown_ = true;
RS_.ForEachNoOrder(TResetRequest());
RS_.Clear();
CleanQueue();
}
private:
class IJob {
public:
virtual ~IJob() {
}
virtual bool Process(TEvent&) = 0;
virtual void Cancel() = 0;
};
typedef TAutoPtr<IJob> TJobPtr;
class TNewRequest: public IJob {
public:
TNewRequest(TRequestSupervisorRef& rs)
: RS_(rs)
{
}
private:
bool Process(TEvent&) override {
RS_->OnEndProcessRequest();
return false;
}
void Cancel() override {
RS_->ResetRequest();
}
TRequestSupervisorRef RS_;
};
class TNewResponse: public IJob {
public:
TNewResponse(TRequestSupervisor* rs, THandleRef& h) noexcept
: RS_(rs)
, H_(h)
{
}
private:
bool Process(TEvent& ev) override {
ev.Type = TEvent::Response;
ev.Hndl = H_;
RS_->FillEventUserData(ev);
RS_->OnEndProcessResponse();
return true;
}
void Cancel() override {
RS_->ResetRequest();
}
TRequestSupervisorRef RS_;
THandleRef H_;
};
public:
THandleRef Request(const TRequest& request) override {
TIntrusivePtr<TRequestSupervisor> rs(new TRequestSupervisor(request, this));
THandleRef h;
try {
rs->Ref();
h = NNeh::Request(request.Msg, rs.Get());
//accurately handle race when processing new request event
//(we already can receive response (call OnNotify) before we schedule info about new request here)
} catch (...) {
rs->UnRef();
throw;
}
rs->OnMakeRequest(h);
ScheduleRequest(rs, h, request.Deadline);
return h;
}
bool Wait(TEvent& ev, const TInstant deadline_ = TInstant::Max()) override {
while (!Interrupt_) {
TInstant deadline = deadline_;
const TInstant now = TInstant::Now();
if (deadline != TInstant::Max() && now >= deadline) {
break;
}
{ //process jobs queue (requests/responses info)
TAutoPtr<IJob> j;
while (JQ_.Dequeue(&j)) {
if (j->Process(ev)) {
return true;
}
}
}
if (!RS_.Empty()) {
TRequestSupervisor* nearRS = &*RS_.Begin();
if (nearRS->Deadline() <= now) {
if (!nearRS->MarkAsHandled()) {
//race with notify, - now in queue must exist response job for this request
continue;
}
ev.Type = TEvent::Timeout;
nearRS->FillEvent(ev);
nearRS->ResetRequest();
nearRS->UnLink();
return true;
}
deadline = Min(nearRS->Deadline(), deadline);
}
if (SetNearDeadline(deadline)) {
continue; //update deadline to more far time, so need re-check queue for avoiding race
}
E_.WaitD(deadline);
}
Interrupt_ = false;
return false;
}
void Interrupt() override {
Interrupt_ = true;
Signal();
}
size_t QueueSize() override {
return JQ_.Size();
}
private:
void Signal() {
//TODO:try optimize - hack with skipping signaling if not have waiters (reduce mutex usage)
E_.Signal();
}
void ScheduleRequest(TIntrusivePtr<TRequestSupervisor>& rs, const THandleRef& h, const TInstant& deadline) {
TJobPtr j(new TNewRequest(rs));
JQ_.Enqueue(j);
if (!h->Signalled()) {
if (deadline.GetValue() < GetNearDeadline_()) {
Signal();
}
}
}
void ScheduleResponse(TRequestSupervisor* rs, THandleRef& h) {
TJobPtr j(new TNewResponse(rs, h));
JQ_.Enqueue(j);
if (Y_UNLIKELY(Shutdown_)) {
CleanQueue();
} else {
Signal();
}
}
//return true, if deadline re-installed to more late time
bool SetNearDeadline(const TInstant& deadline) {
bool deadlineMovedFurther = deadline.GetValue() > GetNearDeadline_();
SetNearDeadline_(deadline.GetValue());
return deadlineMovedFurther;
}
//used only from Wait()
void RegisterRequest(TRequestSupervisor* rs) {
if (rs->Deadline() != TInstant::Max()) {
RS_.Insert(rs);
} else {
rs->ResetRequest(); //prevent blocking destruction 'endless' requests
}
}
void CleanQueue() {
TAutoPtr<IJob> j;
while (JQ_.Dequeue(&j)) {
j->Cancel();
}
}
private:
void SetNearDeadline_(const TInstant::TValue& v) noexcept {
TGuard<TAdaptiveLock> g(NDLock_);
NearDeadline_.store(v, std::memory_order_release);
}
TInstant::TValue GetNearDeadline_() const noexcept {
TGuard<TAdaptiveLock> g(NDLock_);
return NearDeadline_.load(std::memory_order_acquire);
}
NNeh::TAutoLockFreeQueue<IJob> JQ_;
TAtomicBool Interrupt_;
TRequestsSupervisors RS_;
TAdaptiveLock NDLock_;
std::atomic<TInstant::TValue> NearDeadline_;
::TSystemEvent E_;
TAtomicBool Shutdown_;
};
class TMultiClientAutoShutdown: public IMultiClient {
public:
TMultiClientAutoShutdown()
: MC_(new TMultiClient())
{
}
~TMultiClientAutoShutdown() override {
MC_->Shutdown();
}
size_t QueueSize() override {
return MC_->QueueSize();
}
private:
THandleRef Request(const TRequest& req) override {
return MC_->Request(req);
}
bool Wait(TEvent& ev, TInstant deadline = TInstant::Max()) override {
return MC_->Wait(ev, deadline);
}
void Interrupt() override {
return MC_->Interrupt();
}
private:
TIntrusivePtr<TMultiClient> MC_;
};
}
TMultiClientPtr NNeh::CreateMultiClient() {
return new TMultiClientAutoShutdown();
}
|