Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
pcap_replay_source.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "pcap_reader.hpp"
4
5#include <slick/spsc_queue.hpp>
6
7#include <algorithm>
8#include <atomic>
9#include <bit>
10#include <cmath>
11#include <chrono>
12#include <cstdint>
13#include <ctime>
14#include <exception>
15#include <filesystem>
16#include <format>
17#include <memory>
18#include <optional>
19#include <queue>
20#include <stdexcept>
21#include <string>
22#include <thread>
23#include <utility>
24#include <vector>
25
26namespace slick::sim::md_feed {
27
30struct PcapLine {
31 uint8_t line = 0;
32 std::string address;
33 uint16_t port = 0;
36 std::vector<std::string> paths;
37};
38
46[[nodiscard]] inline std::vector<std::string> resolve_pcap_files(const std::string &root, const std::string &address,
47 uint16_t port, uint64_t begin_ns,
48 uint64_t end_ns) {
49 namespace fs = std::filesystem;
50 constexpr int64_t DAY_S = 86400;
51 std::vector<std::string> files;
52 const std::string group = std::format("{}:{}", address, port);
53 const int64_t first_day = static_cast<int64_t>(begin_ns / 1'000'000'000ull) / DAY_S - 1;
54 const int64_t last_day = static_cast<int64_t>(end_ns / 1'000'000'000ull) / DAY_S + 1;
55 for (int64_t day = first_day; day <= last_day; ++day) {
56 const std::chrono::year_month_day date{std::chrono::sys_days{std::chrono::days{day}}};
57 const fs::path dir = fs::path(root) /
58 std::format("{:04}-{:02}-{:02}", int(date.year()), unsigned(date.month()), unsigned(date.day())) / group;
59 for (const char *ext : {".pcap.zst", ".pcap.gz", ".pcap"}) {
60 const fs::path file = dir / (group + ext);
61 std::error_code ec;
62 if (fs::is_regular_file(file, ec)) {
63 files.push_back(file.string());
64 break;
65 }
66 }
67 }
68 return files;
69}
70
86public:
88 struct Item {
89 uint64_t ts_ns = 0;
90 uint8_t line = 0;
91 const uint8_t *data = nullptr;
92 size_t size = 0;
93 };
94
96 PcapReplaySource(std::string name, std::string root, uint64_t begin_ns, uint64_t end_ns,
97 std::vector<PcapLine> lines, size_t max_queued_batches = 64)
98 : name_(std::move(name))
99 , root_(std::move(root))
100 , begin_ns_(begin_ns)
101 , end_ns_(end_ns)
102 , lines_(std::move(lines))
103 , batches_(static_cast<uint32_t>(std::bit_ceil(std::max<size_t>(max_queued_batches, 1))))
104 {
105 if (end_ns_ < begin_ns_) {
106 throw std::runtime_error(std::format("replay {}: end is before begin", name_));
107 }
108 }
109
111
114
117 void start() {
118 if (thread_.joinable()) {
119 return;
120 }
121 thread_ = std::thread([this] { run(); });
122 }
123
124 void stop() {
125 stopping_.store(true, std::memory_order_relaxed);
126 if (thread_.joinable()) {
127 thread_.join();
128 }
129 }
130
133 [[nodiscard]] bool positioned() const { return positioned_.load(std::memory_order_acquire); }
134
137 [[nodiscard]] bool reader_done() const { return done_.load(std::memory_order_acquire); }
138
142 [[nodiscard]] uint64_t truncated_frames() const { return truncated_frames_.load(std::memory_order_relaxed); }
143
145 [[nodiscard]] std::string error() const {
146 return failed_.load(std::memory_order_acquire) ? error_ : std::string();
147 }
148
150 [[nodiscard]] uint64_t read_ts_ns() const { return read_ts_ns_.load(std::memory_order_relaxed); }
151
154 bool peek(Item &item) {
155 if (cursor_ >= current_.entries.size() && !fetch()) {
156 return false;
157 }
158 const Entry &entry = current_.entries[cursor_];
159 item.ts_ns = entry.ts_ns;
160 item.line = entry.line;
161 item.data = current_.bytes.data() + entry.offset;
162 item.size = entry.size;
163 return true;
164 }
165
167 void pop() {
168 if (cursor_ < current_.entries.size()) {
169 ++cursor_;
170 }
171 }
172
175 [[nodiscard]] bool finished() {
176 if (cursor_ < current_.entries.size()) {
177 return false;
178 }
179 // Everything the reader pushed is visible once it is done, so an empty queue then is the end.
180 return done_.load(std::memory_order_acquire) && !fetch();
181 }
182
183private:
184 struct Entry {
185 uint64_t ts_ns;
186 uint32_t offset;
187 uint32_t size;
188 uint8_t line;
189 };
190 struct Batch {
191 std::vector<uint8_t> bytes;
192 std::vector<Entry> entries;
193 };
194 static constexpr size_t BATCH_PACKETS = 256;
195 static constexpr size_t BATCH_BYTES = 1u << 20;
196
198 struct Stream {
199 PcapLine config;
200 uint32_t addr = 0;
201 std::vector<std::string> files;
202 size_t next_file = 0;
203 std::unique_ptr<PcapReader> reader;
204 bool has_head = false;
205 bool exhausted = false;
206 uint64_t head_ts = 0;
207 std::vector<uint8_t> head;
208 uint64_t last_ts = 0;
209 uint64_t truncated_counted = 0; // of this reader's, already added to truncated_frames_
212 uint64_t overlap_until = 0;
213 };
214
216 bool fetch() {
217 Batch *next = batches_.read();
218 if (!next) {
219 return false;
220 }
221 // Swap, so the slot keeps the spent batch's buffers for the reader to fill again.
222 std::swap(current_, *next);
223 cursor_ = 0;
224 batches_.release(); // the slot is the reader's again
225 return !current_.entries.empty();
226 }
227
236 void trim_files(Stream &s) {
237 if (s.files.size() < 2) {
238 return;
239 }
240 std::vector<std::optional<uint64_t>> starts;
241 for (const auto &file : s.files) {
242 try {
243 PcapReader reader(file);
244 PcapPacket packet;
245 starts.push_back(reader.next(packet) ? std::optional<uint64_t>(packet.ts_ns) : std::nullopt);
246 } catch (const std::exception &) {
247 starts.push_back(std::nullopt);
248 }
249 }
250 std::vector<std::string> kept;
251 for (size_t i = 0; i < s.files.size(); ++i) {
252 const bool covered_by_next = i + 1 < s.files.size() && starts[i + 1] && *starts[i + 1] <= begin_ns_;
253 const bool after_window = starts[i] && *starts[i] > end_ns_;
254 if (!covered_by_next && !after_window) {
255 kept.push_back(std::move(s.files[i]));
256 }
257 }
258 // Everything skipped: leave the newest, so the error (or the lack of packets) is the real one.
259 if (kept.empty()) {
260 kept.push_back(s.files.back());
261 }
262 s.files = std::move(kept);
263 }
264
266 void advance(Stream &s) {
267 s.has_head = false;
268 PcapPacket packet;
269 for (;;) {
270 // Positioning decompresses to `begin`, which can take minutes: let stop() cut it short.
271 if (stopping_.load(std::memory_order_relaxed)) {
272 s.reader.reset();
273 s.exhausted = true;
274 return;
275 }
276 if (!s.reader) {
277 if (s.next_file >= s.files.size()) {
278 s.exhausted = true;
279 return;
280 }
281 s.reader = std::make_unique<PcapReader>(s.files[s.next_file++]);
282 s.truncated_counted = 0;
283 s.overlap_until = s.last_ts;
284 }
285 const bool got = s.reader->next(packet);
286 if (const uint64_t truncated = s.reader->truncated(); truncated != s.truncated_counted) {
287 truncated_frames_.fetch_add(truncated - s.truncated_counted, std::memory_order_relaxed);
288 s.truncated_counted = truncated;
289 }
290 if (!got) {
291 if (!s.reader->error().empty()) {
292 throw std::runtime_error(std::format("{}: {}", s.reader->path(), s.reader->error()));
293 }
294 s.reader.reset();
295 continue;
296 }
297 if (packet.dst_addr != s.addr || packet.dst_port != s.config.port) {
298 continue;
299 }
300 if (packet.ts_ns < begin_ns_ || packet.ts_ns <= s.overlap_until) {
301 continue;
302 }
303 s.overlap_until = 0;
304 if (packet.ts_ns > end_ns_) {
305 s.reader.reset();
306 s.exhausted = true;
307 return;
308 }
309 s.head.assign(packet.data, packet.data + packet.size);
310 s.head_ts = s.last_ts = packet.ts_ns;
311 s.has_head = true;
312 return;
313 }
314 }
315
318 Batch *acquire_batch(uint64_t &index) {
319 while ((index = batches_.try_reserve()) == slick::spsc_queue<Batch>::invalid_index) {
320 if (stopping_.load(std::memory_order_relaxed)) {
321 return nullptr;
322 }
323 std::this_thread::sleep_for(std::chrono::microseconds(200));
324 }
325 Batch *batch = batches_[index];
326 batch->entries.clear();
327 batch->bytes.clear();
328 return batch;
329 }
330
331 void run() {
332 try {
333 std::vector<Stream> streams(lines_.size());
334 for (size_t i = 0; i < lines_.size(); ++i) {
335 streams[i].config = lines_[i];
336 streams[i].addr = parse_ipv4(lines_[i].address);
337 streams[i].files = lines_[i].paths.empty()
338 ? resolve_pcap_files(root_, lines_[i].address, lines_[i].port, begin_ns_, end_ns_)
339 : lines_[i].paths;
340 if (streams[i].files.empty()) {
341 throw std::runtime_error(std::format("replay {}: no capture files for {}:{} in the window",
342 name_, lines_[i].address, lines_[i].port));
343 }
344 }
345 // Skipping to `begin` decompresses everything before it, per line and
346 // independently, so do the lines at once.
347 std::vector<std::exception_ptr> failures(streams.size());
348 std::vector<std::thread> positioning;
349 for (size_t i = 0; i < streams.size(); ++i) {
350 positioning.emplace_back([&, i] {
351 try {
352 trim_files(streams[i]);
353 advance(streams[i]);
354 } catch (...) {
355 failures[i] = std::current_exception();
356 }
357 });
358 }
359 for (auto &t : positioning) {
360 t.join();
361 }
362 for (auto &failure : failures) {
363 if (failure) {
364 std::rethrow_exception(failure);
365 }
366 }
367 positioned_.store(true, std::memory_order_release);
368
369 // Earliest head first. Equal timestamps keep the line order, so A and B copies
370 // of one packet replay together, A first.
371 auto later = [&](size_t a, size_t b) {
372 return streams[a].head_ts != streams[b].head_ts ? streams[a].head_ts > streams[b].head_ts : a > b;
373 };
374 std::priority_queue<size_t, std::vector<size_t>, decltype(later)> heads(later);
375 for (size_t i = 0; i < streams.size(); ++i) {
376 if (streams[i].has_head) {
377 heads.push(i);
378 }
379 }
380 Batch *batch = nullptr; // the ring slot being filled
381 uint64_t slot = 0;
382 while (!heads.empty()) {
383 if (stopping_.load(std::memory_order_relaxed)) {
384 break;
385 }
386 if (!batch && !(batch = acquire_batch(slot))) {
387 break;
388 }
389 const size_t i = heads.top();
390 heads.pop();
391 Stream &s = streams[i];
392 batch->entries.push_back({s.head_ts, static_cast<uint32_t>(batch->bytes.size()),
393 static_cast<uint32_t>(s.head.size()), s.config.line});
394 batch->bytes.insert(batch->bytes.end(), s.head.begin(), s.head.end());
395 read_ts_ns_.store(s.head_ts, std::memory_order_relaxed);
396 advance(s);
397 if (s.has_head) {
398 heads.push(i);
399 }
400 if (batch->entries.size() >= BATCH_PACKETS || batch->bytes.size() >= BATCH_BYTES) {
401 batches_.publish(slot);
402 batch = nullptr;
403 }
404 }
405 if (batch && !batch->entries.empty() && !stopping_.load(std::memory_order_relaxed)) {
406 batches_.publish(slot);
407 }
408 } catch (const std::exception &e) {
409 error_ = e.what();
410 failed_.store(true, std::memory_order_release); // publishes error_, which is never written again
411 }
412 // An error before the files were positioned must not leave a waiter hanging.
413 positioned_.store(true, std::memory_order_release);
414 done_.store(true, std::memory_order_release);
415 }
416
417 std::string name_;
418 std::string root_;
419 uint64_t begin_ns_;
420 uint64_t end_ns_;
421 std::vector<PcapLine> lines_;
422
423 std::thread thread_;
425 slick::spsc_queue<Batch> batches_;
426 std::string error_; // written once by the reader, then failed_ is released
427 std::atomic<bool> failed_{false};
428 std::atomic<uint64_t> truncated_frames_{0};
429 std::atomic<bool> stopping_{false};
430 std::atomic<bool> positioned_{false};
431 std::atomic<bool> done_{false};
432 std::atomic<uint64_t> read_ts_ns_{0};
433
434 // Consumer side.
435 Batch current_;
436 size_t cursor_ = 0;
437};
438
445public:
446 explicit ReplayPacer(double speed = 1.0) : speed_(speed >= 0 && std::isfinite(speed) ? speed : 0) {}
447
448 [[nodiscard]] double speed() const { return speed_; }
449
452 void anchor(uint64_t capture_ns, uint64_t wall_ns) {
453 anchor_capture_ns_ = capture_ns;
454 anchor_wall_ns_ = wall_ns;
455 anchored_ = true;
456 }
457
458 [[nodiscard]] bool anchored() const { return anchored_; }
459
461 [[nodiscard]] uint64_t due_ns(uint64_t capture_ns) const {
462 if (speed_ == 0 || capture_ns <= anchor_capture_ns_) {
463 return anchor_wall_ns_;
464 }
465 return anchor_wall_ns_ + static_cast<uint64_t>(static_cast<double>(capture_ns - anchor_capture_ns_) / speed_);
466 }
467
469 [[nodiscard]] bool is_due(uint64_t capture_ns, uint64_t now_ns) const {
470 return speed_ == 0 || now_ns >= due_ns(capture_ns);
471 }
472
476 [[nodiscard]] uint64_t rebase_ns(uint64_t capture_ns, uint64_t now_ns) const {
477 if (speed_ == 0) {
478 return now_ns;
479 }
480 return std::min(due_ns(capture_ns), now_ns);
481 }
482
483private:
484 double speed_;
485 uint64_t anchor_capture_ns_ = 0;
486 uint64_t anchor_wall_ns_ = 0;
487 bool anchored_ = false;
488};
489
490} // namespace slick::sim::md_feed
bool reader_done() const
True when the reader has nothing more to add: the window is read out, or it failed (see error()).
std::string error() const
What stopped the reader, empty when nothing did. Any thread.
PcapReplaySource & operator=(const PcapReplaySource &)=delete
bool positioned() const
True once every line has been read up to begin_ns and holds a first packet (or has none),...
uint64_t read_ts_ns() const
Capture time of the last packet the reader has merged, nanoseconds. Any thread.
uint64_t truncated_frames() const
Frames the reader skipped for being cut short or malformed (not the IGMP, ARP and other non-UDP traff...
bool peek(Item &item)
The next packet, without consuming it.
bool finished()
True when every packet has been consumed and the reader will add none.
void pop()
Consumes the packet peek() returned. Consumer thread.
PcapReplaySource(std::string name, std::string root, uint64_t begin_ns, uint64_t end_ns, std::vector< PcapLine > lines, size_t max_queued_batches=64)
root is only used for lines without explicit paths.
PcapReplaySource(const PcapReplaySource &)=delete
void anchor(uint64_t capture_ns, uint64_t wall_ns)
Pins the capture time capture_ns to the wall time wall_ns.
uint64_t due_ns(uint64_t capture_ns) const
The wall time at which a packet captured at capture_ns should go out.
bool is_due(uint64_t capture_ns, uint64_t now_ns) const
True when the packet may go out at wall time now_ns.
uint64_t rebase_ns(uint64_t capture_ns, uint64_t now_ns) const
The time to stamp on a packet's events when it goes out at now_ns: its due time, so the replay keeps ...
std::vector< std::string > resolve_pcap_files(const std::string &root, const std::string &address, uint16_t port, uint64_t begin_ns, uint64_t end_ns)
The capture files of group address:port that can hold packets in [begin_ns, end_ns].
uint32_t parse_ipv4(const std::string &text)
Packs a dotted quad such as "224.0.31.1" into host byte order, the form PcapPacket::dst_addr uses.
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().