Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
multicast_packet_feed.hpp
Go to the documentation of this file.
1#pragma once
2
3// Before anything below can pull in windows.h (slick-socket does, through winsock2.h),
4// or its min/max macros are already defined.
5#if defined(_WIN32) && !defined(NOMINMAX)
6#define NOMINMAX
7#endif
8
9#include <nlohmann/json.hpp>
10#include <slick/logger.hpp>
11#include <slick/queue.hpp>
12#include <slick/socket/polled_multicast_receiver.h>
13#include <array>
14#include <atomic>
15#include <chrono>
16#include <cassert>
17#include <cerrno>
18#include <cstdint>
19#include <cstring>
20#include <format>
21#include <memory>
22#include <stdexcept>
23#include <string>
24#include <thread>
25#include <utility>
26#include <vector>
27
28#if defined(__linux__)
29#include <pthread.h>
30#include <sched.h>
31#elif defined(_WIN32)
32#include <windows.h>
33#endif
34
35namespace slick::sim::md_feed {
36
43struct packet_feed_traits : slick::queue_traits {
44 static constexpr bool enable_loss_detection = true;
45};
46
81public:
82 static constexpr uint8_t MAX_LINES = 32;
84 static constexpr uint64_t MEMBERSHIP_RETRY_NS = 100'000'000;
86 static constexpr size_t MAX_DATAGRAM = 1u << 16;
87 static constexpr std::chrono::microseconds RECEIVER_IDLE_SLEEP{50};
88
89 MulticastPacketFeed(std::string name, const nlohmann::json &config)
90 : name_(std::move(name))
91 , config_(config)
92 , packets_(config.value("queue_size", 1u << 24))
93 , cursor_(packets_.initial_reading_index())
94 , max_packets_per_poll_(config.value("max_packets_per_poll", 256u))
95 , receiver_cpu_(config.value("receiver_cpu", -1))
96 {
97 // drain() would otherwise hand over nothing, for ever, and the feed would sit
98 // silent with every packet queued behind it. It is config, so check in every build.
99 if (max_packets_per_poll_ == 0) {
100 throw std::runtime_error(std::format("feed {}: max_packets_per_poll must be above 0", name_));
101 }
102 }
103
104 virtual ~MulticastPacketFeed() { stop(); }
105
108
110 [[nodiscard]] bool has_group(const char *key) const { return config_.contains(key); }
111
114 bool add_line(const char *key, uint8_t line) {
115 // The receiver thread walks lines_, so a line added under it would be a data race.
116 if (started_ || !config_.contains(key) || line >= MAX_LINES) {
117 return false;
118 }
119 const auto &group = config_[key];
120 slick::socket::PolledMulticastReceiverConfig receiver;
121 receiver.multicast_address = group.at("address").get<std::string>();
122 receiver.port = group.at("port").get<uint16_t>();
123 receiver.interface_address = config_.value("interface", receiver.interface_address);
124 receiver.receive_buffer_size = config_.value("receive_buffer_size", 1 << 26);
125 if (receivers_[line]) {
126 return false; // the line is taken
127 }
128 receivers_[line] = std::make_unique<slick::socket::PolledMulticastReceiver>(
129 std::format("{} {}", name_, key), receiver);
130 lines_.push_back(line);
131 return true;
132 }
133
134 void start() {
135 if (thread_.joinable()) {
136 LOG_WARN("feed {}: already started", name_); // as slick-socket's own receivers do
137 return;
138 }
139 started_ = true;
140 for (const uint8_t line : lines_) {
141 if (!receivers_[line]->open()) {
142 LOG_ERROR("feed {}: a multicast receiver failed to start", name_);
143 }
144 }
145 // Starting joined every group. A line the venue still wants left stays
146 // muted, and its next set_joined() leaves the group again.
147 left_ = 0;
148 failing_ = 0;
149 retry_at_ns_.fill(0);
150 for (auto &request : request_) {
151 request.store(NO_REQUEST, std::memory_order_relaxed);
152 }
153 pending_op_.fill(NO_REQUEST);
154 if (!lines_.empty()) {
155 running_.store(true, std::memory_order_release);
156 thread_ = std::thread([this] { receive_loop(); });
157 }
158 }
159
160 void stop() {
161 running_.store(false, std::memory_order_release);
162 if (thread_.joinable()) {
163 thread_.join();
164 }
165 for (const uint8_t line : lines_) {
166 receivers_[line]->close();
167 }
168 started_ = false;
169 }
170
178 bool deliver(uint8_t line, const uint8_t *data, size_t size) {
179 assert(line < MAX_LINES);
180 if (muted_.load(std::memory_order_relaxed) & (1u << line)) {
181 return false;
182 }
183 const auto n = static_cast<uint32_t>(size + 1);
184 if (n > packets_.size()) [[unlikely]] {
185 // A queue too small for one packet is too small for all of them: log the
186 // first, count the rest, rather than flood the log at the feed's rate.
187 if (oversized_.fetch_add(1, std::memory_order_relaxed) == 0) {
188 LOG_ERROR("feed {}: line {} packet of {} bytes exceeds the {} byte queue; dropping it and any like it",
189 name_, line, size, packets_.size());
190 }
191 return false;
192 }
193 const uint64_t index = packets_.reserve(n);
194 uint8_t *entry = packets_[index];
195 entry[0] = line;
196 std::memcpy(entry + 1, data, size);
197 packets_.publish(index, n);
198 return true;
199 }
200
202 void mute(uint8_t line, bool muted) noexcept {
203 assert(line < MAX_LINES);
204 const uint32_t bit = 1u << line;
205 if (muted) {
206 muted_.fetch_or(bit, std::memory_order_relaxed);
207 } else {
208 muted_.fetch_and(~bit, std::memory_order_relaxed);
209 }
210 }
211
222 void set_joined(uint8_t line, bool joined, uint64_t now_ns) {
223 assert(line < MAX_LINES);
224 const uint32_t bit = 1u << line;
225 const uint32_t want_left = joined ? 0 : bit;
226 if ((wanted_left_ & bit) != want_left) {
227 wanted_left_ ^= bit;
228 // Mute before leaving and unmute before joining, so nothing that arrives
229 // while joined is dropped.
230 mute(line, !joined);
231 failing_ &= ~bit;
232 retry_at_ns_[line] = 0;
233 }
234 // A change still in flight has to be followed up even when the socket already is
235 // as wanted: it may be the opposite one, to be withdrawn or its answer collected.
236 if (((left_ & bit) == want_left && pending_op_[line] == NO_REQUEST) || now_ns < retry_at_ns_[line]) {
237 return;
238 }
239 const int error = change_membership(line, joined);
240 if (error == MEMBERSHIP_PENDING) {
241 return; // the receiver thread has not answered yet; ask again next poll
242 }
243 if (error != 0) {
244 retry_at_ns_[line] = now_ns + MEMBERSHIP_RETRY_NS;
245 if (!(failing_ & bit)) {
246 failing_ |= bit;
247 LOG_ERROR("feed {}: line {} could not {} its group, error {}; retrying every {} ms", name_, line,
248 joined ? "rejoin" : "leave", error, MEMBERSHIP_RETRY_NS / 1'000'000);
249 }
250 return;
251 }
252 left_ = (left_ & ~bit) | want_left;
253 failing_ &= ~bit;
254 }
255
260 template <typename OnPacket>
261 uint32_t drain(OnPacket &&on_packet) {
262 uint32_t handled = 0;
263 for (; handled < max_packets_per_poll_; ++handled) {
264 auto [entry, size] = packets_.read(cursor_);
265 if (!entry) {
266 break;
267 }
268 if (size < 1) {
269 continue;
270 }
271 on_packet(entry[0], entry + 1, static_cast<size_t>(size - 1));
272 }
273 return handled;
274 }
275
276 [[nodiscard]] const std::string &name() const noexcept { return name_; }
277
281 [[nodiscard]] uint64_t loss_count() const noexcept { return packets_.loss_count(); }
282
285 [[nodiscard]] uint64_t receive_error_count() const noexcept {
286 return receive_errors_.load(std::memory_order_relaxed);
287 }
288
290 [[nodiscard]] uint64_t oversized_count() const noexcept { return oversized_.load(std::memory_order_relaxed); }
291
292protected:
294 static constexpr int MEMBERSHIP_PENDING = -1;
295
308 virtual int change_membership(uint8_t line, bool join) {
309 if (!receivers_[line] || !running_.load(std::memory_order_acquire)) {
310 return 0; // no thread running: nothing is open that could be changed
311 }
312 auto &request = request_[line];
313 uint8_t &pending = pending_op_[line]; // what this thread last handed over; NO_REQUEST for none
314 const uint8_t op = join ? REQUEST_JOIN : REQUEST_LEAVE;
315 for (;;) {
316 if (pending == NO_REQUEST) {
317 pending = op;
318 request.store(op, std::memory_order_release);
319 return MEMBERSHIP_PENDING;
320 }
321 const uint8_t state = request.load(std::memory_order_acquire);
322 if (state == REQUEST_DONE || state == REQUEST_FAILED) {
323 request.store(NO_REQUEST, std::memory_order_relaxed);
324 const uint8_t handed = std::exchange(pending, NO_REQUEST);
325 // The socket has changed as it was handed, whatever is wanted now: record it
326 // here, or a failed change after this one would be retried from a stale state.
327 if (state == REQUEST_DONE) {
328 const uint32_t bit = 1u << line;
329 left_ = handed == REQUEST_LEAVE ? (left_ | bit) : (left_ & ~bit);
330 }
331 if (handed == op) {
332 return state == REQUEST_DONE ? 0 : EIO;
333 }
334 continue; // the answer to the opposite change: now hand over the wanted one
335 }
336 if (state == pending && pending != op) {
337 uint8_t untouched = pending;
338 if (request.compare_exchange_strong(untouched, NO_REQUEST, std::memory_order_acq_rel)) {
339 // Never made, so the socket is still as it was before it: as `op` asks.
340 pending = NO_REQUEST;
341 return 0;
342 }
343 // The thread took it between the read and the withdrawal: wait for it.
344 }
345 return MEMBERSHIP_PENDING;
346 }
347 }
348
349private:
350 friend struct MulticastPacketFeedTestAccess; // lets a test stall the receiver thread
351
352 static constexpr uint8_t NO_REQUEST = 0;
353 static constexpr uint8_t REQUEST_JOIN = 1;
354 static constexpr uint8_t REQUEST_LEAVE = 2;
355 static constexpr uint8_t REQUEST_BUSY = 3;
356 static constexpr uint8_t REQUEST_DONE = 4;
357 static constexpr uint8_t REQUEST_FAILED = 5;
359 static constexpr uint64_t RECEIVE_ERROR_LOG_NS = 1'000'000'000;
360
363 static bool pin_current_thread(int cpu, const std::string &name) {
364 if (cpu < 0) {
365 return false;
366 }
367 bool ok = false;
368#if defined(__linux__)
369 cpu_set_t set;
370 CPU_ZERO(&set);
371 if (cpu < CPU_SETSIZE) {
372 CPU_SET(cpu, &set);
373 ok = pthread_setaffinity_np(pthread_self(), sizeof(set), &set) == 0;
374 }
375#elif defined(_WIN32)
376 ok = cpu < 64 && SetThreadAffinityMask(GetCurrentThread(), DWORD_PTR{1} << cpu) != 0;
377#endif
378 if (ok) {
379 LOG_INFO("feed {}: receiver thread pinned to CPU core {}", name, cpu);
380 } else {
381 LOG_WARN("feed {}: could not pin the receiver thread to CPU core {}; it will sleep between sweeps", name,
382 cpu);
383 }
384 return ok;
385 }
386
389 void receive_loop() {
390 // Spin only on a core this thread owns: a failed pin leaves it sharing one.
391 const bool spin = pin_current_thread(receiver_cpu_, name_);
392 std::vector<uint8_t> buffer(MAX_DATAGRAM);
393 std::array<uint64_t, MAX_LINES> next_error_log_ns{};
394 constexpr int MAX_BURST = 64; // per line per sweep, so one hot line cannot starve the rest
395 while (running_.load(std::memory_order_acquire)) {
396 bool idle = true;
397 for (const uint8_t line : lines_) {
398 auto &receiver = *receivers_[line];
399 auto &request = request_[line];
400 // Taking the request with a compare-exchange lets change_membership()
401 // withdraw one this thread has not reached, so only one of them wins.
402 if (uint8_t op = request.load(std::memory_order_acquire);
403 (op == REQUEST_JOIN || op == REQUEST_LEAVE) &&
404 request.compare_exchange_strong(op, REQUEST_BUSY, std::memory_order_acq_rel)) {
405 bool ok = true;
406 if (op == REQUEST_JOIN) {
407 ok = receiver.open();
408 } else {
409 receiver.close();
410 }
411 request.store(ok ? REQUEST_DONE : REQUEST_FAILED, std::memory_order_release);
412 }
413 if (!receiver.is_open()) {
414 continue;
415 }
416 for (int i = 0; i < MAX_BURST; ++i) {
417 const auto n = receiver.receive(buffer);
418 if (n < 0) {
419 // A failing socket looks like a quiet feed otherwise. slick-socket
420 // counts the errors but does not say which; it keeps the socket open.
421 const uint64_t total = receive_errors_.fetch_add(1, std::memory_order_relaxed) + 1;
422 const auto now = static_cast<uint64_t>(
423 std::chrono::duration_cast<std::chrono::nanoseconds>(
424 std::chrono::steady_clock::now().time_since_epoch()).count());
425 if (now >= next_error_log_ns[line]) {
426 next_error_log_ns[line] = now + RECEIVE_ERROR_LOG_NS;
427 LOG_ERROR("feed {}: line {} failed to receive ({} read errors so far on the feed)", name_,
428 line, total);
429 }
430 break;
431 }
432 if (n == 0) {
433 break;
434 }
435 idle = false;
436 deliver(line, buffer.data(), static_cast<size_t>(n));
437 }
438 }
439 if (idle && !spin) {
440 std::this_thread::sleep_for(RECEIVER_IDLE_SLEEP);
441 }
442 }
443 }
444
445 std::string name_;
446 nlohmann::json config_;
448 slick::queue<uint8_t, packet_feed_traits> packets_;
449 uint64_t cursor_;
450 uint32_t max_packets_per_poll_;
451 int receiver_cpu_;
452 std::atomic<uint32_t> muted_{0};
453 std::atomic<uint64_t> oversized_{0};
454 std::atomic<uint64_t> receive_errors_{0};
455 // set_joined()'s state, exchange thread only. Bitmasks by line: the lines the
456 // venue wants left, the lines whose group the socket has left (set only once the
457 // call succeeded), and the lines whose last attempt failed, so a failure is
458 // logged once per streak. Then when each line may try again.
459 uint32_t wanted_left_ = 0;
460 uint32_t left_ = 0;
461 uint32_t failing_ = 0;
462 std::array<uint64_t, MAX_LINES> retry_at_ns_{};
464 bool started_ = false;
465 std::atomic<bool> running_{false};
466 std::thread thread_;
469 std::array<std::unique_ptr<slick::socket::PolledMulticastReceiver>, MAX_LINES> receivers_{};
470 std::vector<uint8_t> lines_;
473 std::array<std::atomic<uint8_t>, MAX_LINES> request_{};
475 std::array<uint8_t, MAX_LINES> pending_op_{};
476};
477
478} // namespace slick::sim::md_feed
static constexpr uint64_t MEMBERSHIP_RETRY_NS
How long a failed join or leave waits before set_joined() tries it again.
void mute(uint8_t line, bool muted) noexcept
Drops line's packets on arrival while muted. Any thread.
uint64_t receive_error_count() const noexcept
Reads a socket reported as failed, across every line.
uint64_t oversized_count() const noexcept
Packets refused for being larger than the queue. Only the first is logged.
MulticastPacketFeed & operator=(const MulticastPacketFeed &)=delete
uint32_t drain(OnPacket &&on_packet)
Exchange thread.
virtual int change_membership(uint8_t line, bool join)
Joins or leaves line's group.
MulticastPacketFeed(const MulticastPacketFeed &)=delete
bool has_group(const char *key) const
True when the config names a group for key.
uint64_t loss_count() const noexcept
Queue bytes a receiver overwrote before this thread drained them, each lost packet counting its size ...
static constexpr int MEMBERSHIP_PENDING
What change_membership() returns while the receiver thread has not yet answered.
bool add_line(const char *key, uint8_t line)
Joins the group under key, if the config names one, as line.
void set_joined(uint8_t line, bool joined, uint64_t now_ns)
Exchange thread, from poll().
MulticastPacketFeed(std::string name, const nlohmann::json &config)
bool deliver(uint8_t line, const uint8_t *data, size_t size)
Queues a packet as if line's receiver had received it.
const std::string & name() const noexcept
static constexpr size_t MAX_DATAGRAM
The receiver thread's read buffer: above any UDP payload a venue sends.
static constexpr std::chrono::microseconds RECEIVER_IDLE_SLEEP
Counts the queue bytes a receiver overwrote before the exchange thread drained them.