Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
cli_server.cpp
Go to the documentation of this file.
1// First: slick-socket logs only through LOG_* macros defined before it is included.
2#include <slick/logger.hpp>
3#include "cli_server.hpp"
4#include <algorithm>
5#include <cassert>
6#include <cstring>
7#include <format>
8#include <thread>
9
10namespace slick::sim::cli {
11
12namespace {
13
14std::string_view field(const char *text, size_t size) {
15 return {text, strnlen(text, size)};
16}
17
19bool known(CliCommandType command) {
20 return std::string_view(to_string(command)) != "unknown";
21}
22
23} // namespace
24
25CliServer::CliServer(const slick::socket::TCPServerConfig &config, std::chrono::milliseconds reply_timeout)
26 : Server("CLI", config)
27 , reply_timeout_(reply_timeout)
28{
29}
30
34
35void CliServer::add_endpoints(const std::string &group, const std::vector<CliEndpoint *> &endpoints) {
36 auto route = [this](std::string_view target, size_t index) {
37 if (target.empty()) {
38 return;
39 }
40 if (target.size() > sizeof(CliRequestMessage::target)) {
41 LOG_WARN("CLI: target {} is longer than a request can name", target);
42 }
43 auto it = targets_.find(target);
44 if (it == targets_.end()) {
45 it = targets_.emplace(std::string(target), std::vector<size_t>{}).first;
46 }
47 if (std::find(it->second.begin(), it->second.end(), index) == it->second.end()) {
48 it->second.push_back(index);
49 }
50 };
51 for (CliEndpoint *endpoint : endpoints) {
52 auto found = std::find(endpoints_.begin(), endpoints_.end(), endpoint);
53 const auto index = static_cast<size_t>(found - endpoints_.begin());
54 if (found == endpoints_.end()) {
55 endpoints_.push_back(endpoint);
56 }
57 route(group, index);
58 const std::string_view name = endpoint->name();
59 for (size_t slash = name.find('/'); slash != std::string_view::npos; slash = name.find('/', slash + 1)) {
60 route(name.substr(0, slash), index);
61 }
62 route(name, index);
63 }
64}
65
67 if (!Server::start()) {
68 LOG_ERROR("CLI failed to start on port {}", Server::port());
69 return false;
70 }
71 LOG_INFO("CLI listening on port {}, {} targets", Server::port(), targets_.size());
72 return true;
73}
74
76 Server::stop();
77}
78
79void CliServer::flush(std::chrono::milliseconds limit) {
80 const auto deadline = std::chrono::steady_clock::now() + limit;
81 while (pending_count_.load(std::memory_order_acquire) != 0 && std::chrono::steady_clock::now() < deadline) {
82 std::this_thread::sleep_for(std::chrono::milliseconds(1));
83 }
84}
85
86void CliServer::onClientConnected(int client_id, const std::string &client_address) {
87 LOG_INFO("CLI: connection {} from {}", client_id, client_address);
88 clients_[client_id];
89}
90
92 LOG_INFO("CLI: connection {} closed", client_id);
93 streams_.erase(client_id);
94 auto it = clients_.find(client_id);
95 if (it == clients_.end()) {
96 return;
97 }
98 // The answer still comes; it just has no one to go to.
99 if (auto pending = pending_.find(it->second.ticket); pending != pending_.end()) {
100 pending->second.client_id = -1;
101 }
102 clients_.erase(it);
103}
104
105void CliServer::onClientData(int client_id, const uint8_t *data, size_t length) {
106 auto it = clients_.find(client_id);
107 if (it == clients_.end()) {
108 return;
109 }
110 auto &client = it->second;
111 const bool ok = streams_.feed(client_id, data, length,
112 [&client](const ControlHeader &header, const uint8_t *message) {
113 if (header.type != ControlMessageType::CLI_REQUEST || header.length != sizeof(CliRequestMessage) ||
114 client.waiting.size() >= MAX_WAITING) {
115 return false;
116 }
117 std::memcpy(&client.waiting.emplace_back(), message, sizeof(CliRequestMessage));
118 return true;
119 });
120 if (!ok) {
121 LOG_WARN("CLI: malformed message or too many requests from connection {}, closing it", client_id);
122 client.waiting.clear();
123 Server::disconnect_client(client_id);
124 return;
125 }
126 dispatch(client_id);
127}
128
130 for (size_t i = 0; i < endpoints_.size(); ++i) {
131 endpoints_[i]->take_replies([this, i](uint64_t ticket, CliStatus status, std::string_view text) {
132 on_reply(i, ticket, status, text);
133 });
134 }
135 if (pending_.empty()) {
136 return;
137 }
138 const auto now = std::chrono::steady_clock::now();
139 expired_.clear();
140 for (const auto &[ticket, pending] : pending_) {
141 if (now >= pending.deadline) {
142 expired_.push_back(ticket);
143 }
144 }
145 for (uint64_t ticket : expired_) {
146 finish(ticket);
147 }
148}
149
150void CliServer::dispatch(int client_id) {
151 auto it = clients_.find(client_id);
152 if (it == clients_.end()) {
153 return;
154 }
155 auto &client = it->second;
156 while (client.ticket == 0 && !client.waiting.empty()) {
157 const CliRequestMessage request = client.waiting.front();
158 client.waiting.pop_front();
159 const auto target = field(request.target, sizeof(request.target));
160 const auto arg = field(request.arg, sizeof(request.arg));
161 // Copies: a packed field cannot bind to the logger's references.
162 const uint32_t request_id = request.request_id;
163 const int flag = request.flag;
164 SLICK_LOGGER_LOG_IF_ENABLED(log_level(request.command), "CLI: connection {} request {}: {} {} {}{}{}",
165 client_id, request_id, target, to_string(request.command), flag,
166 arg.empty() ? "" : " ", arg);
167
168 const auto answer = [&](std::string_view text) {
169 send_reply(client_id, request.request_id, CliStatus::OK, text);
170 };
171 switch (request.command) {
172 case CliCommandType::LIST_TARGETS: answer(list_targets()); continue;
173 case CliCommandType::LIST_FEEDS: answer(feeds_); continue;
174 case CliCommandType::GET_VERSION: answer(version_); continue;
175 default: break;
176 }
177 if (!known(request.command)) {
178 send_reply(client_id, request.request_id, CliStatus::FAILED,
179 std::format("unknown command {}", static_cast<int>(request.command)));
180 continue;
181 }
182 auto route = targets_.find(target);
183 if (route == targets_.end()) {
184 send_reply(client_id, request.request_id, CliStatus::FAILED,
185 std::format("unknown target '{}'; ask for the targets", target));
186 continue;
187 }
188 const auto &indices = route->second;
189 if (std::any_of(indices.begin(), indices.end(), [this](size_t i) { return endpoints_[i]->busy(); })) {
190 send_reply(client_id, request.request_id, CliStatus::FAILED, std::format("'{}' is busy", target));
191 continue;
192 }
193
194 const uint64_t ticket = next_ticket_++;
195 Command command{ticket, request.command, request.flag, {}};
196 std::memcpy(command.arg, request.arg, sizeof(command.arg));
197 Pending pending{client_id, request.request_id, {}, indices.size(),
198 std::chrono::steady_clock::now() + reply_timeout_};
199 pending.answers.reserve(indices.size());
200 for (size_t index : indices) {
201 pending.answers.push_back(Answer{index, false, CliStatus::FAILED, {}});
202 // None was busy, and a target names each endpoint once.
203 [[maybe_unused]] const bool posted = endpoints_[index]->post(command);
204 assert(posted);
205 }
206 pending_.emplace(ticket, std::move(pending));
207 pending_count_.store(pending_.size(), std::memory_order_release);
208 client.ticket = ticket;
209 }
210}
211
212void CliServer::on_reply(size_t endpoint, uint64_t ticket, CliStatus status, std::string_view text) {
213 auto it = pending_.find(ticket);
214 if (it == pending_.end()) {
215 return; // Timed out; the client has had its answer.
216 }
217 for (auto &answer : it->second.answers) {
218 if (answer.endpoint == endpoint && !answer.answered) {
219 answer.answered = true;
220 answer.status = status;
221 answer.text.assign(text);
222 if (--it->second.remaining == 0) {
223 finish(ticket);
224 }
225 return;
226 }
227 }
228}
229
230void CliServer::finish(uint64_t ticket) {
231 auto it = pending_.find(ticket);
232 if (it == pending_.end()) {
233 return;
234 }
235 Pending pending = std::move(it->second);
236 pending_.erase(it);
237
238 CliStatus status = CliStatus::OK;
239 std::string text;
240 for (const auto &answer : pending.answers) {
241 const auto &name = endpoints_[answer.endpoint]->name();
242 if (!answer.answered) {
243 status = CliStatus::FAILED;
244 text += std::format("{}: no answer within {} ms\n", name, reply_timeout_.count());
245 LOG_WARN("CLI: {} did not answer request {} within {} ms", name, pending.request_id,
246 reply_timeout_.count());
247 continue;
248 }
249 if (answer.status != CliStatus::OK) {
250 status = CliStatus::FAILED;
251 }
252 std::string_view rest = answer.text;
253 do {
254 const size_t eol = rest.find('\n');
255 text += name;
256 text += ": ";
257 text += rest.substr(0, eol);
258 text += '\n';
259 rest = eol == std::string_view::npos ? std::string_view{} : rest.substr(eol + 1);
260 } while (!rest.empty());
261 }
262 if (!text.empty()) {
263 text.pop_back();
264 }
265
266 if (pending.client_id >= 0) {
267 send_reply(pending.client_id, pending.request_id, status, text);
268 if (auto client = clients_.find(pending.client_id); client != clients_.end()) {
269 client->second.ticket = 0;
270 }
271 }
272 pending_count_.store(pending_.size(), std::memory_order_release);
273 if (pending.client_id >= 0) {
274 dispatch(pending.client_id);
275 }
276}
277
278void CliServer::send_reply(int client_id, uint32_t request_id, CliStatus status, std::string_view text) {
279 text = cut_text(text, UINT16_MAX - sizeof(CliReplyMessage));
280 const CliReplyMessage reply{{static_cast<uint16_t>(sizeof(CliReplyMessage) + text.size()),
282 request_id, status};
283 reply_.resize(sizeof(reply) + text.size());
284 std::memcpy(reply_.data(), &reply, sizeof(reply));
285 std::memcpy(reply_.data() + sizeof(reply), text.data(), text.size());
286 Server::send_data(client_id, reply_.data(), reply_.size());
287}
288
289std::string CliServer::list_targets() const {
290 std::string out;
291 for (const auto &[name, indices] : targets_) {
292 if (!out.empty()) {
293 out += '\n';
294 }
295 out += name;
296 if (indices.size() > 1) {
297 out += std::format(" ({} endpoints)", indices.size());
298 }
299 }
300 return out;
301}
302
303} // namespace slick::sim::cli
Where the CLI server's commands reach a thread that owns some state (the main thread,...
void add_endpoints(const std::string &group, const std::vector< CliEndpoint * > &endpoints)
Routes group, and every /-prefix of each endpoint's name, to the endpoints.
bool start()
False when the port could not be bound.
void onClientDisconnected(int client_id)
void onClientConnected(int client_id, const std::string &client_address)
CliServer(const slick::socket::TCPServerConfig &config, std::chrono::milliseconds reply_timeout=DEFAULT_REPLY_TIMEOUT)
void flush(std::chrono::milliseconds limit)
Waits up to limit for the replies still owed to clients to go out, so the answer to a SHUTDOWN gets s...
void onClientData(int client_id, const uint8_t *data, size_t length)
The CLI commands that switch a gateway's business rejects per ID: REJECT_LOGON, REJECT_NEW_ORDERS and...
constexpr slick::logger::LogLevel log_level(CliCommandType command) noexcept
What a command and its answer are logged at: DEBUG for what clients poll.
constexpr std::string_view cut_text(std::string_view text, size_t size) noexcept
text cut to size bytes, backing off up to 3 so as not to split a UTF-8 character.
CliCommandType
What a CLI request asks for. The values are on the wire: append, never renumber.
@ GET_VERSION
Any target. The CLI server answers with slick-sim's version.
@ LIST_TARGETS
Any target. The CLI server answers with every target it routes to.
@ LIST_FEEDS
Any target. The CLI server answers with every enabled market-data feed.
constexpr const char * to_string(FeedState state) noexcept
@ CLI_REQUEST
Client to sim, on the CLI port: CliRequestMessage.
@ CLI_REPLY
Sim to client, on the CLI port: CliReplyMessage.
One command to the simulator, on the CLI port.
char arg[64]
The ID or level. NUL-padded.
uint8_t flag
1 on, 0 off, for the commands that toggle.
char target[32]
sim, a venue (cme), an instance (cme/<segment>). NUL-padded.
uint32_t request_id
The client's own, echoed in the reply.
Every control message starts with this.