Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
pcap_feed.cpp
Go to the documentation of this file.
1#include "pcap_feed.hpp"
2
3#include <slick/logger.hpp>
4#include <algorithm>
5#include <charconv>
6#include <chrono>
7#include <cmath>
8#include <cstdint>
9#include <cstring>
10#include <format>
11#include <stdexcept>
12
13namespace slick::sim::md_feed {
14
15namespace {
16
17uint64_t time_from_json(const nlohmann::json &config, const char *key, const std::string &feed) {
18 if (!config.contains(key)) {
19 throw std::runtime_error(std::format("pcap feed {}: '{}' is required", feed, key));
20 }
21 const auto &value = config[key];
22 try {
23 if (value.is_number_unsigned()) {
24 return value.get<uint64_t>();
25 }
26 return parse_utc_time_ns(value.get<std::string>());
27 } catch (const std::exception &e) {
28 throw std::runtime_error(std::format("pcap feed {}: '{}': {}", feed, key, e.what()));
29 }
30}
31
32void copy_text(char *dest, size_t size, const std::string &text) {
33 std::memset(dest, 0, size);
34 std::memcpy(dest, text.data(), std::min(text.size(), size - 1));
35}
36
37} // namespace
38
39uint64_t parse_utc_time_ns(const std::string &text) {
40 // YYYY-MM-DDTHH:MM:SS, each field an integer (a sign included, for the range check below).
41 int fields[6] = {};
42 const char *p = text.data();
43 const char *const end = p + text.size();
44 for (int i = 0; i < 6; ++i) {
45 const auto [next, ec] = std::from_chars(p, end, fields[i]);
46 if (ec != std::errc() || (i < 5 && (next == end || *next != "--T::"[i]))) {
47 throw std::runtime_error(std::format("'{}' is not a UTC time like 2026-11-06T14:00:00Z", text));
48 }
49 p = i < 5 ? next + 1 : next;
50 }
51 const auto [year, month, day, hour, minute, second] = fields;
52 uint64_t fraction_ns = 0;
53 size_t pos = static_cast<size_t>(p - text.data());
54 if (pos < text.size() && text[pos] == '.') {
55 ++pos;
56 uint64_t scale = 100'000'000;
57 while (pos < text.size() && text[pos] >= '0' && text[pos] <= '9') {
58 fraction_ns += static_cast<uint64_t>(text[pos] - '0') * scale;
59 scale /= 10;
60 ++pos;
61 }
62 }
63 if (pos < text.size() && text[pos] == 'Z') {
64 ++pos;
65 }
66 // year > 9999 before std::chrono::year, which wraps past 32767: 67562 would read as 2026.
67 if (pos != text.size() || year < 1970 || year > 9999 || month < 1 || month > 12 || day < 1 || day > 31 ||
68 hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
69 throw std::runtime_error(std::format("'{}' is not a UTC time like 2026-11-06T14:00:00Z", text));
70 }
71 const std::chrono::year_month_day date{std::chrono::year{year}, std::chrono::month{static_cast<unsigned>(month)},
72 std::chrono::day{static_cast<unsigned>(day)}};
73 if (!date.ok()) { // Feb 31
74 throw std::runtime_error(std::format("'{}' is not a valid date", text));
75 }
76 const int64_t days = std::chrono::sys_days{date}.time_since_epoch().count();
77 const uint64_t seconds = static_cast<uint64_t>(days) * 86400 + static_cast<uint64_t>(hour * 3600 + minute * 60 + second);
78 if (seconds > UINT64_MAX / 1'000'000'000ull - 1) { // past 2554, beyond the nanosecond count
79 throw std::runtime_error(std::format("'{}' is not a time this system can represent", text));
80 }
81 return seconds * 1'000'000'000ull + fraction_ns;
82}
83
84PcapFeedConfig PcapFeedConfig::from_json(const nlohmann::json &config, const std::string &feed) {
86 c.root = config.value("pcap_root", std::string());
87 c.begin_ns = time_from_json(config, "begin", feed);
88 c.end_ns = time_from_json(config, "end", feed);
89 if (c.end_ns <= c.begin_ns) {
90 throw std::runtime_error(std::format("pcap feed {}: 'end' must be after 'begin'", feed));
91 }
92 c.speed = config.value("speed", 1.0);
93 if (!(c.speed >= 0) || !std::isfinite(c.speed)) {
94 throw std::runtime_error(std::format("pcap feed {}: 'speed' must be 0 (unpaced) or above", feed));
95 }
96 if (!config.contains("control_channel") || !config["control_channel"].contains("port")) {
97 throw std::runtime_error(std::format(
98 "pcap feed {}: needs control_channel.port - clients start the replay over it, and it waits for them", feed));
99 }
100 const auto port = config["control_channel"]["port"].get<int64_t>();
101 if (port < 0 || port > 65535) {
102 throw std::runtime_error(std::format("pcap feed {}: control_channel.port {} is not a port", feed, port));
103 }
104 c.control_port = static_cast<uint16_t>(port);
105 c.control_max_connections = config["control_channel"].value("max_connections", c.control_max_connections);
106 return c;
107}
108
109std::vector<PcapLine> parse_pcap_lines(const nlohmann::json &config,
110 std::span<const std::pair<const char *, uint8_t>> keys) {
111 std::vector<PcapLine> lines;
112 for (const auto &[key, line] : keys) {
113 if (!config.contains(key)) {
114 continue;
115 }
116 const auto &group = config[key];
117 PcapLine l;
118 l.line = line;
119 l.address = group.at("address").get<std::string>();
120 l.port = group.at("port").get<uint16_t>();
121 if (group.contains("path")) {
122 l.paths.push_back(group["path"].get<std::string>());
123 }
124 if (group.contains("paths")) {
125 for (const auto &path : group["paths"]) {
126 l.paths.push_back(path.get<std::string>());
127 }
128 }
129#ifdef _WIN32
130 if (l.paths.empty()) {
131 throw std::runtime_error(std::format(
132 "'{}' needs \"path\" or \"paths\" on Windows: the recorded layout's <address>:<port> names can't "
133 "exist there",
134 key));
135 }
136#endif
137 lines.push_back(std::move(l));
138 }
139 return lines;
140}
141
142PcapFeedBase::PcapFeedBase(std::string name, Venue venue, const PcapFeedConfig &config, std::vector<PcapLine> lines,
143 std::shared_ptr<ReplayGate> gate)
144 : name_(std::move(name))
145 , venue_(venue)
146 , config_(config)
147 , gate_(std::move(gate))
148 , source_(name_, config.root, config.begin_ns, config.end_ns, std::move(lines))
149 , control_(std::format("{} pcap {}", to_string(venue), name_), [&] {
150 slick::socket::TCPServerConfig tcp;
151 tcp.port = config.control_port;
152 tcp.max_connections = config.control_max_connections;
153 return tcp;
154 }(), cli::pcap_feed_path(to_string(venue), name_))
155 , pacer_(config.speed)
156{
157 if (!gate_) {
158 throw std::logic_error("PcapFeedBase needs a replay gate");
159 }
160}
161
165
167 if (!control_.start()) {
168 control_down_ = true;
169 enter(FeedState::ERROR, 0, "the control channel could not be started");
170 return;
171 }
172 source_.start();
173 enter(FeedState::LOADING, 0);
174 LOG_INFO("pcap feed {}: loading {} .. {} (speed {})", name_, config_.begin_ns, config_.end_ns, config_.speed);
175}
176
178 source_.stop();
179 control_.stop();
180}
181
182void PcapFeedBase::enter(FeedState next, uint64_t now_ns, std::string message) {
183 if (state_ == next && message == message_) {
184 return;
185 }
186 state_ = next;
187 message_ = std::move(message);
188 if (next == FeedState::ERROR) {
189 LOG_ERROR("pcap feed {}: {}", name_, message_);
190 } else {
191 LOG_INFO("pcap feed {}: {}{}{}", name_, to_string(next), message_.empty() ? "" : " - ", message_);
192 }
193 // What the handler made of the capture, where a gap or a malformed packet would show.
194 if (next == FeedState::READY || next == FeedState::FINISHED || next == FeedState::ERROR) {
195 if (const auto detail = describe(); !detail.empty()) {
196 LOG_INFO("pcap feed {}: {}", name_, detail);
197 }
198 if (const auto cut = source_.truncated_frames(); cut != 0) {
199 LOG_WARN("pcap feed {}: {} captured frames were cut short or malformed and skipped", name_, cut);
200 }
201 }
202 publish_status(now_ns);
203}
204
205void PcapFeedBase::publish_status(uint64_t now_ns) {
206 FeedStatusMessage status{};
207 status.header = {static_cast<uint16_t>(sizeof(status)), ControlMessageType::FEED_STATUS};
208 status.venue = static_cast<uint8_t>(venue_);
209 status.state = state_;
210 copy_text(status.feed, sizeof(status.feed), name_);
211 status.begin_ns = config_.begin_ns;
212 status.end_ns = config_.end_ns;
213 status.current_ns = std::clamp(current_capture_ns_, config_.begin_ns, config_.end_ns);
214 if (state_ == FeedState::FINISHED) {
215 status.current_ns = config_.end_ns;
216 }
217 const uint64_t span = config_.end_ns - config_.begin_ns;
218 status.progress_permille = state_ == FeedState::FINISHED ? 1000 : static_cast<uint16_t>(
219 std::min<uint64_t>(1000, (status.current_ns - config_.begin_ns) * 1000 / span));
220 status.speed = config_.speed;
221 copy_text(status.message, sizeof(status.message), message_);
222 control_.publish_status(status, message_);
223 // start() has no clock yet (now_ns 0); the first poll arms the heartbeat.
224 next_heartbeat_ns_ = now_ns == 0 ? 0 : now_ns + HEARTBEAT_NS;
225}
226
227void PcapFeedBase::serve_control() {
228 if (control_.take_start()) {
229 start_requested_ = true;
230 }
231}
232
233void PcapFeedBase::poll(uint64_t now_ns) {
234 serve_control();
235 if (state_ == FeedState::IDLE || state_ == FeedState::FINISHED || state_ == FeedState::ERROR) {
236 if (control_down_) {
237 // No control thread answers the CLI. Unanswered, each command waits out the CLI's
238 // timeout, and 16 of them leave `pcap` busy for good.
239 control_.serve_unstarted();
240 }
241 return;
242 }
243 feed(now_ns);
244 if (next_heartbeat_ns_ == 0) {
245 next_heartbeat_ns_ = now_ns + HEARTBEAT_NS;
246 }
247 if (now_ns >= next_heartbeat_ns_ && state_ != FeedState::READY) {
248 publish_status(now_ns);
249 }
250}
251
252void PcapFeedBase::feed(uint64_t now_ns) {
254
255 if (state_ == FeedState::LOADING) {
256 if (!source_.positioned()) {
257 return;
258 }
259 if (const auto error = source_.error(); !error.empty()) {
260 enter(FeedState::ERROR, now_ns, error);
261 return;
262 }
263 enter(FeedState::SYNCING, now_ns);
264 }
265
266 if (state_ == FeedState::SYNCING) {
267 // Unpaced and unstamped: the book is being built, and nothing goes out.
268 event_time_ns_ = now_ns;
269 for (uint32_t i = 0; i < MAX_PACKETS_PER_POLL && source_.peek(item); ++i) {
270 current_capture_ns_ = item.ts_ns;
271 on_packet(item.line, item.data, item.size, now_ns);
272 source_.pop();
273 if (synchronized()) {
274 on_timer(now_ns);
275 enter(FeedState::READY, now_ns);
276 break;
277 }
278 }
279 if (state_ == FeedState::SYNCING) {
280 on_timer(now_ns);
281 if (synchronized()) {
282 enter(FeedState::READY, now_ns);
283 } else {
284 if (source_.finished()) {
285 const auto error = source_.error();
286 enter(FeedState::ERROR, now_ns,
287 error.empty() ? "the capture ended before the book was synchronized; widen the window "
288 "or check that the snapshot capture covers its start"
289 : error);
290 }
291 return;
292 }
293 }
294 }
295
296 if (state_ == FeedState::READY) {
297 if (!start_requested_) {
298 return;
299 }
300 // The held book is published from now, even if no packet is left to replay.
301 gate_->open();
302 if (!source_.peek(item)) {
303 if (source_.finished()) {
304 if (const auto error = source_.error(); !error.empty()) {
305 enter(FeedState::ERROR, now_ns, error);
306 } else {
307 enter(FeedState::FINISHED, now_ns);
308 }
309 }
310 return;
311 }
312 // The capture time of the next packet is what the wall clock starts from.
313 pacer_.anchor(item.ts_ns, now_ns);
314 enter(FeedState::REPLAYING, now_ns);
315 }
316
317 if (state_ == FeedState::REPLAYING) {
318 for (uint32_t i = 0; i < MAX_PACKETS_PER_POLL && source_.peek(item); ++i) {
319 if (!pacer_.is_due(item.ts_ns, now_ns)) {
320 break;
321 }
322 current_capture_ns_ = item.ts_ns;
323 event_time_ns_ = pacer_.rebase_ns(item.ts_ns, now_ns);
324 on_packet(item.line, item.data, item.size, now_ns);
325 source_.pop();
326 }
327 // The handler's timers fire now, not at the last packet's time.
328 event_time_ns_ = now_ns;
329 on_timer(now_ns);
330 if (source_.finished()) {
331 if (const auto error = source_.error(); !error.empty()) {
332 enter(FeedState::ERROR, now_ns, error);
333 } else {
334 enter(FeedState::FINISHED, now_ns);
335 }
336 }
337 }
338}
339
340} // namespace slick::sim::md_feed
const std::string & name() const noexcept
Definition pcap_feed.hpp:95
virtual void on_timer(uint64_t now_ns)=0
The handler's timers (gap timeouts), while it is being fed.
void poll(uint64_t now_ns)
Exchange thread: serves control requests, advances the state machine and feeds the handler what is du...
virtual std::string describe() const
What the handler has done so far, for the log at READY and at the end: packets, gaps,...
virtual void on_packet(uint8_t line, const uint8_t *data, size_t size, uint64_t now_ns)=0
Hands one captured packet to the venue's protocol handler.
PcapFeedBase(std::string name, Venue venue, const PcapFeedConfig &config, std::vector< PcapLine > lines, std::shared_ptr< ReplayGate > gate)
gate is shared with the market-data publisher, which holds market data back until it opens.
std::string error() const
What stopped the reader, empty when nothing did. Any thread.
bool positioned() const
True once every line has been read up to begin_ns and holds a first packet (or has none),...
bool peek(Item &item)
The next packet, without consuming it.
void pop()
Consumes the packet peek() returned. Consumer thread.
std::string pcap_feed_path(std::string_view venue, std::string_view feed)
pcap/<venue>/<feed>.
uint64_t parse_utc_time_ns(const std::string &text)
Parses a UTC "YYYY-MM-DDTHH:MM:SS[.fraction][Z]" into nanoseconds since the epoch.
Definition pcap_feed.cpp:39
std::vector< PcapLine > parse_pcap_lines(const nlohmann::json &config, std::span< const std::pair< const char *, uint8_t > > keys)
The multicast groups of a pcap feed's config: for each {key, line} that the config names,...
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.
@ SYNCING
Building the book from the snapshot and incremental captures. Nothing is published.
@ LOADING
Opening the capture files and reading up to the window's begin.
constexpr const char * to_string(FeedState state) noexcept
What a pcap feed's config entry says, beyond its venue's multicast groups.
Definition pcap_feed.hpp:33
static PcapFeedConfig from_json(const nlohmann::json &config, const std::string &feed)
Throws std::runtime_error naming feed when a key is missing or invalid.
Definition pcap_feed.cpp:84
One multicast group of a replay, as the venue knows it (an enum value below MulticastPacketFeed::MAX_...
std::vector< std::string > paths
Capture files for this group, oldest first.
A packet at the head of the stream. data is valid until pop().