MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
mxl::lib::EventRingBuffer Class Reference

Non-owning single-producer event ring view safe for concurrent snapshot readers. More...

#include <EventRingBuffer.hpp>

Collaboration diagram for mxl::lib::EventRingBuffer:

Public Types

enum class  ReadResult { Ready , Pending , Overwritten , Invalid }
 Outcome of a bounded attempt to copy an entry without waiting. More...

Public Member Functions

 EventRingBuffer (void *memory, std::uint32_t count, std::uint32_t payloadSize)
 Attach a view and validate immutable headers across all slots.
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.
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 Public Member Functions

static std::size_t bufferSize (std::uint32_t count, std::uint32_t payloadSize)
 Validate geometry and compute the complete mapping length.
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.
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.
static constexpr std::size_t slotStride (std::uint32_t payloadSize) noexcept
 Compute the physical stride between adjacent slots.

Static Public Attributes

static constexpr auto EMPTY = std::numeric_limits<std::uint64_t>::max()
 Tag identifying a slot with no publication.
static constexpr auto MAX_INDEX = (EMPTY >> 1) - 1
 Largest index whose complete tag does not collide with EMPTY.
static constexpr auto STORAGE_VERSION = std::uint32_t{1}
 Version used by immutable ring and slot headers.

Private Member Functions

Event & slot (std::uint64_t index) const noexcept
 Resolve a logical queue index to a physical slot modulo capacity.

Static Private Member Functions

static void loadBytes (void *destination, std::uint64_t const *source, std::size_t size) noexcept
 Copy shared words into private bytes using acquire loads.
static std::uint64_t * payloadWords (Event &event) noexcept
 Locate the atomic payload words immediately after an event slot header.
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 void validateGeometry (std::uint32_t count, std::uint32_t payloadSize)
 Validate slot count, payload capacity and mapping-size limits.

Private Attributes

std::uint32_t _count
 Validated physical slot count.
EventRingHeader * _header
 Borrowed address of the mapping's immutable ring header.
std::uint32_t _payloadSize
 Validated per-entry payload capacity in bytes.
std::size_t _stride
 Aligned distance in bytes between slot headers.

Detailed Description

Non-owning single-producer event ring view safe for concurrent snapshot readers.

Metadata and payload are copied through atomic words; sequence tags detect overwrite during a read. The writer owns head advancement, timestamp validation and notifications. No shared tail or writer reservation cursor is stored here. The mapping must outlive this view and all calls through it.

Inspired by vt-tv/lockfree_ipc_ringbuffer revision ffd97a3cb0162109920af04408b54c2703aa9e4e; see docs/EventFlows.md.

Definition at line 47 of file EventRingBuffer.hpp.

Member Enumeration Documentation

◆ ReadResult

Outcome of a bounded attempt to copy an entry without waiting.

Enumerator
Ready 

Metadata and payload form a validated snapshot of the requested entry.

Pending 

The requested entry is not yet published or its index is unrepresentable.

Overwritten 

The slot advanced past this index or changed while being copied.

Invalid 

A stable snapshot contains unsupported or invalid metadata.

Definition at line 55 of file EventRingBuffer.hpp.

56 {
57 Ready,
58 Pending,
59 Overwritten,
60 Invalid
61 };

Constructor & Destructor Documentation

◆ EventRingBuffer()

mxl::lib::EventRingBuffer::EventRingBuffer ( void * memory,
std::uint32_t count,
std::uint32_t payloadSize )
inline

Attach a view and validate immutable headers across all slots.

Parameters
memoryInitialized mapping, possibly read-only for a reader.
countExpected slot count from the common flow configuration.
payloadSizeExpected per-entry payload capacity.
Precondition
memory is correctly aligned and covers bufferSize(count, payloadSize) bytes.
Exceptions
std::invalid_argumentGeometry or a ring/slot header is invalid.

Definition at line 105 of file EventRingBuffer.hpp.

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 }
EventRingHeader * _header
Borrowed address of the mapping's immutable ring header.
std::size_t _stride
Aligned distance in bytes between slot headers.
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.
std::uint32_t _count
Validated physical slot count.
std::uint32_t _payloadSize
Validated per-entry payload capacity in bytes.
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.
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
EventHeader header
Sequence, layout and metadata fields for this slot.
Definition Flow.hpp:91

Member Function Documentation

◆ bufferSize()

std::size_t mxl::lib::EventRingBuffer::bufferSize ( std::uint32_t count,
std::uint32_t payloadSize )
inlinestatic

Validate geometry and compute the complete mapping length.

Parameters
countNumber of slots, from 2 through 65536.
payloadSizeMaximum bytes per entry, from 1 through 1048576.
Returns
Ring header size plus the stride of every slot.
Exceptions
std::invalid_argumentGeometry is unsupported or its byte count overflows.

Definition at line 81 of file EventRingBuffer.hpp.

82 {
83 validateGeometry(count, payloadSize);
84 return sizeof(EventRingHeader) + (slotStride(payloadSize) * count);
85 }

◆ initialize()

void mxl::lib::EventRingBuffer::initialize ( void * memory,
std::uint32_t count,
std::uint32_t payloadSize )
static

Construct headers, empty sequence tags and payload words in a fresh mapping.

Parameters
[out]memoryWritable storage of at least bufferSize(count, payloadSize) bytes.
countNumber of slots to construct.
payloadSizeMaximum bytes per entry.
Precondition
memory is aligned for Event, and no reader or writer accesses it yet.
Exceptions
std::invalid_argumentGeometry is invalid.

Definition at line 9 of file EventRingBuffer.cpp.

10 {
11 validateGeometry(count, payloadSize);
12 auto header = std::construct_at(static_cast<EventRingHeader*>(memory));
13 header->version = STORAGE_VERSION;
14 header->size = sizeof *header;
15 header->eventCount = count;
16 header->payloadSize = payloadSize;
17 auto slotMemory = static_cast<std::uint8_t*>(memory) + sizeof(EventRingHeader);
18 auto const stride = slotStride(payloadSize);
19 auto const payloadWordCount = (payloadSize + sizeof(std::uint64_t) - 1) / sizeof(std::uint64_t);
20 for (auto i = std::size_t{0}; i < count; ++i, slotMemory += stride)
21 {
22 auto event = std::construct_at(reinterpret_cast<Event*>(slotMemory));
23 event->header.version = STORAGE_VERSION;
24 event->header.size = sizeof event->header;
25 event->header.sequence = EMPTY;
26 std::uninitialized_value_construct_n(payloadWords(*event), payloadWordCount);
27 }
28 }
static constexpr auto EMPTY
Tag identifying a slot with no publication.
static std::uint64_t * payloadWords(Event &event) noexcept
Locate the atomic payload words immediately after an event slot header.

◆ load()

std::uint64_t mxl::lib::EventRingBuffer::load ( std::uint64_t const & value)
inlinestaticnoexcept

Load a shared 64-bit word with acquire ordering, including from a read-only mapping.

Parameters
valueNaturally aligned word accessed atomically by concurrent users.
Returns
The atomically observed value.

Definition at line 205 of file EventRingBuffer.hpp.

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 }

◆ loadBytes()

void mxl::lib::EventRingBuffer::loadBytes ( void * destination,
std::uint64_t const * source,
std::size_t size )
inlinestaticprivatenoexcept

Copy shared words into private bytes using acquire loads.

Parameters
[out]destinationPrivate storage covering size bytes.
sourceAligned shared words covering size rounded up to eight bytes.
sizeByte count to copy; the final word may be copied partially.

Definition at line 271 of file EventRingBuffer.hpp.

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 }
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.
std::size_t size() const noexcept
Returns the total number of writers that are registered in the DomainWatcher.

◆ payloadWords()

std::uint64_t * mxl::lib::EventRingBuffer::payloadWords ( Event & event)
inlinestaticprivatenoexcept

Locate the atomic payload words immediately after an event slot header.

Parameters
eventSlot header inside a live mapping.
Returns
Payload word address; callers respect mapping permissions and use atomic access.

Definition at line 241 of file EventRingBuffer.hpp.

242 {
243 return reinterpret_cast<std::uint64_t*>(reinterpret_cast<std::uint8_t*>(&event) + sizeof(Event));
244 }

◆ publish()

mxlStatus mxl::lib::EventRingBuffer::publish ( std::uint64_t index,
mxlEventInfo const & info,
std::uint8_t const * payload )
inlinenoexcept

Atomically publish metadata and payload under a new sequence tag.

Parameters
indexQueue index selected by the sole producer, normally headIndex + 1.
infoValidated entry metadata; eventSize must not exceed the ring capacity.
payloadSource of at least info.eventSize bytes, stable for the call.
Precondition
The caller exclusively owns publication and the mapping is writable.
Return values
MXL_STATUS_OKThe entry is published; the caller may advance the head.
MXL_ERR_OUT_OF_RANGE_TOO_LATEindex exceeds MAX_INDEX.
MXL_ERR_FLOW_INVALIDThe slot already holds this or a newer sequence tag.
Note
This primitive does not validate timestamps or update the shared head.

Definition at line 139 of file EventRingBuffer.hpp.

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 }
static constexpr auto MAX_INDEX
Largest index whose complete tag does not collide with EMPTY.
static void storeBytes(std::uint64_t *destination, void const *source, std::size_t size) noexcept
Copy private bytes to shared words using release stores.
@ 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
uint64_t index

◆ read()

ReadResult mxl::lib::EventRingBuffer::read ( std::uint64_t index,
mxlEventInfo & info,
std::uint8_t * payload ) const
inlinenoexcept

Copy one entry with sequence validation before and after the copy.

Parameters
indexQueue index to read.
[out]infoDestination for metadata.
[out]payloadPrivate destination with at least the configured payload capacity.
Returns
Snapshot outcome; outputs are usable only when the result is ReadResult::Ready.
Precondition
Concurrent calls use separate output storage. The mapping remains alive.

Definition at line 169 of file EventRingBuffer.hpp.

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 }
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.
constexpr auto EVENT_HEADER_VERSION
Version stored in the public mxlEventInfo metadata of every published entry.
Definition Flow.hpp:61
uint32_t version
Structure version, currently 1.
Definition flow.h:160
uint32_t size
Size of this structure.
Definition flow.h:161
uint32_t eventSize
Number of payload bytes published in this entry, possibly zero. For fragments this is the fragment si...
Definition flow.h:179
uint64_t index
Zero-based queue position, assigned by the library on a successful read. Compare with mxlFlowRuntimeI...
Definition flow.h:202
uint32_t flags
Reserved; must be zero.
Definition flow.h:163

◆ slot()

Event & mxl::lib::EventRingBuffer::slot ( std::uint64_t index) const
inlineprivatenoexcept

Resolve a logical queue index to a physical slot modulo capacity.

Parameters
indexQueue index whose slot is needed.
Returns
Slot header in the borrowed mapping; access must obey the atomic protocol.

Definition at line 231 of file EventRingBuffer.hpp.

232 {
233 return *reinterpret_cast<Event*>(reinterpret_cast<std::uint8_t*>(_header) + sizeof(EventRingHeader) + ((index % _count) * _stride));
234 }

◆ slotStride()

constexpr std::size_t mxl::lib::EventRingBuffer::slotStride ( std::uint32_t payloadSize)
inlinestaticconstexprnoexcept

Compute the physical stride between adjacent slots.

Parameters
payloadSizeMaximum payload bytes per entry.
Returns
Slot header plus payload capacity, rounded up to a fixed 128-byte boundary.

Definition at line 68 of file EventRingBuffer.hpp.

69 {
70 constexpr auto alignment = std::size_t{128};
71 return (sizeof(Event) + payloadSize + alignment - 1) & ~(alignment - 1U);
72 }

◆ storeBytes()

void mxl::lib::EventRingBuffer::storeBytes ( std::uint64_t * destination,
void const * source,
std::size_t size )
inlinestaticprivatenoexcept

Copy private bytes to shared words using release stores.

Parameters
[out]destinationAligned words with space for size rounded up to eight bytes.
sourceStable private bytes to publish.
sizeByte count; zero permits a null source.

Definition at line 252 of file EventRingBuffer.hpp.

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 }

◆ validateGeometry()

void mxl::lib::EventRingBuffer::validateGeometry ( std::uint32_t count,
std::uint32_t payloadSize )
inlinestaticprivate

Validate slot count, payload capacity and mapping-size limits.

Exceptions
std::invalid_argumentGeometry is unsupported or its byte count overflows.

Definition at line 217 of file EventRingBuffer.hpp.

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 }

Member Data Documentation

◆ _count

std::uint32_t mxl::lib::EventRingBuffer::_count
private

Validated physical slot count.

Definition at line 283 of file EventRingBuffer.hpp.

◆ _header

EventRingHeader* mxl::lib::EventRingBuffer::_header
private

Borrowed address of the mapping's immutable ring header.

Definition at line 282 of file EventRingBuffer.hpp.

◆ _payloadSize

std::uint32_t mxl::lib::EventRingBuffer::_payloadSize
private

Validated per-entry payload capacity in bytes.

Definition at line 284 of file EventRingBuffer.hpp.

◆ _stride

std::size_t mxl::lib::EventRingBuffer::_stride
private

Aligned distance in bytes between slot headers.

Definition at line 285 of file EventRingBuffer.hpp.

◆ EMPTY

auto mxl::lib::EventRingBuffer::EMPTY = std::numeric_limits<std::uint64_t>::max()
staticconstexpr

Tag identifying a slot with no publication.

Definition at line 51 of file EventRingBuffer.hpp.

◆ MAX_INDEX

auto mxl::lib::EventRingBuffer::MAX_INDEX = (EMPTY >> 1) - 1
staticconstexpr

Largest index whose complete tag does not collide with EMPTY.

Definition at line 52 of file EventRingBuffer.hpp.

◆ STORAGE_VERSION

auto mxl::lib::EventRingBuffer::STORAGE_VERSION = std::uint32_t{1}
staticconstexpr

Version used by immutable ring and slot headers.

Definition at line 50 of file EventRingBuffer.hpp.

50{1};

The documentation for this class was generated from the following files: