-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp_rpc_request.cc
More file actions
400 lines (366 loc) · 11.8 KB
/
http_rpc_request.cc
File metadata and controls
400 lines (366 loc) · 11.8 KB
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
// Copyright (c) 2014 The Trident Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Author: Zuoyan Qin (qinzuoyan@gmail.com)
#include <trident/http_rpc_request.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <google/protobuf/io/printer.h>
#include <trident/http.h>
#include <trident/pbjson.h>
#include <trident/rpc_error_code.h>
#include <trident/rpc_server_impl.h>
#include <trident/rpc_server_stream.h>
#include <trident/string_utils.h>
#include <trident/web_service.h>
namespace trident {
HTTPRpcRequest::HTTPRpcRequest() :
_type(GET),
_req_body(new ReadBuffer()),
_req_json(NULL)
{
}
HTTPRpcRequest::~HTTPRpcRequest()
{
if (_req_json != NULL)
{
delete _req_json;
}
}
RpcRequest::RpcRequestType HTTPRpcRequest::RequestType()
{
return RpcRequest::HTTP;
}
std::string HTTPRpcRequest::Method()
{
return _method;
}
uint64 HTTPRpcRequest::SequenceId()
{
// id is not supported in HTTP
return 0;
}
void HTTPRpcRequest::ProcessRequest(
const RpcServerStreamWPtr& server_stream,
const ServicePoolPtr& service_pool)
{
std::string service_name;
std::string method_name;
if (!ParseMethodFullName(_method, &service_name, &method_name))
{
InnerProcess(server_stream, service_pool);
return;
}
MethodBoard* method_board = FindMethodBoard(service_pool, service_name, method_name);
if (method_board == NULL)
{
InnerProcess(server_stream, service_pool);
return;
}
google::protobuf::Service* service = method_board->GetServiceBoard()->Service();
const google::protobuf::MethodDescriptor* method_desc = method_board->Descriptor();
google::protobuf::Message* request = service->GetRequestPrototype(method_desc).New();
if (_type == POST_PB)
{
bool parse_request_return = request->ParseFromZeroCopyStream(_req_body.get());
if (!parse_request_return)
{
#if 0
LOG(ERROR) << "ProcessRequest(): " << RpcEndpointToString(_remote_endpoint)
<< ": {" << SequenceId() << "}: parse pb body failed";
#else
SLOG(ERROR, "ProcessRequest(): %s: {%lu}: parse pb body failed",
RpcEndpointToString(_remote_endpoint).c_str(), SequenceId());
#endif
SendFailedResponse(server_stream,
RPC_ERROR_PARSE_REQUEST_MESSAGE, "parse pb body failed");
delete request;
return;
}
}
else
{
std::string json_str;
if (_type == POST)
{
json_str = _req_body->ToString();
}
else
{
json_str = _query_params["request"];
}
if (json_str.empty())
{
// if null json str, set as null object
json_str = "{}";
}
std::string err;
_req_json = ParseJson(json_str.c_str(), err);
if (_req_json == NULL || jsonobject2pb(_req_json, request, err) < 0)
{
#if 0
LOG(ERROR) << "ProcessRequest(): " << RpcEndpointToString(_remote_endpoint)
<< ": {" << SequenceId() << "}: parse json failed: " << err;
#else
SLOG(ERROR, "ProcessRequest(): %s: {%lu}: parse json failed: %s",
RpcEndpointToString(_remote_endpoint).c_str(), SequenceId(), err.c_str());
#endif
SendFailedResponse(server_stream,
RPC_ERROR_PARSE_REQUEST_MESSAGE, "parse json failed: " + err);
delete request;
return;
}
}
google::protobuf::Message* response = service->GetResponsePrototype(method_desc).New();
RpcController* controller = new RpcController();
const RpcControllerImplPtr& cntl = controller->impl();
cntl->SetSequenceId(0);
cntl->SetMethodId(_method);
cntl->SetLocalEndpoint(_local_endpoint);
cntl->SetRemoteEndpoint(_remote_endpoint);
cntl->SetRpcServerStream(server_stream);
cntl->SetRequestReceivedTime(_received_time);
cntl->SetResponseCompressType(CompressTypeNone);
// ATTENTION: because the lifetime of HttpRpcRequest covers CallMethod() of service,
// so we can just store pointers to avoid unnecessary data copy.
cntl->SetHttp();
cntl->SetHttpPath(&_path);
cntl->SetHttpQueryParams(&_query_params);
cntl->SetHttpHeaders(&_headers);
CallMethod(method_board, controller, request, response);
}
ReadBufferPtr HTTPRpcRequest::AssembleSucceedResponse(
const RpcControllerImplPtr& /*cntl*/,
const google::protobuf::Message* response,
std::string& err)
{
WriteBuffer write_buffer;
if (_type == POST_PB)
{
if (!RenderResponse(&write_buffer, PROTOBUF, response->SerializeAsString()))
{
err = "render protobuf response failed";
return ReadBufferPtr();
}
}
else
{
std::string json_str;
pb2json(response, json_str);
if (!RenderResponse(&write_buffer, JSON, json_str))
{
err = "render json response failed";
return ReadBufferPtr();
}
}
ReadBufferPtr read_buffer(new ReadBuffer());
write_buffer.SwapOut(read_buffer.get());
return read_buffer;
}
ReadBufferPtr HTTPRpcRequest::AssembleFailedResponse(
int32 error_code,
const std::string& reason,
std::string& err)
{
std::ostringstream oss;
oss << "\"ERROR: " << error_code << ": "
<< StringUtils::replace_all(reason, "\"", "\\\"") << "\"";
WriteBuffer write_buffer;
if (!RenderResponse(&write_buffer, JSON, oss.str()))
{
err = "render json response failed";
return ReadBufferPtr();
}
ReadBufferPtr read_buffer(new ReadBuffer());
write_buffer.SwapOut(read_buffer.get());
return read_buffer;
}
bool HTTPRpcRequest::ParsePath()
{
if (_original_path.empty() || _original_path[0] != '/')
{
return false;
}
// decode
_decoded_path = StringUtils::decode_url(_original_path,
(StringUtils::E_DECODE_RESERVED_CHAR | StringUtils::E_DECODE_PERCENT_SIGN_CHAR));
#if 0
#else
SLOG(DEBUG, "ParsePath(): original_path=[%s], decoded_path=[%s]",
_original_path.c_str(), _decoded_path.c_str());
#endif
// parse method
size_t start = 1; // skip first '/'
size_t end = _decoded_path.size();
for (size_t i = start; i != end; ++i)
{
if (_decoded_path[i] == '?' || _decoded_path[i] == '#')
{
end = i;
break;
}
}
_path = _decoded_path.substr(0, end);
_method = _decoded_path.substr(start, end - start);
// parse query
if (end < _decoded_path.size() && _decoded_path[end] == '?')
{
start = end + 1;
end = _decoded_path.size();
for (size_t i = start; i != end; ++i)
{
if (_decoded_path[i] == '#')
{
end = i;
break;
}
}
_query_string = _decoded_path.substr(start, end - start);
if (!_query_string.empty())
{
std::vector<std::string> param_list;
StringUtils::split(_query_string, "&", ¶m_list);
for (size_t i = 0; i < param_list.size(); ++i)
{
const std::string& param = param_list[i];
std::string::size_type pos = param.find('=');
if (pos != std::string::npos)
{
std::string key = param.substr(0, pos);
std::string value = param.substr(pos + 1);
_query_params[key] = value;
}
}
}
}
// parse fragment
if (end < _decoded_path.size() && _decoded_path[end] == '#')
{
_fragment_id = _decoded_path.substr(end + 1);
}
return true;
}
void HTTPRpcRequest::SendResponse(
const RpcServerStreamWPtr& server_stream,
const HTTPResponse& response)
{
WriteBuffer write_buffer;
if (!RenderResponse(&write_buffer, response))
{
#if 0
LOG(ERROR) << "SendResponse(): " << RpcEndpointToString(_remote_endpoint)
<< ": {" << SequenceId() << "}"
<< ": render response failed";
#else
SLOG(ERROR, "SendResponse(): %s: {%lu}: render response failed",
RpcEndpointToString(_remote_endpoint).c_str(), SequenceId());
#endif
return;
}
ReadBufferPtr read_buffer(new ReadBuffer());
write_buffer.SwapOut(read_buffer.get());
response.content->SwapOut(read_buffer.get());
SendSucceedResponse(server_stream, read_buffer);
}
bool HTTPRpcRequest::RenderResponse(
google::protobuf::io::ZeroCopyOutputStream* output,
const RenderType type,
const std::string& body)
{
std::ostringstream oss;
oss << body.size();
google::protobuf::io::Printer printer(output, '$');
printer.Print("HTTP/1.1 200 OK\r\n");
switch (type)
{
case JSON:
printer.Print("Content-Type: application/json\r\n");
break;
case PROTOBUF:
printer.Print("Content-Type: application/protobuf\r\n");
break;
case HTML:
printer.Print("Content-Type: text/html; charset=UTF-8\r\n");
break;
default:
break;
}
printer.Print("Access-Control-Allow-Origin: *\r\n");
printer.Print("Content-Length: $LENGTH$\r\n", "LENGTH", oss.str());
printer.Print("\r\n");
printer.PrintRaw(body);
return !printer.failed();
}
bool HTTPRpcRequest::RenderResponse(
google::protobuf::io::ZeroCopyOutputStream* output,
const HTTPResponse& response)
{
std::ostringstream oss;
oss << response.content->ByteCount();
google::protobuf::io::Printer printer(output, '$');
printer.Print("$STATUS_LINE$\r\n", "STATUS_LINE", response.status_line);
printer.Print("Content-Type: $TYPE$\r\n", "TYPE", response.content_type);
printer.Print("Access-Control-Allow-Origin: *\r\n");
printer.Print("Content-Length: $LENGTH$\r\n", "LENGTH", oss.str());
printer.Print("\r\n");
return !printer.failed();
}
rapidjson::Document* HTTPRpcRequest::ParseJson(
const char* str,
std::string& err)
{
rapidjson::Document* d = new rapidjson::Document();
d->Parse<0>(str);
if (d->HasParseError())
{
err = d->GetParseError();
delete d;
return NULL;
}
return d;
}
void HTTPRpcRequest::InnerProcess(const RpcServerStreamWPtr& server_stream,
const ServicePoolPtr& service_pool)
{
RpcServerImpl* server = service_pool->RpcServer();
WebServicePtr web_service = server->GetWebService();
if (_type == POST)
{
std::vector<std::string> param_list;
StringUtils::split(_req_body->ToString(), "&", ¶m_list);
for (size_t i = 0; i < param_list.size(); ++i)
{
const std::string& param = param_list[i];
std::string::size_type pos = param.find('=');
if (pos != std::string::npos)
{
std::string key = param.substr(0, pos);
std::string value = param.substr(pos + 1);
_query_params[key] = value;
}
}
}
if (web_service && web_service->RoutePage(
shared_from_this(), server_stream))
{
return;
}
else
{
#if 0
LOG(ERROR) << "InnerProcess(): " << RpcEndpointToString(_remote_endpoint)
<< ": {" << SequenceId() << "}: method not found: " << _method;
#else
SLOG(ERROR, "InnerProcess(): %s: {%lu}: method not found: %s",
RpcEndpointToString(_remote_endpoint).c_str(), SequenceId(), _method.c_str());
#endif
SendFailedResponse(server_stream,
RPC_ERROR_FOUND_METHOD, "method not found: " + _method);
return;
}
}
} // namespace trident