90 : name_(std::move(
name))
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))
99 if (max_packets_per_poll_ == 0) {
100 throw std::runtime_error(std::format(
"feed {}: max_packets_per_poll must be above 0", name_));
110 [[nodiscard]]
bool has_group(
const char *key)
const {
return config_.contains(key); }
116 if (started_ || !config_.contains(key) || line >=
MAX_LINES) {
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]) {
128 receivers_[line] = std::make_unique<slick::socket::PolledMulticastReceiver>(
129 std::format(
"{} {}", name_, key), receiver);
130 lines_.push_back(line);
135 if (thread_.joinable()) {
136 LOG_WARN(
"feed {}: already started", name_);
140 for (
const uint8_t line : lines_) {
141 if (!receivers_[line]->open()) {
142 LOG_ERROR(
"feed {}: a multicast receiver failed to start", name_);
149 retry_at_ns_.fill(0);
150 for (
auto &request : request_) {
151 request.store(NO_REQUEST, std::memory_order_relaxed);
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(); });
161 running_.store(
false, std::memory_order_release);
162 if (thread_.joinable()) {
165 for (
const uint8_t line : lines_) {
166 receivers_[line]->close();
178 bool deliver(uint8_t line,
const uint8_t *data,
size_t size) {
180 if (muted_.load(std::memory_order_relaxed) & (1u << line)) {
183 const auto n =
static_cast<uint32_t
>(size + 1);
184 if (n > packets_.size()) [[unlikely]] {
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());
193 const uint64_t index = packets_.reserve(n);
194 uint8_t *entry = packets_[index];
196 std::memcpy(entry + 1, data, size);
197 packets_.publish(index, n);
202 void mute(uint8_t line,
bool muted)
noexcept {
204 const uint32_t bit = 1u << line;
206 muted_.fetch_or(bit, std::memory_order_relaxed);
208 muted_.fetch_and(~bit, std::memory_order_relaxed);
222 void set_joined(uint8_t line,
bool joined, uint64_t now_ns) {
224 const uint32_t bit = 1u << line;
225 const uint32_t want_left = joined ? 0 : bit;
226 if ((wanted_left_ & bit) != want_left) {
232 retry_at_ns_[line] = 0;
236 if (((left_ & bit) == want_left && pending_op_[line] == NO_REQUEST) || now_ns < retry_at_ns_[line]) {
245 if (!(failing_ & bit)) {
247 LOG_ERROR(
"feed {}: line {} could not {} its group, error {}; retrying every {} ms", name_, line,
252 left_ = (left_ & ~bit) | want_left;
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_);
271 on_packet(entry[0], entry + 1,
static_cast<size_t>(size - 1));
276 [[nodiscard]]
const std::string &
name() const noexcept {
return name_; }
281 [[nodiscard]] uint64_t
loss_count() const noexcept {
return packets_.loss_count(); }
286 return receive_errors_.load(std::memory_order_relaxed);
290 [[nodiscard]] uint64_t
oversized_count() const noexcept {
return oversized_.load(std::memory_order_relaxed); }
309 if (!receivers_[line] || !running_.load(std::memory_order_acquire)) {
312 auto &request = request_[line];
313 uint8_t &pending = pending_op_[line];
314 const uint8_t op = join ? REQUEST_JOIN : REQUEST_LEAVE;
316 if (pending == NO_REQUEST) {
318 request.store(op, std::memory_order_release);
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);
327 if (state == REQUEST_DONE) {
328 const uint32_t bit = 1u << line;
329 left_ = handed == REQUEST_LEAVE ? (left_ | bit) : (left_ & ~bit);
332 return state == REQUEST_DONE ? 0 : EIO;
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)) {
340 pending = NO_REQUEST;
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;
363 static bool pin_current_thread(
int cpu,
const std::string &
name) {
368#if defined(__linux__)
371 if (cpu < CPU_SETSIZE) {
373 ok = pthread_setaffinity_np(pthread_self(),
sizeof(set), &set) == 0;
376 ok = cpu < 64 && SetThreadAffinityMask(GetCurrentThread(), DWORD_PTR{1} << cpu) != 0;
379 LOG_INFO(
"feed {}: receiver thread pinned to CPU core {}",
name, cpu);
381 LOG_WARN(
"feed {}: could not pin the receiver thread to CPU core {}; it will sleep between sweeps",
name,
389 void receive_loop() {
391 const bool spin = pin_current_thread(receiver_cpu_, name_);
393 std::array<uint64_t, MAX_LINES> next_error_log_ns{};
394 constexpr int MAX_BURST = 64;
395 while (running_.load(std::memory_order_acquire)) {
397 for (
const uint8_t line : lines_) {
398 auto &receiver = *receivers_[line];
399 auto &request = request_[line];
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)) {
406 if (op == REQUEST_JOIN) {
407 ok = receiver.open();
411 request.store(ok ? REQUEST_DONE : REQUEST_FAILED, std::memory_order_release);
413 if (!receiver.is_open()) {
416 for (
int i = 0; i < MAX_BURST; ++i) {
417 const auto n = receiver.receive(buffer);
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_,
436 deliver(line, buffer.data(),
static_cast<size_t>(n));
446 nlohmann::json config_;
448 slick::queue<uint8_t, packet_feed_traits> packets_;
450 uint32_t max_packets_per_poll_;
452 std::atomic<uint32_t> muted_{0};
453 std::atomic<uint64_t> oversized_{0};
454 std::atomic<uint64_t> receive_errors_{0};
459 uint32_t wanted_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};
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_{};