MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
EventRingBuffer.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
7
8#pragma once
9
10#include <cstring>
11#include <algorithm>
12#include <atomic>
13#include <limits>
14#include <stdexcept>
15#include <type_traits>
16#include "Flow.hpp"
17
18namespace mxl::lib
19{
22 {
23 std::uint32_t version;
24 std::uint32_t size;
25 std::uint32_t eventCount;
26 std::uint32_t payloadSize;
27 std::uint8_t reserved[4096 - 16];
28 };
29
30 static_assert(sizeof(EventRingHeader) == 4096);
31 static_assert(std::has_unique_object_representations_v<EventRingHeader>);
32 static_assert(std::atomic_ref<std::uint64_t>::is_always_lock_free);
33 static_assert(std::atomic_ref<std::uint32_t>::is_always_lock_free);
34 static_assert(std::atomic_ref<std::uint64_t>::required_alignment <= alignof(std::uint64_t));
35
48 {
49 public:
50 constexpr static auto STORAGE_VERSION = std::uint32_t{1};
51 constexpr static auto EMPTY = std::numeric_limits<std::uint64_t>::max();
52 constexpr static auto MAX_INDEX = (EMPTY >> 1) - 1;
53
62
68 constexpr static std::size_t slotStride(std::uint32_t payloadSize) noexcept
69 {
70 constexpr auto alignment = std::size_t{128};
71 return (sizeof(Event) + payloadSize + alignment - 1) & ~(alignment - 1U);
72 }
73
81 static std::size_t bufferSize(std::uint32_t count, std::uint32_t payloadSize)
82 {
83 validateGeometry(count, payloadSize);
84 return sizeof(EventRingHeader) + (slotStride(payloadSize) * count);
85 }
86
95 static void initialize(void* memory, std::uint32_t count, std::uint32_t payloadSize);
96
105 EventRingBuffer(void* memory, std::uint32_t count, std::uint32_t payloadSize)
106 : _header{static_cast<EventRingHeader*>(memory)}
107 , _count{count}
108 , _payloadSize{payloadSize}
109 , _stride{slotStride(payloadSize)}
110 {
111 validateGeometry(count, payloadSize);
112 if ((_header->version != STORAGE_VERSION) || (_header->size != sizeof *_header) || (_header->eventCount != count) ||
113 (_header->payloadSize != payloadSize))
114 {
115 throw std::invalid_argument{"Invalid event ring header."};
116 }
117 // Only immutable fields may be inspected while another process publishes.
118 for (auto i = std::size_t{0}; i < count; ++i)
119 {
120 auto const& header = slot(i).header;
121 if ((header.version != STORAGE_VERSION) || (header.size != sizeof header))
122 {
123 throw std::invalid_argument{"Invalid event slot header."};
124 }
125 }
126 }
127
139 mxlStatus publish(std::uint64_t index, mxlEventInfo const& info, std::uint8_t const* payload) noexcept
140 {
141 if (index > MAX_INDEX)
142 {
144 }
145 auto& event = slot(index);
146 auto sequence = std::atomic_ref{event.header.sequence};
147 auto const previous = sequence.load(std::memory_order_relaxed);
148 if ((previous != EMPTY) && (previous != (index << 1)) && ((previous >> 1) >= index))
149 {
150 // An unpublished writing tag for this index is safe to retry after a crash.
151 // A completed tag must never be reused: readers may already have observed it.
153 }
154 sequence.store(index << 1, std::memory_order_release);
155 storeBytes(event.header.infoWords, &info, sizeof info);
156 storeBytes(payloadWords(event), payload, info.eventSize);
157 sequence.store((index << 1) | 1, std::memory_order_release);
158 return MXL_STATUS_OK;
159 }
160
169 ReadResult read(std::uint64_t index, mxlEventInfo& info, std::uint8_t* payload) const noexcept
170 {
171 if (index > MAX_INDEX)
172 {
173 return ReadResult::Pending;
174 }
175 auto& event = slot(index);
176 auto const expected = (index << 1) | 1;
177 auto const before = load(event.header.sequence);
178 if (before != expected)
179 {
180 return (before != EMPTY) && ((before >> 1) > index) ? ReadResult::Overwritten : ReadResult::Pending;
181 }
182 loadBytes(&info, event.header.infoWords, sizeof info);
183 // Metadata may be an inconsistent snapshot until the final sequence check.
184 if (info.eventSize <= _payloadSize)
185 {
186 loadBytes(payload, payloadWords(event), info.eventSize);
187 }
188 if (load(event.header.sequence) != before)
189 {
191 }
192 if ((info.version != EVENT_HEADER_VERSION) || (info.size != sizeof info) || (info.flags != 0) || (info.eventSize > _payloadSize))
193 {
194 return ReadResult::Invalid;
195 }
196 info.index = index; // Queue position is library-owned, not producer metadata.
197 return ReadResult::Ready;
198 }
199
205 static std::uint64_t load(std::uint64_t const& value) noexcept
206 {
207 // libc++ versions used by MXL do not support atomic_ref<const T>.
208 // This performs loads only, including on read-only IPC mappings.
209 return std::atomic_ref{const_cast<std::uint64_t&>(value)}.load(std::memory_order_acquire);
210 }
211
212 private:
217 static void validateGeometry(std::uint32_t count, std::uint32_t payloadSize)
218 {
219 if ((count < 2) || (count > 65536) || (payloadSize == 0) || (payloadSize > 1048576) ||
220 (slotStride(payloadSize) > (std::numeric_limits<std::size_t>::max() - sizeof(EventRingHeader)) / count))
221 {
222 throw std::invalid_argument{"Invalid event buffer dimensions."};
223 }
224 }
225
231 Event& slot(std::uint64_t index) const noexcept
232 {
233 return *reinterpret_cast<Event*>(reinterpret_cast<std::uint8_t*>(_header) + sizeof(EventRingHeader) + ((index % _count) * _stride));
234 }
235
241 static std::uint64_t* payloadWords(Event& event) noexcept
242 {
243 return reinterpret_cast<std::uint64_t*>(reinterpret_cast<std::uint8_t*>(&event) + sizeof(Event));
244 }
245
252 static void storeBytes(std::uint64_t* destination, void const* source, std::size_t size) noexcept
253 {
254 auto const bytes = static_cast<std::uint8_t const*>(source);
255 for (auto offset = std::size_t{0}; offset < size; offset += sizeof *destination)
256 {
257 auto word = std::uint64_t{};
258 std::memcpy(&word, bytes + offset, std::min(sizeof word, size - offset));
259 // If a reader observes any new word, this release/acquire pair
260 // forces its final sequence load to observe the writing tag or later.
261 std::atomic_ref{destination[offset / sizeof word]}.store(word, std::memory_order_release);
262 }
263 }
264
271 static void loadBytes(void* destination, std::uint64_t const* source, std::size_t size) noexcept
272 {
273 auto bytes = static_cast<std::uint8_t*>(destination);
274 for (auto offset = std::size_t{0}; offset < size; offset += sizeof *source)
275 {
276 auto const word = load(source[offset / sizeof(std::uint64_t)]);
277 std::memcpy(bytes + offset, &word, std::min(sizeof word, size - offset));
278 }
279 }
280
281 private:
283 std::uint32_t _count;
284 std::uint32_t _payloadSize;
285 std::size_t _stride;
286 };
287}
Internal shared-memory headers for discrete grains and event slots.
static void initialize(void *memory, std::uint32_t count, std::uint32_t payloadSize)
Construct headers, empty sequence tags and payload words in a fresh mapping.
EventRingBuffer(void *memory, std::uint32_t count, std::uint32_t payloadSize)
Attach a view and validate immutable headers across all slots.
EventRingHeader * _header
Borrowed address of the mapping's immutable ring header.
static constexpr auto EMPTY
Tag identifying a slot with no publication.
std::size_t _stride
Aligned distance in bytes between slot headers.
static std::uint64_t * payloadWords(Event &event) noexcept
Locate the atomic payload words immediately after an event slot header.
ReadResult read(std::uint64_t index, mxlEventInfo &info, std::uint8_t *payload) const noexcept
Copy one entry with sequence validation before and after the copy.
static void validateGeometry(std::uint32_t count, std::uint32_t payloadSize)
Validate slot count, payload capacity and mapping-size limits.
static constexpr std::size_t slotStride(std::uint32_t payloadSize) noexcept
Compute the physical stride between adjacent slots.
static std::size_t bufferSize(std::uint32_t count, std::uint32_t payloadSize)
Validate geometry and compute the complete mapping length.
mxlStatus publish(std::uint64_t index, mxlEventInfo const &info, std::uint8_t const *payload) noexcept
Atomically publish metadata and payload under a new sequence tag.
static constexpr auto MAX_INDEX
Largest index whose complete tag does not collide with EMPTY.
static void loadBytes(void *destination, std::uint64_t const *source, std::size_t size) noexcept
Copy shared words into private bytes using acquire loads.
ReadResult
Outcome of a bounded attempt to copy an entry without waiting.
@ Overwritten
The slot advanced past this index or changed while being copied.
@ Pending
The requested entry is not yet published or its index is unrepresentable.
@ Invalid
A stable snapshot contains unsupported or invalid metadata.
@ Ready
Metadata and payload form a validated snapshot of the requested entry.
std::uint32_t _count
Validated physical slot count.
std::uint32_t _payloadSize
Validated per-entry payload capacity in bytes.
static void storeBytes(std::uint64_t *destination, void const *source, std::size_t size) noexcept
Copy private bytes to shared words using release stores.
static constexpr auto STORAGE_VERSION
Version used by immutable ring and slot headers.
Event & slot(std::uint64_t index) const noexcept
Resolve a logical queue index to a physical slot modulo capacity.
static std::uint64_t load(std::uint64_t const &value) noexcept
Load a shared 64-bit word with acquire ordering, including from a read-only mapping.
struct mxlEventInfo_t mxlEventInfo
Metadata for one event queue entry, either a complete event or a fragment.
mxlStatus
MXL SDK Status codes.
Definition mxl.h:22
@ MXL_ERR_FLOW_INVALID
Definition mxl.h:41
@ MXL_STATUS_OK
Definition mxl.h:23
@ MXL_ERR_OUT_OF_RANGE_TOO_LATE
Definition mxl.h:30
constexpr auto EVENT_HEADER_VERSION
Version stored in the public mxlEventInfo metadata of every published entry.
Definition Flow.hpp:61
std::size_t size() const noexcept
Returns the total number of writers that are registered in the DomainWatcher.
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
Immutable 4 KiB geometry header at the start of the single event ring file.
std::uint32_t version
Storage version checked when the ring is opened.
std::uint8_t reserved[4096 - 16]
Zero-initialized padding to 4096 bytes.
std::uint32_t eventCount
Number of physical slots; every slot may retain an entry.
std::uint32_t size
Size of this header in bytes.
std::uint32_t payloadSize
Maximum payload bytes stored in one slot.
Fixed part of an event slot; its payload follows immediately in the mapping.
Definition Flow.hpp:90
EventHeader header
Sequence, layout and metadata fields for this slot.
Definition Flow.hpp:91
uint64_t index