2#include <slick/logger.hpp>
14std::string_view field(
const char *text,
size_t size) {
15 return {text, strnlen(text, size)};
20 return std::string_view(
to_string(command)) !=
"unknown";
26 : Server(
"CLI", config)
27 , reply_timeout_(reply_timeout)
36 auto route = [
this](std::string_view target,
size_t index) {
41 LOG_WARN(
"CLI: target {} is longer than a request can name", target);
43 auto it = targets_.find(target);
44 if (it == targets_.end()) {
45 it = targets_.emplace(std::string(target), std::vector<size_t>{}).first;
47 if (std::find(it->second.begin(), it->second.end(), index) == it->second.end()) {
48 it->second.push_back(index);
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);
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);
67 if (!Server::start()) {
68 LOG_ERROR(
"CLI failed to start on port {}", Server::port());
71 LOG_INFO(
"CLI listening on port {}, {} targets", Server::port(), targets_.size());
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));
87 LOG_INFO(
"CLI: connection {} from {}", client_id, client_address);
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()) {
99 if (
auto pending = pending_.find(it->second.ticket); pending != pending_.end()) {
100 pending->second.client_id = -1;
106 auto it = clients_.find(client_id);
107 if (it == clients_.end()) {
110 auto &client = it->second;
111 const bool ok = streams_.feed(client_id, data, length,
112 [&client](
const ControlHeader &header,
const uint8_t *message) {
114 client.waiting.size() >= MAX_WAITING) {
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);
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);
135 if (pending_.empty()) {
138 const auto now = std::chrono::steady_clock::now();
140 for (
const auto &[ticket, pending] : pending_) {
141 if (now >= pending.deadline) {
142 expired_.push_back(ticket);
145 for (uint64_t ticket : expired_) {
150void CliServer::dispatch(
int client_id) {
151 auto it = clients_.find(client_id);
152 if (it == clients_.end()) {
155 auto &client = it->second;
156 while (client.ticket == 0 && !client.waiting.empty()) {
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));
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 {}: {} {} {}{}{}",
166 arg.empty() ?
"" :
" ", arg);
168 const auto answer = [&](std::string_view text) {
179 std::format(
"unknown command {}",
static_cast<int>(request.
command)));
182 auto route = targets_.find(target);
183 if (route == targets_.end()) {
185 std::format(
"unknown target '{}'; ask for the targets", target));
188 const auto &indices = route->second;
189 if (std::any_of(indices.begin(), indices.end(), [
this](
size_t i) { return endpoints_[i]->busy(); })) {
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) {
203 [[maybe_unused]]
const bool posted = endpoints_[index]->post(command);
206 pending_.emplace(ticket, std::move(pending));
207 pending_count_.store(pending_.size(), std::memory_order_release);
208 client.ticket = ticket;
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()) {
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) {
230void CliServer::finish(uint64_t ticket) {
231 auto it = pending_.find(ticket);
232 if (it == pending_.end()) {
235 Pending pending = std::move(it->second);
240 for (
const auto &answer : pending.answers) {
241 const auto &name = endpoints_[answer.endpoint]->name();
242 if (!answer.answered) {
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());
252 std::string_view rest = answer.text;
254 const size_t eol = rest.find(
'\n');
257 text += rest.substr(0, eol);
259 rest = eol == std::string_view::npos ? std::string_view{} : rest.substr(eol + 1);
260 }
while (!rest.empty());
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;
272 pending_count_.store(pending_.size(), std::memory_order_release);
273 if (pending.client_id >= 0) {
274 dispatch(pending.client_id);
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()),
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());
289std::string CliServer::list_targets()
const {
291 for (
const auto &[name, indices] : targets_) {
296 if (indices.size() > 1) {
297 out += std::format(
" ({} endpoints)", indices.size());
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.