-
Notifications
You must be signed in to change notification settings - Fork 12
/
rpc.h
141 lines (102 loc) · 3 KB
/
rpc.h
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
#pragma once
#include "log.h"
#include "protocol.h"
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
namespace NRpc {
////////////////////////////////////////////////////////////////////////////////
struct SocketState
{
int fd = 0;
NProtocol::Message current_message;
std::deque<std::string> output_queue;
uint32_t current_output_sent_count = 0;
std::string current_output;
};
using SocketStatePtr = std::shared_ptr<SocketState>;
////////////////////////////////////////////////////////////////////////////////
// input -> output func
using Handler =
std::function<std::string(char message_type, const std::string& message)>;
////////////////////////////////////////////////////////////////////////////////
inline bool process_input(SocketState& state, const Handler& handler)
{
bool success = true;
char buf[512];
int total_read = 0;
while (true) {
auto len = std::min(sizeof(buf), state.current_message.to_read());
auto count = recv(state.fd, buf, len, 0);
if (count == -1) {
if (errno != EAGAIN) {
LOG_PERROR("recv failed");
success = false;
}
break;
} else if (count == 0) {
break;
}
total_read += count;
state.current_message.on_data(buf, count);
if (count < len) {
break;
}
if (state.current_message.is_complete()) {
auto response = handler(
state.current_message.message_type,
state.current_message.buffer);
state.current_message.reset();
if (response.size()) {
state.output_queue.push_back(std::move(response));
}
}
}
if (total_read == 0) {
LOG_INFO("conn closed");
success = false;
}
return success;
}
////////////////////////////////////////////////////////////////////////////////
inline bool process_output(SocketState& state)
{
bool success = true;
while (true) {
auto& buffer = state.current_output;
auto& offset = state.current_output_sent_count;
if (state.current_output.empty()) {
if (state.output_queue.empty()) {
break;
}
buffer = state.output_queue.front();
offset = 0;
state.output_queue.pop_front();
}
auto len = buffer.size() - offset;
const auto count = send(
state.fd,
buffer.data() + offset,
len,
MSG_NOSIGNAL);
if (count == -1) {
if (errno != EAGAIN) {
LOG_PERROR("send failed");
success = false;
}
break;
} else if (count == 0) {
break;
}
if (count == len) {
buffer.clear();
} else {
offset += count;
}
}
return success;
}
} // namespace NRpc