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
|
#pragma once
#include "ydb/core/client/server/grpc_base.h"
#include <library/cpp/grpc/server/grpc_server.h>
#include <util/generic/queue.h>
using grpc::Status;
namespace NKikimr {
namespace NGRpcProxy {
///////////////////////////////////////////////////////////////////////////////
using namespace NKikimrClient;
template<class TResponse>
class ISessionHandler : public TAtomicRefCount<ISessionHandler<TResponse>> {
public:
virtual ~ISessionHandler()
{ }
/// Finish session.
virtual void Finish() = 0;
/// Send reply to client.
virtual void Reply(const TResponse& resp) = 0;
virtual void ReadyForNextRead() = 0;
virtual bool IsShuttingDown() const = 0;
};
template<class TResponse>
using ISessionHandlerRef = TIntrusivePtr<ISessionHandler<TResponse>>;
template <class TRequest, class TResponse>
class ISession : public ISessionHandler<TResponse>
{
using ISessionRef = TIntrusivePtr<ISession<TRequest, TResponse>>;
protected:
class TRequestCreated : public NGrpc::IQueueEvent {
public:
TRequestCreated(ISessionRef session)
: Session(session)
{ }
bool Execute(bool ok) override {
if (!ok) {
Session->DestroyStream("waiting stream creating failed");
return false;
}
Session->OnCreated();
return false;
}
void DestroyRequest() override {
if (!Session->Context.c_call() && Session->ClientDone) {
// AsyncNotifyWhenDone will not appear on the queue.
delete Session->ClientDone;
Session->ClientDone = nullptr;
}
delete this;
}
ISessionRef Session;
};
class TReadDone : public NGrpc::IQueueEvent {
public:
TReadDone(ISessionRef session)
: Session(session)
{ }
bool Execute(bool ok) override {
if (ok) {
Session->OnRead(Request);
} else {
if (Session->IsCancelled()) {
Session->DestroyStream("reading from stream failed");
} else {
Session->OnDone();
}
}
return false;
}
void DestroyRequest() override {
delete this;
}
TRequest Request;
ISessionRef Session;
};
class TWriteDone : public NGrpc::IQueueEvent {
public:
TWriteDone(ISessionRef session, ui64 size)
: Session(session)
, Size(size)
{ }
bool Execute(bool ok) override {
Session->OnWriteDone(Size);
if (!ok) {
Session->DestroyStream("writing to stream failed");
return false;
}
TGuard<TSpinLock> lock(Session->Lock);
if (Session->Responses.empty()) {
Session->HaveWriteInflight = false;
if (Session->NeedFinish) {
lock.Release();
Session->Stream.Finish(Status::OK, new TFinishDone(Session));
}
} else {
auto resp = Session->Responses.front();
Session->Responses.pop();
lock.Release();
ui64 sz = resp.ByteSize();
Session->Stream.Write(resp, new TWriteDone(Session, sz));
}
return false;
}
void DestroyRequest() override {
delete this;
}
ISessionRef Session;
ui64 Size;
};
class TFinishDone : public NGrpc::IQueueEvent {
public:
TFinishDone(ISessionRef session)
: Session(session)
{ }
bool Execute(bool) override {
Session->DestroyStream("some stream finished");
return false;
}
void DestroyRequest() override {
delete this;
}
ISessionRef Session;
};
class TClientDone : public NGrpc::IQueueEvent {
public:
TClientDone(ISessionRef session)
: Session(session)
{
Session->ClientDone = this;
}
bool Execute(bool) override {
Session->ClientIsDone = true;
Session->DestroyStream("sesison closed");
return false;
}
void DestroyRequest() override {
Y_VERIFY(Session->ClientDone);
Session->ClientDone = nullptr;
delete this;
}
ISessionRef Session;
};
public:
ISession(grpc::ServerCompletionQueue* cq)
: CQ(cq)
, Stream(&Context)
, HaveWriteInflight(false)
, NeedFinish(false)
, ClientIsDone(false)
{
Context.AsyncNotifyWhenDone(new TClientDone(this));
}
TString GetDatabase() const {
TString key = "x-ydb-database";
const auto& clientMetadata = Context.client_metadata();
const auto range = clientMetadata.equal_range(grpc::string_ref{key.data(), key.size()});
if (range.first == range.second) {
return "";
}
TVector<TStringBuf> values;
values.reserve(std::distance(range.first, range.second));
for (auto it = range.first; it != range.second; ++it) {
return TString(it->second.data(), it->second.size());
}
return "";
}
TString GetPeerName() const {
TString res(Context.peer());
if (res.StartsWith("ipv4:[") || res.StartsWith("ipv6:[")) {
size_t pos = res.find(']');
Y_VERIFY(pos != TString::npos);
res = res.substr(6, pos - 6);
} else if (res.StartsWith("ipv4:")) {
size_t pos = res.rfind(':');
if (pos == TString::npos) {//no port
res = res.substr(5);
} else {
res = res.substr(5, pos - 5);
}
} else {
size_t pos = res.rfind(":"); //port
if (pos != TString::npos) {
res = res.substr(0, pos);
}
}
return res;
}
protected:
virtual void OnCreated() = 0;
virtual void OnRead(const TRequest& request) = 0;
virtual void OnDone() = 0;
virtual void OnWriteDone(ui64 size) = 0;
virtual void DestroyStream(const TString& reason, NPersQueue::NErrorCode::EErrorCode code = NPersQueue::NErrorCode::BAD_REQUEST) = 0;
/// Start accepting session's requests.
virtual void Start() = 0;
bool IsCancelled() const {
return ClientIsDone && Context.IsCancelled();
}
void ReplyWithError(const TString& description, NPersQueue::NErrorCode::EErrorCode code)
{
TResponse response;
response.MutableError()->SetDescription(description);
response.MutableError()->SetCode(code);
Reply(response);
Finish();
}
/// Finish session.
void Finish() override {
{
TGuard<TSpinLock> lock(Lock);
if (NeedFinish)
return;
if (HaveWriteInflight || !Responses.empty()) {
NeedFinish = true;
return;
}
HaveWriteInflight = true;
}
Stream.Finish(Status::OK, new TFinishDone(this));
}
/// Send reply to client.
void Reply(const TResponse& resp) override {
{
TGuard<TSpinLock> lock(Lock);
if (NeedFinish) //ignore responses after finish
return;
if (HaveWriteInflight || !Responses.empty()) {
Responses.push(resp);
return;
} else {
HaveWriteInflight = true;
}
}
ui64 size = resp.ByteSize();
Stream.Write(resp, new TWriteDone(this, size));
}
void ReadyForNextRead() override {
{
TGuard<TSpinLock> lock(Lock);
if (NeedFinish) {
return;
}
}
auto read = new TReadDone(this);
Stream.Read(&read->Request, read);
}
protected:
grpc::ServerCompletionQueue* const CQ;
grpc::ServerContext Context;
grpc::ServerAsyncReaderWriter<TResponse, TRequest>
Stream;
private:
TSpinLock Lock;
bool HaveWriteInflight;
bool NeedFinish;
std::atomic<bool> ClientIsDone;
TClientDone* ClientDone;
TQueue<TResponse> Responses; //TODO: if Responses total size is too big - fail this session;
};
}
}
|