Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
pcap_control_server.cpp
Go to the documentation of this file.
2#include <slick/logger.hpp>
3#include <utils/timestamp.hpp>
4#include <chrono>
5#include <cstring>
6#include <format>
7#include <iterator>
8
9namespace slick::sim::md_feed {
10
11namespace {
12
13std::string utc(uint64_t ns) {
14 // Not the uint64_t overload: it guesses the unit from the magnitude.
15 return utils::format_timestamp_iso8601(std::chrono::system_clock::time_point(
16 std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::nanoseconds(ns))));
17}
18
20void describe(const FeedStatusMessage &status, std::string_view message, std::string &out) {
21 // Copies: a packed field cannot bind to std::format's references.
22 const FeedState state = status.state;
23 const unsigned permille = status.progress_permille;
24 const uint64_t current_ns = status.current_ns;
25 const uint64_t begin_ns = status.begin_ns;
26 const uint64_t end_ns = status.end_ns;
27 const double speed = status.speed;
28 std::format_to(std::back_inserter(out), "{} {}.{}%, capture {}, window {}..{}, speed {}", to_string(state),
29 permille / 10, permille % 10, utc(current_ns), utc(begin_ns), utc(end_ns), speed);
30 if (!message.empty()) {
31 out += " - ";
32 out += message;
33 }
34}
35
36} // namespace
37
38PcapControlServer::PcapControlServer(std::string name, const slick::socket::TCPServerConfig &config,
39 std::string cli_name)
40 : Server(name, config)
41 , name_(std::move(name))
42 , cli_(std::move(cli_name))
43{
44}
45
49
51 if (!Server::start()) {
52 LOG_ERROR("{} control channel failed to start on port {}", name_, Server::port());
53 return false;
54 }
55 LOG_INFO("{} control channel listening on port {}", name_, Server::port());
56 return true;
57}
58
60 Server::stop();
61}
62
63void PcapControlServer::publish_status(const FeedStatusMessage &status, std::string_view message) {
64 const auto index = outbox_.reserve();
65 StatusSlot &slot = *outbox_[index];
66 std::memcpy(slot.bytes, &status, sizeof(status));
67 slot.message_size = static_cast<uint16_t>(
68 cli::cut_text(message, sizeof(slot.message)).copy(slot.message, sizeof(slot.message)));
69 outbox_.publish(index);
70}
71
72void PcapControlServer::onClientConnected(int client_id, const std::string &client_address) {
73 LOG_INFO("{} control channel: connection {} from {}", name_, client_id, client_address);
74 // Deliver what is queued to the clients already here, so that last_status_ is current
75 // and this client is not sent a stale state followed by the newer ones.
76 deliver();
77 clients_.insert(client_id);
78 if (last_status_) {
79 Server::send_data(client_id, last_status_->bytes, sizeof(last_status_->bytes));
80 }
81}
82
84 LOG_INFO("{} control channel: connection {} closed", name_, client_id);
85 clients_.erase(client_id);
86 streams_.erase(client_id);
87}
88
89void PcapControlServer::onClientData(int client_id, const uint8_t *data, size_t length) {
90 const bool ok = streams_.feed(client_id, data, length, [this](const ControlHeader &header, const uint8_t *) {
91 if (header.type != ControlMessageType::START || header.length != sizeof(StartMessage)) {
92 return false;
93 }
94 request_start();
95 return true;
96 });
97 if (!ok) {
98 LOG_WARN("{} control channel: malformed message from connection {}, closing it", name_, client_id);
99 Server::disconnect_client(client_id);
100 }
101}
102
104 deliver();
105 cli_.serve([this](const cli::Command &command, std::string &out) { return serve_cli(command, out); });
106}
107
108void PcapControlServer::deliver() {
109 for (;;) {
110 auto [slot, size] = outbox_.read(outbox_cursor_);
111 if (slot == nullptr) {
112 return;
113 }
114 last_status_ = *slot;
115 for (int client : clients_) {
116 Server::send_data(client, slot->bytes, sizeof(slot->bytes));
117 }
118 }
119}
120
121bool PcapControlServer::serve_cli(const cli::Command &command, std::string &out) {
122 // Again, now that the command is in: a status published before it was posted is
123 // visible from here on, so the answer is never older than the command.
124 deliver();
125 // Zero is IDLE, for the moment before the first status.
126 FeedStatusMessage status{};
127 std::string_view message;
128 if (last_status_) {
129 std::memcpy(&status, last_status_->bytes, sizeof(status));
130 message = {last_status_->message, last_status_->message_size};
131 }
132 switch (command.command) {
134 describe(status, message, out);
135 return true;
137 switch (status.state) {
138 case FeedState::ERROR:
139 out = "cannot start; ";
140 describe(status, message, out);
141 return false;
142 case FeedState::READY: out = "starting; "; break;
143 case FeedState::REPLAYING: out = "already replaying; "; break;
144 case FeedState::FINISHED: out = "already finished; "; break;
145 default: out = "starts once READY; "; break;
146 }
147 // Even once started: the exchange thread ignores it then, as it does a second START.
148 request_start();
149 describe(status, message, out);
150 return true;
151 default:
152 return cli::refuse_unserved(command, out);
153 }
154}
155
156} // namespace slick::sim::md_feed
void publish_status(const FeedStatusMessage &status, std::string_view message)
Sends status to every client now connected, and to each one that connects before the next.
void onClientConnected(int client_id, const std::string &client_address)
void onClientData(int client_id, const uint8_t *data, size_t length)
bool start()
False when the port could not be bound.
PcapControlServer(std::string name, const slick::socket::TCPServerConfig &config, std::string cli_name)
cli_name is the CLI endpoint's (cli::pcap_feed_path).
bool refuse_unserved(const Command &command, std::string &out)
A handler's answer to a command it doesn't serve: says so in out, false.
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.
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
Definition timestamp.hpp:9
@ START_REPLAY
pcap. Starts each feed's replay, as a control-channel START does.
@ PCAP_STATUS
pcap. Each feed's state, progress and window.
FeedState
Where a pcap replay feed is. The values are on the wire: append, never renumber.
@ READY
The book is built and held. Replay starts when a client sends START.
@ FINISHED
The window is replayed out.
@ REPLAYING
Publishing the capture.
@ ERROR
The feed failed; message says why.
constexpr const char * to_string(FeedState state) noexcept
@ START
Client to sim: start the replay.
Every control message starts with this.
The replay feed's state.
Starts the replay of every loaded instrument.
One command, as the CLI server hands it to the thread that runs it.