3#include <slick/logger.hpp>
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));
21 const auto &value = config[key];
23 if (value.is_number_unsigned()) {
24 return value.get<uint64_t>();
27 }
catch (
const std::exception &e) {
28 throw std::runtime_error(std::format(
"pcap feed {}: '{}': {}", feed, key, e.what()));
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));
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));
49 p = i < 5 ? next + 1 : next;
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] ==
'.') {
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;
63 if (pos < text.size() && text[pos] ==
'Z') {
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));
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)}};
74 throw std::runtime_error(std::format(
"'{}' is not a valid date", text));
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) {
79 throw std::runtime_error(std::format(
"'{}' is not a time this system can represent", text));
81 return seconds * 1'000'000'000ull + fraction_ns;
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);
90 throw std::runtime_error(std::format(
"pcap feed {}: 'end' must be after 'begin'", feed));
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));
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));
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));
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)) {
116 const auto &group = config[key];
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>());
124 if (group.contains(
"paths")) {
125 for (
const auto &path : group[
"paths"]) {
126 l.
paths.push_back(path.get<std::string>());
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 "
137 lines.push_back(std::move(l));
143 std::shared_ptr<ReplayGate> gate)
144 : name_(std::move(
name))
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;
155 , pacer_(config.speed)
158 throw std::logic_error(
"PcapFeedBase needs a replay gate");
167 if (!control_.start()) {
168 control_down_ =
true;
174 LOG_INFO(
"pcap feed {}: loading {} .. {} (speed {})", name_, config_.begin_ns, config_.end_ns, config_.speed);
182void PcapFeedBase::enter(
FeedState next, uint64_t now_ns, std::string message) {
183 if (state_ == next && message == message_) {
187 message_ = std::move(message);
189 LOG_ERROR(
"pcap feed {}: {}", name_, message_);
191 LOG_INFO(
"pcap feed {}: {}{}{}", name_,
to_string(next), message_.empty() ?
"" :
" - ", message_);
195 if (
const auto detail =
describe(); !detail.empty()) {
196 LOG_INFO(
"pcap feed {}: {}", name_, detail);
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);
202 publish_status(now_ns);
205void PcapFeedBase::publish_status(uint64_t now_ns) {
206 FeedStatusMessage 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);
215 status.current_ns = config_.end_ns;
217 const uint64_t span = config_.end_ns - config_.begin_ns;
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_);
224 next_heartbeat_ns_ = now_ns == 0 ? 0 : now_ns + HEARTBEAT_NS;
227void PcapFeedBase::serve_control() {
228 if (control_.take_start()) {
229 start_requested_ =
true;
239 control_.serve_unstarted();
244 if (next_heartbeat_ns_ == 0) {
245 next_heartbeat_ns_ = now_ns + HEARTBEAT_NS;
248 publish_status(now_ns);
252void PcapFeedBase::feed(uint64_t now_ns) {
259 if (
const auto error = source_.
error(); !error.empty()) {
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;
273 if (
synchronized()) {
281 if (
synchronized()) {
284 if (source_.finished()) {
285 const auto error = source_.error();
287 error.empty() ?
"the capture ended before the book was synchronized; widen the window "
288 "or check that the snapshot capture covers its start"
297 if (!start_requested_) {
302 if (!source_.peek(item)) {
303 if (source_.finished()) {
304 if (
const auto error = source_.error(); !error.empty()) {
313 pacer_.anchor(item.
ts_ns, now_ns);
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)) {
322 current_capture_ns_ = item.
ts_ns;
323 event_time_ns_ = pacer_.rebase_ns(item.
ts_ns, now_ns);
328 event_time_ns_ = now_ns;
330 if (source_.finished()) {
331 if (
const auto error = source_.error(); !error.empty()) {
const std::string & name() const noexcept
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.
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
@ FEED_STATUS
Sim to client.
What a pcap feed's config entry says, beyond its venue's multicast groups.
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.
int control_max_connections
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().