MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
test_events.cpp File Reference

Event API, fragmentation, lifetime and concurrency regression tests. More...

#include <csignal>
#include <cstring>
#include <algorithm>
#include <array>
#include <atomic>
#include <barrier>
#include <fstream>
#include <future>
#include <limits>
#include <span>
#include <thread>
#include <vector>
#include <poll.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/wait.h>
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <fmt/format.h>
#include <mxl/flow.h>
#include <mxl/mxl.h>
#include "mxl-internal/EventRingBuffer.hpp"
#include "mxl-internal/Flow.hpp"
#include "mxl-internal/FlowManager.hpp"
#include "mxl-internal/FlowParser.hpp"
#include "mxl-internal/PosixFlowIoFactory.hpp"
#include "mxl-internal/Sync.hpp"
#include "PcapReader.hpp"
#include "Utils.hpp"
Include dependency graph for test_events.cpp:

Go to the source code of this file.

Functions

 TEST_CASE ("Compact event slots preserve payload boundaries across wraparound", "[events]")
 TEST_CASE ("Event atomic copies survive contention within the same mapping", "[events][concurrency]")
 TEST_CASE ("Event capacity follows grain rate and history duration", "[events]")
 TEST_CASE ("Event capacity rejects overflow before narrowing", "[events]")
 TEST_CASE ("Event group hints validate names roles and scopes", "[events][parser]")
 TEST_CASE ("Event parser requires a positive grain rate", "[events]")
 TEST_CASE ("Event publication retries only unpublished sequence tags", "[events][recovery]")
 TEST_CASE ("Event sequence exhaustion cannot alias an empty slot", "[events]")
 TEST_CASE ("Event writer recovery preserves publication and timestamp order", "[events][recovery]")
 TEST_CASE ("Independent event readers each consume every publication", "[events][concurrency]")
 TEST_CASE ("One event writer wakes independent readers in other processes", "[events][concurrency][ipc]")
 TEST_CASE ("Reopened event writers restore the last committed timestamp", "[events][timestamps]")
 TEST_CASE ("ST 2110-41 pcap packets round trip through the event ring", "[events][pcap]")
 TEST_CASE_METHOD (EventFixture, "Event API rejects wrong handles and invalid arguments", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event cancellation and invalid commits do not publish", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event capacity rejects too little or excessive history", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event commits reject earlier timestamps without publishing", "[events][timestamps]")
 TEST_CASE_METHOD (EventFixture, "Event flow queue preserves timestamps and complete payloads", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event indices identify queue position and skipped entries", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event overrun recovers at oldest retained event and hides open slot", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event reader rejects truncated shared payload", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event reader validates headers throughout the shared buffer", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event readers have independent cursors and wake on commit", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event readers never expose torn payloads during concurrent wraparound", "[events][concurrency]")
 TEST_CASE_METHOD (EventFixture, "Event slots occupy one shared memory file", "[events]")
 TEST_CASE_METHOD (EventFixture, "Event snapshots survive overwrite and reads from independent readers", "[events][concurrency]")
 TEST_CASE_METHOD (EventFixture, "Fragment offset mismatches expose discontinuities to the consumer", "[events][fragmentation]")
 TEST_CASE_METHOD (EventFixture, "Late event reader starts at oldest retained event and detects deleted flow", "[events]")
 TEST_CASE_METHOD (EventFixture, "Opening an event initializes every metadata field", "[events]")
 TEST_CASE_METHOD (EventFixture, "Repeated event writer acquisition shares publication state", "[events]")
 TEST_CASE_METHOD (EventFixture, "Two event fragments preserve continuity and reassemble across ring wrap", "[events][fragmentation]")
 TEST_CASE_METHOD (EventFixture, "Unfragmented events have zero offset and are complete", "[events][fragmentation]")

Detailed Description

Event API, fragmentation, lifetime and concurrency regression tests.

Definition in file test_events.cpp.

Function Documentation

◆ TEST_CASE() [1/13]

TEST_CASE ( "Compact event slots preserve payload boundaries across wraparound" ,
"" [events] )
Test
Compact event slots preserve adjacent entries and buffer bounds for unaligned payload capacities.

Aligned backing storage with an extra block to detect writes beyond the ring.

< Raw storage for slots or the trailing sentinel.

Definition at line 1402 of file test_events.cpp.

1403{
1404 using Ring = mxl::lib::EventRingBuffer;
1405
1407 struct alignas(128) Block
1408 {
1409 std::uint8_t bytes[128];
1410 };
1411
1412 constexpr auto count = std::uint32_t{3};
1413 for (auto const capacity : std::array<std::uint32_t, 11>{1, 7, 8, 13, 63, 64, 65, 127, 128, 129, 4096})
1414 {
1415 // Probe word and cache-line boundaries; the extra block detects writes beyond the ring.
1416 CAPTURE(capacity);
1417 auto const size = Ring::bufferSize(count, capacity);
1418 REQUIRE(size % sizeof(Block) == 0);
1419 auto memory = std::vector<Block>{(size / sizeof(Block)) + 1};
1420 std::memset(memory.data(), 0xCD, size + sizeof(Block));
1421 Ring::initialize(memory.data(), count, capacity);
1422 for (auto i = std::size_t{0}; i < count; ++i)
1423 {
1424 auto const bytes = reinterpret_cast<std::uint8_t const*>(memory.data()) + sizeof(mxl::lib::EventRingHeader) +
1425 (i * Ring::slotStride(capacity));
1426 auto const& header = reinterpret_cast<mxl::lib::Event const*>(bytes)->header;
1427 REQUIRE(reinterpret_cast<std::uintptr_t>(&header.sequence) % 128 == 0);
1428 REQUIRE(reinterpret_cast<std::uintptr_t>(header.infoWords) % 128 == 0);
1429 auto const isZero = [](auto byte) noexcept
1430 {
1431 return byte == 0;
1432 };
1433 REQUIRE(std::ranges::all_of(header.layoutPadding, isZero));
1434 REQUIRE(std::ranges::all_of(header.sequencePadding, isZero));
1435 }
1436 auto ring = Ring{memory.data(), count, capacity};
1437 auto payload = std::vector<std::uint8_t>{};
1438 payload.resize(capacity);
1439 for (auto index = std::uint64_t{0}; index < std::uint64_t{count} * 2; ++index)
1440 {
1441 auto info = mxlEventInfo{};
1442 info.version = mxl::lib::EVENT_HEADER_VERSION;
1443 info.size = sizeof info;
1444 info.timestamp = index;
1445 info.eventSize = capacity;
1446 info.complete = 1;
1447 std::ranges::fill(payload, static_cast<std::uint8_t>(index));
1448 REQUIRE(ring.publish(index, info, payload.data()) == MXL_STATUS_OK);
1449 }
1450 REQUIRE_NOTHROW(Ring{memory.data(), count, capacity});
1451 for (auto index = std::uint64_t{count}; index < std::uint64_t{count} * 2; ++index)
1452 {
1453 auto info = mxlEventInfo{};
1454 std::ranges::fill(payload, 0);
1455 REQUIRE(ring.read(index, info, payload.data()) == Ring::ReadResult::Ready);
1456 REQUIRE(info.timestamp == index);
1457 REQUIRE(info.eventSize == capacity);
1458 REQUIRE(std::ranges::all_of(payload,
1459 [index](auto byte) noexcept
1460 {
1461 // Each retained slot must contain only the byte pattern written for its own index.
1462 return byte == index;
1463 }));
1464 }
1465 auto const sentinel = std::span{memory.back().bytes};
1466 REQUIRE(std::ranges::all_of(sentinel,
1467 [](auto byte) noexcept
1468 {
1469 // An unchanged canary means no write reached the block beyond the ring.
1470 return byte == 0xCD;
1471 }));
1472 }
1473}
Non-owning single-producer event ring view safe for concurrent snapshot readers.
struct mxlEventInfo_t mxlEventInfo
Metadata for one event queue entry, either a complete event or a fragment.
@ MXL_STATUS_OK
Definition mxl.h:23
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.
Fixed part of an event slot; its payload follows immediately in the mapping.
Definition Flow.hpp:90
uint64_t index
REQUIRE(timeDelta< 33 '366 '667LL)

◆ TEST_CASE() [2/13]

TEST_CASE ( "Event atomic copies survive contention within the same mapping" ,
"" [events][concurrency] )
Test
Event atomic copies survive contention within the same mapping.

Page-aligned backing storage for an in-memory event ring test.

< One page of raw mapping storage.

Definition at line 1476 of file test_events.cpp.

1477{
1478 // Race low-level copies in one mapping: overwritten entries are allowed, torn snapshots are not.
1479 using Ring = mxl::lib::EventRingBuffer;
1480
1482 struct alignas(4096) Page
1483 {
1484 std::uint8_t bytes[4096];
1485 };
1486
1487 constexpr auto count = std::uint32_t{3};
1488 constexpr auto total = std::uint64_t{4000};
1489 auto memory = std::vector<Page>{(Ring::bufferSize(count, 4096) + sizeof(Page) - 1) / sizeof(Page)};
1490 Ring::initialize(memory.data(), count, 4096);
1491 auto ring = Ring{memory.data(), count, 4096};
1492 auto start = std::barrier{3};
1493 auto failed = std::atomic<bool>{false};
1494 auto producer = std::async(std::launch::async,
1495 [&]
1496 {
1497 // Vary both length and contents while publishing directly into the shared mapping.
1498 start.arrive_and_wait();
1499 for (auto index = std::uint64_t{0}; index < total && !failed; ++index)
1500 {
1501 auto info = mxlEventInfo{};
1502 info.version = mxl::lib::EVENT_HEADER_VERSION;
1503 info.size = sizeof info;
1504 info.timestamp = 4000 + index;
1505 info.eventSize = info.timestamp % 4097;
1506 info.complete = 1;
1507 auto payload = std::array<std::uint8_t, 4096>{};
1508 for (auto byte = std::uint32_t{0}; byte < info.eventSize; ++byte)
1509 {
1510 payload[byte] = static_cast<std::uint8_t>((info.timestamp * 29) + (std::uint64_t{byte} * 7));
1511 }
1512 if (ring.publish(index, info, payload.data()) != MXL_STATUS_OK)
1513 {
1514 failed = true;
1515 }
1516 }
1517 });
1518 auto reader = std::async(std::launch::async,
1519 [&]
1520 {
1521 // Skip overwritten indices and validate every snapshot that the ring reports as ready.
1522 start.arrive_and_wait();
1523 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{10};
1524 auto index = std::uint64_t{0};
1525 auto received = std::size_t{0};
1526 while (index < total && !failed && std::chrono::steady_clock::now() < deadline)
1527 {
1528 auto info = mxlEventInfo{};
1529 auto payload = std::array<std::uint8_t, 4096>{};
1530 auto const result = ring.read(index, info, payload.data());
1531 if (result == Ring::ReadResult::Ready)
1532 {
1533 if (info.timestamp != 4000 + index || !validPattern(info, payload.data()))
1534 {
1535 failed = true;
1536 break;
1537 }
1538 ++received;
1539 ++index;
1540 }
1541 else if (result == Ring::ReadResult::Overwritten)
1542 {
1543 ++index;
1544 }
1545 else if (result == Ring::ReadResult::Invalid)
1546 {
1547 failed = true;
1548 }
1549 else
1550 {
1551 std::this_thread::yield();
1552 }
1553 }
1554 if (index != total)
1555 {
1556 failed = true;
1557 }
1558 return received;
1559 });
1560 start.arrive_and_wait();
1561 producer.get();
1562 auto const received = reader.get();
1563 REQUIRE_FALSE(failed);
1564 REQUIRE(received > 0);
1565}
mxlFlowReader reader

◆ TEST_CASE() [3/13]

TEST_CASE ( "Event capacity follows grain rate and history duration" ,
"" [events] )
Test
Event capacity follows grain rate and history duration.

Definition at line 880 of file test_events.cpp.

881{
882 SECTION("A different rate changes capacity")
883 {
884 // At 50 entries/s, the default 200 ms history requires ten slots.
885 auto fixture = EventFixture{definitionWithRate(R"({"numerator":50})")};
886 REQUIRE(fixture.config.event.eventCount == 10);
887 REQUIRE(fixture.config.common.grainRate.numerator == 50);
888 }
889 SECTION("Fractional rates use integer division")
890 {
891 // 22.5 entries/s over 0.2 s gives 4.5 entries; capacity currently truncates to four.
892 auto fixture = EventFixture{definitionWithRate(R"({"numerator":45,"denominator":2})")};
893 REQUIRE(fixture.config.event.eventCount == 4);
894 REQUIRE(fixture.config.common.grainRate.numerator == 45);
895 REQUIRE(fixture.config.common.grainRate.denominator == 2);
896 }
897 SECTION("Large rational components do not overflow intermediate products")
898 {
899 // Just over 20 entries/s; coprime components keep both products wider than 64 bits.
900 auto fixture = EventFixture{definitionWithRate(R"({"numerator":2000000000001,"denominator":100000000000})")};
901 REQUIRE(fixture.config.event.eventCount == 4);
902 }
903 SECTION("Domain history duration changes capacity")
904 {
905 // Holding the rate at 20 entries/s and extending history to 0.5 s produces ten slots.
906 auto fixture = EventFixture{definition, R"({"urn:x-mxl:option:history_duration/v1.0":500000000})"};
907 REQUIRE(fixture.config.event.eventCount == 10);
908 }
909}

◆ TEST_CASE() [4/13]

TEST_CASE ( "Event capacity rejects overflow before narrowing" ,
"" [events] )
Test
Reject capacities wider than size_t before narrowing to the ring geometry.

Definition at line 924 of file test_events.cpp.

925{
926 auto domain = mxl::tests::makeTempDomain();
927 {
928 auto options = std::ofstream{mxl::lib::makeDomainOptionsFilePath(domain)};
929 options << R"({"urn:x-mxl:option:history_duration/v1.0":9223372036854775808})";
930 }
931 auto instance = mxlCreateInstance(domain.c_str(), nullptr);
932 REQUIRE(instance != nullptr);
933 auto writer = mxlFlowWriter{};
934 // The capacity exceeds 2^64; narrowing first would incorrectly accept 2,361 slots.
935 auto flowDef = definitionWithRate(R"({"numerator":4000000000000000512,"denominator":2000000000})");
936 auto status = mxlCreateFlowWriter(instance, flowDef.c_str(), nullptr, &writer, nullptr, nullptr);
938 std::filesystem::remove_all(domain);
939 REQUIRE(status != MXL_STATUS_OK);
940}
struct mxlFlowWriter_t * mxlFlowWriter
Definition flow.h:206
MXL_EXPORT mxlStatus mxlCreateFlowWriter(mxlInstance instance, char const *flowDef, char const *options, mxlFlowWriter *writer, mxlFlowConfigInfo *configInfo, bool *created)
Definition flow.cpp:198
MXL_EXPORT mxlStatus mxlDestroyInstance(mxlInstance in_instance)
Definition mxl.cpp:106
MXL_EXPORT mxlInstance mxlCreateInstance(char const *in_mxlDomain, char const *in_options)
Definition mxl.cpp:45
std::filesystem::path makeDomainOptionsFilePath(std::filesystem::path const &domain)
Definition PathUtils.cpp:59
std::filesystem::path makeTempDomain()
Definition Utils.hpp:108
mxlFlowWriter writer
auto flowDef

◆ TEST_CASE() [5/13]

TEST_CASE ( "Event group hints validate names roles and scopes" ,
"" [events][parser] )
Test
Event group hints reject empty components and invalid scopes while accepting supported forms.

Definition at line 854 of file test_events.cpp.

855{
856 // Change only the group hint to isolate valid forms from malformed names, roles and scopes.
857 auto flow = picojson::value{};
858 REQUIRE(picojson::parse(flow, definition).empty());
859 auto& hints = flow.get<picojson::object>()["tags"].get<picojson::object>()["urn:x-nmos:tag:grouphint/v1.0"];
860
861 for (auto const hint : {"group:role", "group:role:device", "group:role:node"})
862 {
863 CAPTURE(hint);
864 hints = picojson::value{picojson::array{picojson::value{std::string{hint}}}};
865 REQUIRE_NOTHROW(mxl::lib::FlowParser{flow.serialize()});
866 }
867 for (auto const hint : {"", ":", "group", "group:", ":role", "group::node", "group:role:", "group:role:invalid", "group:role:node:extra"})
868 {
869 CAPTURE(hint);
870 hints = picojson::value{picojson::array{picojson::value{std::string{hint}}}};
871 REQUIRE_THROWS_AS(mxl::lib::FlowParser{flow.serialize()}, std::domain_error);
872 }
873 hints = picojson::value{picojson::array{}};
874 REQUIRE_THROWS_AS(mxl::lib::FlowParser{flow.serialize()}, std::domain_error);
875 hints = picojson::value{picojson::array{picojson::value{true}}};
876 REQUIRE_THROWS_AS(mxl::lib::FlowParser{flow.serialize()}, std::domain_error);
877}

◆ TEST_CASE() [6/13]

TEST_CASE ( "Event parser requires a positive grain rate" ,
"" [events] )
Test
Event parser requires a positive grain rate.

Definition at line 829 of file test_events.cpp.

830{
831 // Check event classification and reject descriptors that cannot yield a valid ring capacity.
835 auto const parser = mxl::lib::FlowParser{definition};
836 REQUIRE(parser.getFormat() == MXL_DATA_FORMAT_EVENT);
837 REQUIRE(parser.getGrainRate().numerator == 20);
838 REQUIRE(parser.getGrainRate().denominator == 1);
839 REQUIRE(parser.getPayloadSize() == MXL_DATA_FORMAT_GRAIN_SIZE);
840 REQUIRE_THROWS(parser.getTotalPayloadSlices());
841 for (auto rate : {R"({"numerator":0})", R"({"numerator":-1})", R"({"numerator":20,"denominator":0})"})
842 {
843 auto flowDef = definitionWithRate(rate);
844 REQUIRE_THROWS(mxl::lib::FlowParser{flowDef});
845 }
846
847 auto flow = picojson::value{};
848 REQUIRE(picojson::parse(flow, definition).empty());
849 flow.get<picojson::object>().erase("grain_rate");
850 REQUIRE_THROWS(mxl::lib::FlowParser{flow.serialize()});
851}
int mxlIsSupportedDataFormat(int format)
Definition dataformat.h:56
int mxlIsContinuousDataFormat(int format)
Definition dataformat.h:106
int mxlIsDiscreteDataFormat(int format)
Definition dataformat.h:75
@ MXL_DATA_FORMAT_EVENT
Asynchronous queue of complete events or event fragments.
Definition dataformat.h:30
#define MXL_DATA_FORMAT_GRAIN_SIZE
Definition dataformat.h:15
auto const rate
Compute the grain index for the flow rate and current TAI time.

◆ TEST_CASE() [7/13]

TEST_CASE ( "Event publication retries only unpublished sequence tags" ,
"" [events][recovery] )
Test
Interrupted copies may be retried, but completed sequence tags must never be reused.

Definition at line 1603 of file test_events.cpp.

1604{
1605 using Ring = mxl::lib::EventRingBuffer;
1606
1607 struct alignas(4096) Page
1608 {
1609 std::uint8_t bytes[4096];
1610 };
1611
1612 auto memory = std::vector<Page>{(Ring::bufferSize(2, 13) + sizeof(Page) - 1) / sizeof(Page)};
1613 Ring::initialize(memory.data(), 2, 13);
1614 auto ring = Ring{memory.data(), 2, 13};
1615 auto slot = reinterpret_cast<mxl::lib::Event*>(reinterpret_cast<std::uint8_t*>(memory.data()) + sizeof(mxl::lib::EventRingHeader));
1616 auto info = mxlEventInfo{};
1617 info.version = mxl::lib::EVENT_HEADER_VERSION;
1618 info.size = sizeof info;
1619 info.eventSize = 13;
1620 auto payload = std::array<std::uint8_t, 13>{};
1621 payload.fill(0xAB);
1622 SECTION("Unpublished tag may be retried")
1623 {
1624 slot->header.sequence = 0;
1625 REQUIRE(ring.read(0, info, payload.data()) == Ring::ReadResult::Pending);
1626 REQUIRE(ring.publish(0, info, payload.data()) == MXL_STATUS_OK);
1627 payload.fill(0);
1628 REQUIRE(ring.read(0, info, payload.data()) == Ring::ReadResult::Ready);
1629 REQUIRE(std::ranges::all_of(payload, [](auto byte) { return byte == 0xAB; }));
1630 REQUIRE(ring.publish(0, info, payload.data()) == MXL_ERR_FLOW_INVALID);
1631 }
1632 SECTION("Completed tag may not be reused")
1633 {
1634 REQUIRE(ring.publish(0, info, payload.data()) == MXL_STATUS_OK);
1635 REQUIRE(ring.publish(0, info, payload.data()) == MXL_ERR_FLOW_INVALID);
1636 }
1637 SECTION("Newer writing tag may not be overwritten")
1638 {
1639 slot->header.sequence = 2 << 1;
1640 REQUIRE(ring.publish(0, info, payload.data()) == MXL_ERR_FLOW_INVALID);
1641 }
1642}
@ MXL_ERR_FLOW_INVALID
Definition mxl.h:41

◆ TEST_CASE() [8/13]

TEST_CASE ( "Event sequence exhaustion cannot alias an empty slot" ,
"" [events] )
Test
Event sequence exhaustion cannot alias an empty slot.

Page-aligned backing storage for an in-memory event ring test.

< One page of raw mapping storage.

Definition at line 1568 of file test_events.cpp.

1569{
1570 using Ring = mxl::lib::EventRingBuffer;
1571
1573 struct alignas(4096) Page
1574 {
1575 std::uint8_t bytes[4096];
1576 };
1577
1578 auto memory = std::vector<Page>{(Ring::bufferSize(2, 13) + sizeof(Page) - 1) / sizeof(Page)};
1579 Ring::initialize(memory.data(), 2, 13);
1580 auto ring = Ring{memory.data(), 2, 13};
1581 auto const index = Ring::MAX_INDEX;
1582 // The largest valid sequence must stay distinguishable from the empty-slot sentinel.
1583 auto info = mxlEventInfo{};
1584 info.version = mxl::lib::EVENT_HEADER_VERSION;
1585 info.size = sizeof info;
1586 info.eventSize = 13;
1587 auto payload = std::array<std::uint8_t, 13>{};
1588 payload.fill(0xAB);
1589 REQUIRE(ring.publish(index, info, payload.data()) == MXL_STATUS_OK);
1590 payload.fill(0);
1591 REQUIRE(ring.read(index, info, payload.data()) == Ring::ReadResult::Ready);
1592 REQUIRE(std::ranges::all_of(payload,
1593 [](auto byte) noexcept
1594 {
1595 // The final valid sequence must still deliver every byte of its payload.
1596 return byte == 0xAB;
1597 }));
1598 REQUIRE(ring.publish(index + 1, info, payload.data()) == MXL_ERR_OUT_OF_RANGE_TOO_LATE);
1599 REQUIRE(ring.read(Ring::MAX_INDEX + 1, info, payload.data()) == Ring::ReadResult::Pending);
1600}
@ MXL_ERR_OUT_OF_RANGE_TOO_LATE
Definition mxl.h:30

◆ TEST_CASE() [9/13]

TEST_CASE ( "Event writer recovery preserves publication and timestamp order" ,
"" [events][recovery] )
Test
Recover each writer-crash stage both before the first entry and after wraparound.

Definition at line 1688 of file test_events.cpp.

1689{
1690 using namespace mxl::lib;
1691 using Ring = EventRingBuffer;
1692 auto const initialCount = GENERATE(std::uint64_t{0}, std::uint64_t{6});
1693 // 0: interrupted copy; 1: complete slot, stale head; 2: updated head, no notification.
1694 auto const crashStage = GENERATE(0, 1, 2);
1695 CAPTURE(initialCount, crashStage);
1696
1697 struct Domain
1698 {
1699 std::filesystem::path path = mxl::tests::makeTempDomain();
1700
1701 ~Domain()
1702 {
1703 auto error = std::error_code{};
1704 std::filesystem::remove_all(path, error);
1705 }
1706 };
1707
1708 auto const domain = Domain{};
1709 auto manager = FlowManager{domain.path};
1710 auto watcher = std::make_shared<DomainWatcher>(domain.path);
1711 auto factory = PosixFlowIoFactory{watcher};
1712 auto const flowId = uuids::uuid::from_string(id).value();
1713 auto [created, data] = manager.createOrOpenEventFlow(flowId, definition, 4, mxlRational{20, 1}, 13);
1714 REQUIRE(created);
1715 auto* flow = data->flow();
1716 auto info = mxlEventInfo{};
1717 info.version = EVENT_HEADER_VERSION;
1718 info.size = sizeof info;
1719 info.eventSize = 13;
1720 info.complete = 1;
1721 auto bytes = std::array<std::uint8_t, 13>{};
1722 bytes.fill(0xAB);
1723 for (auto i = std::uint64_t{0}; i < initialCount; ++i)
1724 {
1725 info.timestamp = 10 + i;
1726 REQUIRE(data->ring().publish(i, info, bytes.data()) == MXL_STATUS_OK);
1727 flow->info.runtime.headIndex = i;
1728 }
1729 auto const eventFile = makeEventDataFilePath(makeFlowDirectoryName(domain.path, id));
1730 auto mapping = SharedMemorySegment{eventFile.c_str(), AccessMode::READ_WRITE, Ring::bufferSize(4, 13), LockMode::None};
1731 auto* slot = reinterpret_cast<Event*>(
1732 static_cast<std::uint8_t*>(mapping.data()) + sizeof(EventRingHeader) + ((initialCount % 4) * Ring::slotStride(13)));
1733 info.timestamp = 100;
1734 if (crashStage == 0)
1735 {
1736 slot->header.sequence = initialCount << 1;
1737 std::memset(slot + 1, 0xCD, 13); // Partial stale payload that recovery must replace completely.
1738 }
1739 else
1740 {
1741 REQUIRE(data->ring().publish(initialCount, info, bytes.data()) == MXL_STATUS_OK);
1742 if (crashStage == 2)
1743 {
1744 flow->info.runtime.headIndex = initialCount;
1745 }
1746 }
1747 auto const previous = flow->state.syncCounter;
1748 auto waiter = std::async(std::launch::async,
1749 [flow, previous] { return waitUntilChanged(&flow->state.syncCounter, previous, mxl::lib::Duration{1'000'000'000}); });
1750 auto writer = factory.createEventFlowWriter(manager, flowId, std::move(data));
1751 auto payload = static_cast<std::uint8_t*>(nullptr);
1752 REQUIRE(writer->openEvent(&info, &payload) == MXL_STATUS_OK);
1753 if (crashStage == 0)
1754 {
1755 REQUIRE(writer->getFlowRuntimeInfo().headIndex == (initialCount == 0 ? MXL_UNDEFINED_INDEX : initialCount - 1));
1756 info.timestamp = 100;
1757 info.eventSize = 13;
1758 std::memcpy(payload, bytes.data(), bytes.size());
1759 REQUIRE(writer->commit(info) == MXL_STATUS_OK);
1760 }
1761 else
1762 {
1763 REQUIRE(writer->getFlowRuntimeInfo().headIndex == initialCount);
1764 info.timestamp = 99;
1765 REQUIRE(writer->commit(info) == MXL_ERR_INVALID_ARG);
1766 REQUIRE(writer->cancel() == MXL_STATUS_OK);
1767 }
1768 REQUIRE(waiter.get());
1769 REQUIRE(flow->state.syncCounter != previous);
1770 auto ring = Ring{mapping.data(), 4, 13};
1771 auto received = mxlEventInfo{};
1772 auto copied = std::array<std::uint8_t, 13>{};
1773 REQUIRE(ring.read(initialCount, received, copied.data()) == Ring::ReadResult::Ready);
1774 REQUIRE(received.timestamp == 100);
1775 REQUIRE(received.index == initialCount);
1776 REQUIRE(copied == bytes);
1777 REQUIRE(ring.publish(initialCount, received, bytes.data()) == MXL_ERR_FLOW_INVALID);
1778 REQUIRE(writer->openEvent(&info, &payload) == MXL_STATUS_OK);
1779 info.timestamp = 100;
1780 REQUIRE(writer->commit(info) == MXL_STATUS_OK);
1781 REQUIRE(writer->getFlowRuntimeInfo().headIndex == initialCount + 1);
1782}
@ MXL_ERR_INVALID_ARG
Definition mxl.h:35
std::filesystem::path makeEventDataFilePath(std::filesystem::path const &flowDirectory)
Locate an event ring file within its flow directory.
Definition PathUtils.cpp:53
bool waitUntilChanged(T const *in_addr, T in_expected, Timepoint in_deadline)
Definition Sync.cpp:68
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
Definition PathUtils.cpp:11
#define MXL_UNDEFINED_INDEX
Definition rational.h:17
struct mxlRational_t mxlRational
auto const flowId

◆ TEST_CASE() [10/13]

TEST_CASE ( "Independent event readers each consume every publication" ,
"" [events][concurrency] )
Test
Independent readers each consume every event without duplicate delivery.

Definition at line 1099 of file test_events.cpp.

1100{
1101 auto fixture = EventFixture{definitionWithRate(R"({"numerator":2560})")};
1102 constexpr auto total = std::size_t{256};
1103 auto consumers = std::vector<std::unique_ptr<IndependentEventReader>>{};
1104 for (auto i = 0; i < 4; ++i)
1105 {
1106 consumers.push_back(std::make_unique<IndependentEventReader>(fixture.domain));
1107 }
1108 auto start = std::barrier{6};
1109 auto failed = std::atomic<bool>{false};
1110 auto producer = std::async(std::launch::async,
1111 [&]
1112 {
1113 start.arrive_and_wait();
1114 for (auto i = std::size_t{0}; i < total; ++i)
1115 {
1116 if (writePattern(fixture.writer, 4000 + i) != MXL_STATUS_OK)
1117 {
1118 failed = true;
1119 return false;
1120 }
1121 }
1122 return true;
1123 });
1124 auto readers = std::vector<std::future<std::vector<std::uint64_t>>>{};
1125 for (auto const& consumer : consumers)
1126 {
1127 readers.emplace_back(std::async(std::launch::async,
1128 [&, reader = consumer->reader]
1129 {
1130 auto values = std::vector<std::uint64_t>{};
1131 start.arrive_and_wait();
1132 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
1133 while (!failed && (values.size() < total) && (std::chrono::steady_clock::now() < deadline))
1134 {
1135 auto info = mxlEventInfo{};
1136 auto payload = static_cast<std::uint8_t*>(nullptr);
1137 auto const status = mxlFlowReaderGetEvent(reader, 1000000, &info, &payload);
1138 if (status == MXL_STATUS_OK)
1139 {
1140 std::this_thread::yield();
1141 if (!validPattern(info, payload) || (info.index != values.size()))
1142 {
1143 failed = true;
1144 break;
1145 }
1146 values.push_back(info.timestamp);
1147 }
1148 else if (status != MXL_ERR_OUT_OF_RANGE_TOO_EARLY)
1149 {
1150 failed = true;
1151 break;
1152 }
1153 }
1154 return values;
1155 }));
1156 }
1157 start.arrive_and_wait();
1158 auto const successfulWrites = producer.get();
1159 auto results = std::vector<std::vector<std::uint64_t>>{};
1160 for (auto& future : readers)
1161 {
1162 results.push_back(future.get());
1163 }
1164 REQUIRE(successfulWrites);
1165 REQUIRE_FALSE(failed);
1166 for (auto const& values : results)
1167 {
1168 REQUIRE(values.size() == total);
1169 for (auto i = std::size_t{0}; i < total; ++i)
1170 {
1171 REQUIRE(values[i] == 4000 + i);
1172 }
1173 }
1174 fixture.checkHead(total - 1);
1175}
MXL_EXPORT mxlStatus mxlFlowReaderGetEvent(mxlFlowReader reader, uint64_t timeoutNs, mxlEventInfo *event, uint8_t **payload)
Definition flow.cpp:726
@ MXL_ERR_OUT_OF_RANGE_TOO_EARLY
Definition mxl.h:31

◆ TEST_CASE() [11/13]

TEST_CASE ( "One event writer wakes independent readers in other processes" ,
"" [events][concurrency][ipc] )
Test
One event writer wakes independent readers in other processes.

Own the pipe descriptors used to coordinate child readers with the producer.

< Read and write descriptors, each -1 until initialized.

Close any initialized descriptors during normal or failed test teardown.

Ensure a child reader cannot outlive a failed IPC test.

< Child process ID, or -1 after it has been reaped.

Kill and reap an outstanding child during test teardown.

Definition at line 1292 of file test_events.cpp.

1293{
1294 // Spawn separate processes to verify wakeups and payload visibility across shared mappings.
1296 struct Pipe
1297 {
1298 std::array<int, 2> fds{-1, -1};
1299
1301 ~Pipe()
1302 {
1303 // Close only initialized descriptors when setup or an assertion fails.
1304 for (auto fd : fds)
1305 {
1306 if (fd >= 0)
1307 {
1308 ::close(fd);
1309 }
1310 }
1311 }
1312 };
1313
1315 struct Child
1316 {
1317 pid_t pid{-1};
1318
1320 ~Child()
1321 {
1322 if (pid > 0)
1323 {
1324 // Ensure a failed assertion cannot leave a blocked child behind.
1325 ::kill(pid, SIGKILL);
1326 while (::waitpid(pid, nullptr, 0) < 0 && errno == EINTR)
1327 {
1328 }
1329 }
1330 }
1331 };
1332
1333 auto fixture = EventFixture{definitionWithRate(R"({"numerator":2560})")};
1334 auto ready = Pipe{};
1335 auto start = Pipe{};
1336 // The child readers inherit these descriptors across exec to coordinate with the parent.
1337 REQUIRE(::pipe(ready.fds.data()) == 0); // NOLINT(android-cloexec-pipe): readiness descriptor must survive exec.
1338 REQUIRE(::pipe(start.fds.data()) == 0); // NOLINT(android-cloexec-pipe): start descriptor must survive exec.
1339 auto children = std::array<Child, 2>{};
1340 auto environment = std::array<char*, 1>{nullptr};
1341 for (auto i = std::size_t{0}; i < children.size(); ++i)
1342 {
1343 auto arguments = std::array<std::string, 7>{
1344 MXL_EVENT_IPC_WORKER, fixture.domain.string(), id, "4000", "256", std::to_string(ready.fds[1]), std::to_string(start.fds[0])};
1345 auto argv = std::array<char*, 8>{};
1346 for (auto arg = std::size_t{0}; arg < arguments.size(); ++arg)
1347 {
1348 argv[arg] = arguments[arg].data();
1349 }
1350 REQUIRE(::posix_spawn(&children[i].pid, argv[0], nullptr, nullptr, argv.data(), environment.data()) == 0);
1351 }
1352 // Both child readers attach before the parent publishes.
1353 for (auto i = std::size_t{0}; i < children.size(); ++i)
1354 {
1355 auto watched = pollfd{.fd = ready.fds[0], .events = POLLIN, .revents = 0};
1356 REQUIRE(::poll(&watched, 1, 10000) == 1);
1357 auto token = char{};
1358 REQUIRE(::read(ready.fds[0], &token, 1) == 1);
1359 REQUIRE(token == 'R');
1360 }
1361 REQUIRE(::write(start.fds[1], "GG", 2) == 2);
1362 std::this_thread::sleep_for(std::chrono::milliseconds{10});
1363 for (auto i = std::uint64_t{0}; i < 256; ++i)
1364 {
1365 REQUIRE(writePattern(fixture.writer, 4000 + i) == MXL_STATUS_OK);
1366 }
1367 for (auto i = std::uint64_t{0}; i < 256; ++i)
1368 {
1369 auto info = mxlEventInfo{};
1370 auto payload = static_cast<std::uint8_t*>(nullptr);
1371 REQUIRE(mxlFlowReaderGetEventNonBlocking(fixture.reader, &info, &payload) == MXL_STATUS_OK);
1372 REQUIRE(info.timestamp == 4000 + i);
1373 REQUIRE(validPattern(info, payload));
1374 }
1375 for (auto& child : children)
1376 {
1377 auto status = int{};
1378 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
1379 auto result = pid_t{0};
1380 do
1381 {
1382 result = ::waitpid(child.pid, &status, WNOHANG);
1383 if (result != 0)
1384 {
1385 break;
1386 }
1387 std::this_thread::sleep_for(std::chrono::milliseconds{1});
1388 }
1389 while (std::chrono::steady_clock::now() < deadline);
1390 REQUIRE(result == child.pid);
1391 child.pid = -1;
1392 REQUIRE(WIFEXITED(status));
1393 REQUIRE(WEXITSTATUS(status) == 0);
1394 }
1395 fixture.checkHead(255);
1396 // Child reader teardown leaves the sole writer usable.
1397 fixture.write(9000);
1398 fixture.read(9000);
1399}
MXL_EXPORT mxlStatus mxlFlowReaderGetEventNonBlocking(mxlFlowReader reader, mxlEventInfo *event, uint8_t **payload)
Attempt to read one event entry without waiting for publication.
Definition flow.cpp:748

◆ TEST_CASE() [12/13]

TEST_CASE ( "Reopened event writers restore the last committed timestamp" ,
"" [events][timestamps] )
Test
Reopened event writers restore the last committed timestamp.

Own the temporary domain used to test writer reattachment without deleting flow files.

< Directory removed after all local mappings are destroyed.

Remove the test domain without throwing from cleanup.

Definition at line 573 of file test_events.cpp.

574{
575 // Keep flow storage alive across writer destruction to check persisted timestamp ordering.
577 struct Domain
578 {
579 std::filesystem::path path = mxl::tests::makeTempDomain();
580
582 ~Domain()
583 {
584 // Use the error-code overload so cleanup cannot throw during a failed assertion.
585 auto error = std::error_code{};
586 std::filesystem::remove_all(path, error);
587 }
588 };
589
590 auto const domain = Domain{};
591 auto manager = mxl::lib::FlowManager{domain.path};
592 auto const watcher = std::make_shared<mxl::lib::DomainWatcher>(domain.path);
593 auto const factory = mxl::lib::PosixFlowIoFactory{watcher};
594 auto const parsedFlowId = uuids::uuid::from_string(id);
595 if (!parsedFlowId.has_value())
596 {
597 FAIL("Invalid event test flow UUID.");
598 return;
599 }
600 auto const flowId = parsedFlowId.value();
601 auto const createWriter = [&](bool expectedCreated)
602 {
603 // Reopen the same storage and distinguish attachment from initial flow creation.
604 auto [created, data] = manager.createOrOpenEventFlow(flowId, definition, 4, mxlRational{20, 1}, MXL_DATA_FORMAT_GRAIN_SIZE);
605 REQUIRE(created == expectedCreated);
606 return factory.createEventFlowWriter(manager, flowId, std::move(data));
607 };
608 auto writer = createWriter(true);
609 for (auto timestamp = std::uint64_t{42}; timestamp < 48; ++timestamp)
610 {
611 auto info = mxlEventInfo{};
612 auto payload = static_cast<std::uint8_t*>(nullptr);
613 REQUIRE(writer->openEvent(&info, &payload) == MXL_STATUS_OK);
614 info.timestamp = timestamp;
615 info.eventSize = 0;
616 info.complete = 1;
617 REQUIRE(writer->commit(info) == MXL_STATUS_OK);
618 }
619 auto const before = writer->getFlowRuntimeInfo();
620 // Destroy the internal writer without the instance deleting the flow files.
621 writer.reset();
622 writer = createWriter(false);
623
624 auto info = mxlEventInfo{};
625 auto payload = static_cast<std::uint8_t*>(nullptr);
626 REQUIRE(writer->openEvent(&info, &payload) == MXL_STATUS_OK);
627 info.timestamp = 46;
628 info.eventSize = 0;
629 info.complete = 1;
630 REQUIRE(writer->commit(info) == MXL_ERR_INVALID_ARG);
631 REQUIRE(writer->getFlowRuntimeInfo().headIndex == before.headIndex);
632 REQUIRE(writer->getFlowRuntimeInfo().lastWriteTime == before.lastWriteTime);
633 info.timestamp = 47;
634 REQUIRE(writer->commit(info) == MXL_STATUS_OK);
635 REQUIRE(writer->getFlowRuntimeInfo().headIndex == before.headIndex + 1);
636}
auto const timestamp
Definition test_time.cpp:61

◆ TEST_CASE() [13/13]

TEST_CASE ( "ST 2110-41 pcap packets round trip through the event ring" ,
"" [events][pcap] )
Test
Complete and fragmented ST 2110-41 captures survive an event ring round trip. Verify each fragment's metadata and payload against the pcap, enforce offset continuity, and compare reassembled events, including word-alignment padding. The ring is sized for 50 entries per second over the default 200 ms history duration (10 slots).

Synthetic TAI epoch used to make RTP timestamp conversion deterministic.

Definition at line 325 of file test_events.cpp.

326{
327 // Run both captures against expectations that are independent of the conversion helper.
328 auto const capture = GENERATE(
329 St2110Capture{
330 "data/ST2110-41-DIT-100-Serial-ADM-compressed-25frames.pcap", 25, 0, 122, 37158, 15804720, {1328}
331 },
332 St2110Capture{"data/st2110-41-fragmented.pcap", 125, 1, 98, 4500, 894525369, {1436, 28}});
333 CAPTURE(capture.path);
334 auto fixture = EventFixture{definitionWithRate(R"({"numerator":50})")};
335 auto const datagrams = mxl::tests::readUdpDatagrams(capture.path);
336 // Count RTP fragments separately from logical events and exclude the SAP announcement.
337 auto const expectedPackets = capture.eventCount * capture.fragmentSizes.size();
338 REQUIRE(datagrams.size() == expectedPackets + capture.announcementCount);
339 REQUIRE(fixture.config.common.grainRate.numerator == 50);
340 REQUIRE(fixture.config.common.grainRate.denominator == 1);
341 REQUIRE(fixture.config.event.eventCount == 10);
342
344 constexpr auto taiEpoch = std::uint64_t{1'000'000'000'000'000'000};
345 auto packetIndex = std::size_t{};
346 auto completedEvents = std::size_t{};
347 auto announcements = std::size_t{};
348 auto originalEvent = std::vector<std::uint8_t>{};
349 auto receivedEvent = std::vector<std::uint8_t>{};
350 for (auto const& datagram : datagrams)
351 {
352 CAPTURE(packetIndex);
353 auto const rtp = std::span<std::uint8_t const>{datagram.payload};
354 if (datagram.dstPort == 9875)
355 {
356 // The fragmented capture includes a SAP announcement; it is not an RTP event.
357 auto const announcement = std::string_view{reinterpret_cast<char const*>(rtp.data()), rtp.size()};
358 REQUIRE(announcement.find(fmt::format("a=rtpmap:{} ST2110-41/48000", capture.payloadType)) != std::string_view::npos);
359 ++announcements;
360 continue;
361 }
362 REQUIRE(packetIndex < expectedPackets);
363 auto const fragmentIndex = packetIndex % capture.fragmentSizes.size();
364 auto const expectedSize = capture.fragmentSizes[fragmentIndex];
365 auto const finalFragment = fragmentIndex + 1 == capture.fragmentSizes.size();
366 auto const expectedTimestamp = std::uint64_t{capture.firstTimestamp} + (completedEvents * 1920);
367 // All fragments share one timestamp; only a new event advances it by 1,920 ticks (40 ms).
368 REQUIRE(rtp.size() == 20 + expectedSize);
369 REQUIRE(rtp[1] == capture.payloadType);
370 REQUIRE(((std::uint32_t{rtp[2]} << 8) | std::uint32_t{rtp[3]}) == capture.firstSequence + packetIndex);
371 REQUIRE(readNetworkWord(rtp.subspan<4, 4>()) == expectedTimestamp);
372 auto const itemHeader = readNetworkWord(rtp.subspan<12, 4>());
373 REQUIRE((itemHeader >> 10) == capture.dataItemType);
374 REQUIRE(((itemHeader >> 9) & 1U) == static_cast<std::uint32_t>(finalFragment));
375 REQUIRE((itemHeader & 0x1FFU) == (expectedSize / 4) + 1);
376 REQUIRE(std::uint64_t{readNetworkWord(rtp.subspan<16, 4>())} * 4 == originalEvent.size());
377
378 // Consume each entry before publishing the next to exercise slot reuse without an overrun.
379 // Comparing against packet-owned storage also avoids using the writer buffer as the oracle.
380 writeSt2110Packet(fixture.writer, rtp, taiEpoch, fixture.config.event.eventPayloadSize);
381 fixture.checkHead(packetIndex);
382 auto info = mxlEventInfo{};
383 auto buffer = static_cast<std::uint8_t*>(nullptr);
385 REQUIRE(buffer != nullptr);
387 REQUIRE(info.size == sizeof info);
388 REQUIRE(info.timestamp == taiEpoch + (expectedTimestamp * 1'000'000'000 / 48'000));
389 REQUIRE(info.flags == 0);
390 REQUIRE(info.registryType == MXL_EVENT_REGISTRY_TYPE_SMPTE);
391 auto const expectedDit = fmt::format("{:X}", capture.dataItemType);
392 REQUIRE(std::string_view{info.dataItemType, expectedDit.size()} == expectedDit);
393 REQUIRE(info.dataItemType[expectedDit.size()] == '\0');
394 REQUIRE(info.eventSize == expectedSize);
395 // The next fragment must start exactly after the bytes already assembled: no gaps or overlaps.
396 REQUIRE(info.offset == receivedEvent.size());
397 REQUIRE(info.complete == static_cast<std::uint8_t>(finalFragment));
398 auto const originalPayload = rtp.subspan(20);
399 auto const receivedPayload = std::span<std::uint8_t const>{buffer, info.eventSize};
400 REQUIRE(std::ranges::equal(receivedPayload, originalPayload));
401 originalEvent.insert(originalEvent.end(), originalPayload.begin(), originalPayload.end());
402 receivedEvent.insert(receivedEvent.end(), receivedPayload.begin(), receivedPayload.end());
403 if (info.complete)
404 {
405 // A final fragment closes one logical event. Reset both assemblies before the next one.
406 REQUIRE(receivedEvent == originalEvent);
407 originalEvent.clear();
408 receivedEvent.clear();
409 ++completedEvents;
410 }
411 ++packetIndex;
412 }
413 // Catch skipped packets, missing final fragments, and unexpected extra queue entries at EOF.
414 REQUIRE(packetIndex == expectedPackets);
415 REQUIRE(completedEvents == capture.eventCount);
416 REQUIRE(announcements == capture.announcementCount);
417 REQUIRE(originalEvent.empty());
418 REQUIRE(receivedEvent.empty());
419 auto info = mxlEventInfo{};
420 auto buffer = static_cast<std::uint8_t*>(nullptr);
422}
@ MXL_EVENT_REGISTRY_TYPE_SMPTE
SMPTE registry DIT strings without the 0x prefix.
Definition flowinfo.h:131
std::vector< UdpDatagram > readUdpDatagrams(std::filesystem::path const &path)
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.

◆ TEST_CASE_METHOD() [1/19]

TEST_CASE_METHOD ( EventFixture ,
"Event API rejects wrong handles and invalid arguments" ,
"" [events] )
Test
Event API rejects wrong handles and invalid arguments.

Definition at line 812 of file test_events.cpp.

813{
814 // Reject malformed calls and grain APIs without making the event flow unusable.
815 auto info = mxlEventInfo{};
816 auto grain = mxlGrainInfo{};
817 auto payload = static_cast<uint8_t*>(nullptr);
820 REQUIRE(mxlFlowWriterOpenEvent(nullptr, &info, &payload) == MXL_ERR_INVALID_FLOW_WRITER);
824 write(12);
825 read(12);
826}
MXL_EXPORT mxlStatus mxlFlowWriterOpenGrain(mxlFlowWriter writer, uint64_t index, mxlGrainInfo *mxlGrainInfo, uint8_t **payload)
Definition flow.cpp:446
struct mxlGrainInfo_t mxlGrainInfo
MXL_EXPORT mxlStatus mxlFlowReaderGetGrainNonBlocking(mxlFlowReader reader, uint64_t index, mxlGrainInfo *grain, uint8_t **payload)
Definition flow.cpp:392
MXL_EXPORT mxlStatus mxlFlowWriterOpenEvent(mxlFlowWriter writer, mxlEventInfo *event, uint8_t **payload)
Definition flow.cpp:664
@ MXL_ERR_INVALID_FLOW_WRITER
Definition mxl.h:33
@ MXL_ERR_INVALID_FLOW_READER
Definition mxl.h:32

◆ TEST_CASE_METHOD() [2/19]

TEST_CASE_METHOD ( EventFixture ,
"Event cancellation and invalid commits do not publish" ,
"" [events] )
Test
Event cancellation and invalid commits do not publish.

Definition at line 478 of file test_events.cpp.

479{
480 // Only a successful commit may advance the head or expose the private write buffer.
481 checkHead(MXL_UNDEFINED_INDEX);
482 auto info = mxlEventInfo{};
483 auto payload = static_cast<uint8_t*>(nullptr);
486 checkHead(MXL_UNDEFINED_INDEX);
488 info.eventSize = config.event.eventPayloadSize + 1;
489 info.timestamp = 1000;
491 checkHead(MXL_UNDEFINED_INDEX);
492 auto received = mxlEventInfo{};
495 checkHead(MXL_UNDEFINED_INDEX);
497 write(42);
498 checkHead(0);
499 read(42);
501 info.timestamp = 1000;
502 info.eventSize = 0;
503 info.complete = 1;
506 checkHead(0);
507 info.eventSize = 0;
508 info.timestamp = 43;
509 info.complete = 1;
511 checkHead(1);
513 REQUIRE(received.eventSize == 0);
514 REQUIRE(received.offset == 0);
515 REQUIRE(received.complete == 1);
516}
MXL_EXPORT mxlStatus mxlFlowWriterCommitEvent(mxlFlowWriter writer, mxlEventInfo const *event)
Definition flow.cpp:686
MXL_EXPORT mxlStatus mxlFlowWriterCancelEvent(mxlFlowWriter writer)
Cancel the open event without publishing or changing timestamp ordering.
Definition flow.cpp:708

◆ TEST_CASE_METHOD() [3/19]

TEST_CASE_METHOD ( EventFixture ,
"Event capacity rejects too little or excessive history" ,
"" [events] )
Test
Event capacity rejects too little or excessive history.

Definition at line 912 of file test_events.cpp.

913{
914 // These rates request zero, one or more than 65,536 slots with the default 200 ms history.
915 for (auto rate : {R"({"numerator":1})", R"({"numerator":5})", R"({"numerator":327685})"})
916 {
917 auto flowDef = definitionWithRate(rate);
918 auto rejected = mxlFlowWriter{};
919 REQUIRE(mxlCreateFlowWriter(producer, flowDef.c_str(), nullptr, &rejected, nullptr, nullptr) != MXL_STATUS_OK);
920 }
921}

◆ TEST_CASE_METHOD() [4/19]

TEST_CASE_METHOD ( EventFixture ,
"Event commits reject earlier timestamps without publishing" ,
"" [events][timestamps] )
Test
Event commits reject earlier timestamps without publishing.

Definition at line 519 of file test_events.cpp.

520{
521 auto timestamps = std::vector<std::uint64_t>{500};
522 SECTION("Before ring wraparound")
523 {}
524 SECTION("After ring wraparound")
525 {
526 for (auto i = std::uint64_t{1}; i < config.event.eventCount + 2; ++i)
527 {
528 timestamps.push_back(500 + i);
529 }
530 }
531 SECTION("At the maximum timestamp")
532 {
533 timestamps.front() = std::numeric_limits<std::uint64_t>::max();
534 }
535 for (auto const timestamp : timestamps)
536 {
537 write(timestamp);
538 read(timestamp);
539 }
540
541 // Compare runtime state as well as read results: rejection must not publish a phantom entry.
542 auto before = mxlFlowInfo{};
544 auto info = mxlEventInfo{};
545 auto payload = static_cast<std::uint8_t*>(nullptr);
547 info.timestamp = timestamps.back() - 1;
548 info.eventSize = 1;
549 info.complete = 1;
550 payload[0] = 0xAB;
552
553 auto after = mxlFlowInfo{};
555 REQUIRE(after.runtime.headIndex == before.runtime.headIndex);
556 REQUIRE(after.runtime.lastWriteTime == before.runtime.lastWriteTime);
557 auto received = mxlEventInfo{};
558 auto receivedPayload = static_cast<std::uint8_t*>(nullptr);
560
561 // A rejected commit retains the transaction and payload for correction.
563 info.timestamp = timestamps.back();
565 checkHead(before.runtime.headIndex + 1);
566 REQUIRE(mxlFlowReaderGetEventNonBlocking(reader, &received, &receivedPayload) == MXL_STATUS_OK);
567 REQUIRE(received.timestamp == timestamps.back());
568 REQUIRE(received.eventSize == 1);
569 REQUIRE(receivedPayload[0] == 0xAB);
570}
MXL_EXPORT mxlStatus mxlFlowReaderGetInfo(mxlFlowReader reader, mxlFlowInfo *info)
Definition flow.cpp:293
struct mxlFlowInfo_t mxlFlowInfo

◆ TEST_CASE_METHOD() [5/19]

TEST_CASE_METHOD ( EventFixture ,
"Event flow queue preserves timestamps and complete payloads" ,
"" [events] )
Test
Event flow queue preserves timestamps and complete payloads.

Definition at line 300 of file test_events.cpp.

301{
302 REQUIRE(config.common.format == MXL_DATA_FORMAT_EVENT);
303 REQUIRE(config.common.grainRate.numerator == 20);
304 REQUIRE(config.common.grainRate.denominator == 1);
305 REQUIRE(config.event.eventCount == 4);
306 REQUIRE(config.event.eventPayloadSize == MXL_DATA_FORMAT_GRAIN_SIZE);
307 auto info = mxlEventInfo{};
308 auto payload = static_cast<uint8_t*>(nullptr);
310 // Zero and duplicates are valid, but committed timestamps must not decrease.
311 for (auto timestamp : {0ULL, 0ULL, 3ULL, 500ULL, 500ULL, 900ULL})
312 {
313 write(timestamp);
314 read(timestamp);
315 }
317}

◆ TEST_CASE_METHOD() [6/19]

TEST_CASE_METHOD ( EventFixture ,
"Event indices identify queue position and skipped entries" ,
"" [events] )
Test
Queue indices reveal lag and losses independently of timestamps.

Definition at line 1645 of file test_events.cpp.

1646{
1647 write(42);
1648 auto info = mxlEventInfo{};
1649 auto payload = static_cast<std::uint8_t*>(nullptr);
1651 REQUIRE(info.index == 0);
1652 auto const previous = info.index;
1653 for (auto i = 0; i < 6; ++i)
1654 {
1655 write(42); // Identical timestamps cannot identify queue position.
1656 }
1657 auto const before = info;
1658 auto const beforePayload = payload;
1660 REQUIRE(std::memcmp(&before, &info, sizeof info) == 0);
1661 REQUIRE(payload == beforePayload);
1663 REQUIRE(info.index == 3);
1664 REQUIRE(info.index - previous - 1 == 2);
1665 auto runtime = mxlFlowRuntimeInfo{};
1667 REQUIRE(runtime.headIndex - info.index == 3);
1668 for (auto i = std::uint64_t{4}; i <= 6; ++i)
1669 {
1671 REQUIRE(info.index == i);
1672 }
1673 REQUIRE(mxlFlowWriterOpenEvent(writer, &info, &payload) == MXL_STATUS_OK);
1674 REQUIRE(info.eventSize == 0);
1675 REQUIRE(info.index == MXL_UNDEFINED_INDEX);
1676 info.timestamp = 42;
1677 info.index = 999; // Producer-supplied queue positions are ignored.
1680 REQUIRE(info.index == 7);
1681 REQUIRE(info.eventSize == 0); // Reopening must not publish bytes left by the previous event.
1682 auto const finalInfo = info;
1684 REQUIRE(std::memcmp(&finalInfo, &info, sizeof info) == 0);
1685}
MXL_EXPORT mxlStatus mxlFlowReaderGetRuntimeInfo(mxlFlowReader reader, mxlFlowRuntimeInfo *info)
Definition flow.cpp:339
struct mxlFlowRuntimeInfo_t mxlFlowRuntimeInfo

◆ TEST_CASE_METHOD() [7/19]

TEST_CASE_METHOD ( EventFixture ,
"Event overrun recovers at oldest retained event and hides open slot" ,
"" [events] )
Test
Event overrun recovers at oldest retained event and hides open slot.

Definition at line 753 of file test_events.cpp.

754{
755 // Leave the reader idle while ten writes overrun its four-slot history. Only 6..9 survive.
756 for (auto i = uint64_t{0}; i < 10; ++i)
757 {
758 write(i);
759 checkHead(i);
760 }
761 auto info = mxlEventInfo{};
762 auto payload = static_cast<uint8_t*>(nullptr);
765 checkHead(9);
766 // Scribbling on an uncommitted write must not damage the oldest still-readable slot.
767 std::memset(payload, 255, 32);
768 read(6);
769 read(7);
770 read(8);
771 read(9);
774 checkHead(9);
775 write(10);
776 checkHead(10);
777 read(10);
778}

◆ TEST_CASE_METHOD() [8/19]

TEST_CASE_METHOD ( EventFixture ,
"Event reader rejects truncated shared payload" ,
"" [events] )
Test
Event reader rejects truncated shared payload.

Definition at line 981 of file test_events.cpp.

982{
984 reader = nullptr;
985 auto const eventFile = mxl::lib::makeEventDataFilePath(mxl::lib::makeFlowDirectoryName(domain, id));
986 // Removing even the final byte makes the last slot incomplete.
987 std::filesystem::resize_file(eventFile, std::filesystem::file_size(eventFile) - 1);
988 REQUIRE(mxlCreateFlowReader(consumer, id, "", &reader) != MXL_STATUS_OK);
989}
MXL_EXPORT mxlStatus mxlReleaseFlowReader(mxlInstance instance, mxlFlowReader reader)
Definition flow.cpp:177
MXL_EXPORT mxlStatus mxlCreateFlowReader(mxlInstance instance, char const *flowId, char const *options, mxlFlowReader *reader)
Definition flow.cpp:136

◆ TEST_CASE_METHOD() [9/19]

TEST_CASE_METHOD ( EventFixture ,
"Event reader validates headers throughout the shared buffer" ,
"" [events] )
Test
Event reader validates headers throughout the shared buffer.

Definition at line 1026 of file test_events.cpp.

1027{
1029 reader = nullptr;
1030 auto const eventFile = mxl::lib::makeEventDataFilePath(mxl::lib::makeFlowDirectoryName(domain, id));
1031 auto const slotStride = mxl::lib::EventRingBuffer::slotStride(config.event.eventPayloadSize);
1032 {
1033 auto file = std::fstream{eventFile, std::ios::in | std::ios::out | std::ios::binary};
1034 REQUIRE(file.is_open());
1035 // Corrupt the last slot so validation must inspect more than the first header.
1036 file.seekp(static_cast<std::streamoff>(sizeof(mxl::lib::EventRingHeader) + ((config.event.eventCount - 1) * slotStride)));
1037 auto const invalidVersion = uint32_t{0};
1038 file.write(reinterpret_cast<char const*>(&invalidVersion), sizeof invalidVersion);
1039 REQUIRE(file.good());
1040 }
1041 REQUIRE(mxlCreateFlowReader(consumer, id, "", &reader) != MXL_STATUS_OK);
1042}
static constexpr std::size_t slotStride(std::uint32_t payloadSize) noexcept
Compute the physical stride between adjacent slots.

◆ TEST_CASE_METHOD() [10/19]

TEST_CASE_METHOD ( EventFixture ,
"Event readers have independent cursors and wake on commit" ,
"" [events] )
Test
Event readers have independent cursors and wake on commit.

Definition at line 781 of file test_events.cpp.

782{
783 // A second instance provides an independent cursor; both readers must receive event 100.
784 auto other = mxlCreateInstance(domain.c_str(), "{}");
785 REQUIRE(other);
786 auto otherReader = mxlFlowReader{};
787 REQUIRE(mxlCreateFlowReader(other, id, "", &otherReader) == MXL_STATUS_OK);
788 auto future = std::async(std::launch::async,
789 [&]
790 {
791 // Wait on an empty queue so the next commit must wake the blocked reader.
792 auto info = mxlEventInfo{};
793 auto payload = static_cast<uint8_t*>(nullptr);
794 auto status = mxlFlowReaderGetEvent(reader, 1000000000, &info, &payload);
795 return std::pair{status, info.timestamp};
796 });
797 std::this_thread::sleep_for(std::chrono::milliseconds(10));
798 write(100);
799 auto result = future.get();
800 REQUIRE(result.first == MXL_STATUS_OK);
801 REQUIRE(result.second == 100);
802 auto info = mxlEventInfo{};
803 auto payload = static_cast<uint8_t*>(nullptr);
804 REQUIRE(mxlFlowReaderGetEventNonBlocking(otherReader, &info, &payload) == MXL_STATUS_OK);
805 REQUIRE(info.timestamp == 100);
807 REQUIRE(mxlReleaseFlowReader(other, otherReader) == MXL_STATUS_OK);
809}
struct mxlFlowReader_t * mxlFlowReader
Definition flow.h:205

◆ TEST_CASE_METHOD() [11/19]

TEST_CASE_METHOD ( EventFixture ,
"Event readers never expose torn payloads during concurrent wraparound" ,
"" [events][concurrency] )
Test
Event readers never expose torn payloads during concurrent wraparound.

Definition at line 1217 of file test_events.cpp.

1218{
1219 // Independent-reader stress with a tiny ring: overruns and empty reads are expected.
1220 // Every successful read must still contain matching metadata and timestamp-derived bytes.
1221 auto consumers = std::vector<std::unique_ptr<IndependentEventReader>>{};
1222 for (auto i = 0; i < 2; ++i)
1223 {
1224 consumers.push_back(std::make_unique<IndependentEventReader>(domain));
1225 }
1226 auto start = std::barrier{4};
1227 auto finished = std::atomic<bool>{false};
1228 auto failures = std::atomic<unsigned>{0};
1229 auto snapshots = std::atomic<unsigned>{0};
1230 auto workers = std::vector<std::future<void>>{};
1231 workers.emplace_back(std::async(std::launch::async,
1232 [&]
1233 {
1234 // Keep wrapping the small ring to race publication against readers copying payloads.
1235 start.arrive_and_wait();
1236 for (auto i = std::uint64_t{0}; i < 6000; ++i)
1237 {
1238 if (writePattern(writer, i) != MXL_STATUS_OK)
1239 {
1240 ++failures;
1241 break;
1242 }
1243 }
1244 finished = true;
1245 }));
1246 for (auto thread = unsigned{0}; thread < 2; ++thread)
1247 {
1248 workers.emplace_back(std::async(std::launch::async,
1249 [&, eventReader = consumers[thread]->reader]
1250 {
1251 // Accept missed entries but reject any successful read containing inconsistent bytes.
1252 start.arrive_and_wait();
1253 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{10};
1254 do
1255 {
1256 auto info = mxlEventInfo{};
1257 auto payload = static_cast<std::uint8_t*>(nullptr);
1258 auto const status = mxlFlowReaderGetEvent(eventReader, 1000000, &info, &payload);
1259 if (status == MXL_STATUS_OK)
1260 {
1261 std::this_thread::yield();
1262 if (!validPattern(info, payload))
1263 {
1264 ++failures;
1265 }
1266 ++snapshots;
1267 }
1268 else if (status != MXL_ERR_OUT_OF_RANGE_TOO_EARLY && status != MXL_ERR_OUT_OF_RANGE_TOO_LATE)
1269 {
1270 ++failures;
1271 }
1272 if (finished && status == MXL_ERR_OUT_OF_RANGE_TOO_EARLY)
1273 {
1274 return;
1275 }
1276 }
1277 while (std::chrono::steady_clock::now() < deadline);
1278 ++failures;
1279 }));
1280 }
1281 start.arrive_and_wait();
1282 for (auto& future : workers)
1283 {
1284 future.get();
1285 }
1286 REQUIRE(failures == 0);
1287 REQUIRE(snapshots > 0);
1288 checkHead(5999);
1289}

◆ TEST_CASE_METHOD() [12/19]

TEST_CASE_METHOD ( EventFixture ,
"Event slots occupy one shared memory file" ,
"" [events] )
Test
Event slots occupy one shared memory file.

Definition at line 992 of file test_events.cpp.

993{
994 auto const flowDirectory = mxl::lib::makeFlowDirectoryName(domain, id);
995 auto const eventFile = mxl::lib::makeEventDataFilePath(flowDirectory);
996 REQUIRE(std::filesystem::is_regular_file(eventFile));
997 REQUIRE(config.event.eventPayloadSize == 4096);
998 // One 4 KiB ring header precedes slots containing 768 bytes of internal metadata plus payload.
999 REQUIRE(std::filesystem::file_size(eventFile) == 4096 + (config.event.eventCount * 4864));
1000 REQUIRE(std::filesystem::file_size(eventFile) == mxl::lib::EventRingBuffer::bufferSize(config.event.eventCount, config.event.eventPayloadSize));
1001 REQUIRE_FALSE(std::filesystem::exists(flowDirectory / "grains"));
1002 REQUIRE_FALSE(std::filesystem::exists(flowDirectory / "producer"));
1003
1004 for (auto i = uint64_t{0}; i < 6; ++i)
1005 {
1006 auto info = mxlEventInfo{};
1007 auto payload = static_cast<uint8_t*>(nullptr);
1008 REQUIRE(mxlFlowWriterOpenEvent(writer, &info, &payload) == MXL_STATUS_OK);
1009 info.timestamp = i;
1010 info.eventSize = sizeof i;
1011 info.complete = 1;
1012 std::memcpy(payload, &i, sizeof i);
1014 }
1015
1016 auto info = mxlEventInfo{};
1017 auto payload = static_cast<uint8_t*>(nullptr);
1019 read(2);
1020 read(3);
1021 read(4);
1022 read(5);
1023}
static std::size_t bufferSize(std::uint32_t count, std::uint32_t payloadSize)
Validate geometry and compute the complete mapping length.

◆ TEST_CASE_METHOD() [13/19]

TEST_CASE_METHOD ( EventFixture ,
"Event snapshots survive overwrite and reads from independent readers" ,
"" [events][concurrency] )
Test
Event snapshots survive overwrite and reads from independent readers.

Definition at line 1178 of file test_events.cpp.

1179{
1180 // Retain this thread's snapshot while an independent reader repeatedly reads and overwrites the ring.
1181 REQUIRE(writePattern(writer, 4095) == MXL_STATUS_OK);
1182 auto info = mxlEventInfo{};
1183 auto payload = static_cast<std::uint8_t*>(nullptr);
1185 auto other = IndependentEventReader{domain};
1186 auto future = std::async(std::launch::async,
1187 [&]
1188 {
1189 // Overwrite the ring repeatedly while the originating thread retains its earlier snapshot.
1190 auto initialInfo = mxlEventInfo{};
1191 auto initialPayload = static_cast<std::uint8_t*>(nullptr);
1192 if (mxlFlowReaderGetEventNonBlocking(other.reader, &initialInfo, &initialPayload) != MXL_STATUS_OK)
1193 {
1194 return false;
1195 }
1196 for (auto i = std::uint64_t{0}; i < 100; ++i)
1197 {
1198 if (writePattern(writer, 4096 + i) != MXL_STATUS_OK)
1199 {
1200 return false;
1201 }
1202 auto otherInfo = mxlEventInfo{};
1203 auto otherPayload = static_cast<std::uint8_t*>(nullptr);
1204 if (mxlFlowReaderGetEventNonBlocking(other.reader, &otherInfo, &otherPayload) != MXL_STATUS_OK ||
1205 !validPattern(otherInfo, otherPayload))
1206 {
1207 return false;
1208 }
1209 }
1210 return true;
1211 });
1212 REQUIRE(future.get());
1213 REQUIRE(validPattern(info, payload));
1214}

◆ TEST_CASE_METHOD() [14/19]

TEST_CASE_METHOD ( EventFixture ,
"Fragment offset mismatches expose discontinuities to the consumer" ,
"" [events][fragmentation] )
Test
Fragment offset mismatches expose discontinuities to the consumer.

Definition at line 704 of file test_events.cpp.

705{
706 auto const firstBytes = std::vector<std::uint8_t>{0x10, 0x20, 0x30, 0x40, 0x50};
707 auto const secondBytes = std::vector<std::uint8_t>{0x60, 0x70, 0x80};
708 constexpr auto timestamp = std::uint64_t{123456789};
709 auto incorrectOffset = std::uint32_t{};
710 SECTION("Gap in the payload")
711 {
712 incorrectOffset = static_cast<std::uint32_t>(firstBytes.size() + 1);
713 }
714 SECTION("Overlap with the previous fragment")
715 {
716 incorrectOffset = static_cast<std::uint32_t>(firstBytes.size() - 1);
717 }
718 SECTION("Unexpected restart at offset zero")
719 {
720 incorrectOffset = 0;
721 }
722 writeFragment(timestamp, firstBytes, 0, false);
723 writeFragment(timestamp, secondBytes, incorrectOffset, true);
724
725 auto const [first, firstPayload] = readFragment();
726 REQUIRE(first.timestamp == timestamp);
727 REQUIRE(first.offset == 0);
728 REQUIRE(first.complete == 0);
729 REQUIRE(first.eventSize == firstBytes.size());
730 REQUIRE(firstPayload == firstBytes);
731
732 auto const [second, secondPayload] = readFragment();
733 REQUIRE(second.timestamp == first.timestamp);
734 REQUIRE(second.offset == incorrectOffset);
735 REQUIRE(second.complete == 1);
736 REQUIRE(second.eventSize == secondBytes.size());
737 REQUIRE(secondPayload == secondBytes);
738
739 // The consumer must validate offset continuity before accepting a completion flag.
740 auto const expectedOffset = first.offset + first.eventSize;
741 REQUIRE(expectedOffset == 5);
742 auto const discontinuity = second.offset != expectedOffset;
743 REQUIRE(discontinuity);
744 auto const validCompletion = !discontinuity && second.complete == 1;
745 REQUIRE_FALSE(validCompletion);
746
747 // Discarding the interrupted assembly does not prevent subsequent delivery.
748 write(timestamp + 1);
749 read(timestamp + 1);
750}

◆ TEST_CASE_METHOD() [15/19]

TEST_CASE_METHOD ( EventFixture ,
"Late event reader starts at oldest retained event and detects deleted flow" ,
"" [events] )
Test
Late event reader starts at oldest retained event and detects deleted flow.

Definition at line 943 of file test_events.cpp.

944{
945 // Reattach after the four-slot ring has wrapped; the new cursor starts at retained entry 2.
946 for (auto i = uint64_t{0}; i < 6; ++i)
947 {
948 write(i);
949 }
951 reader = nullptr;
952 REQUIRE(mxlCreateFlowReader(consumer, id, "", &reader) == MXL_STATUS_OK);
953 read(2);
954 read(3);
955 read(4);
956 read(5);
958 writer = nullptr;
959 auto info = mxlEventInfo{};
960 auto payload = static_cast<uint8_t*>(nullptr);
962}
MXL_EXPORT mxlStatus mxlReleaseFlowWriter(mxlInstance instance, mxlFlowWriter writer)
Definition flow.cpp:262

◆ TEST_CASE_METHOD() [16/19]

TEST_CASE_METHOD ( EventFixture ,
"Opening an event initializes every metadata field" ,
"" [events] )
Test
Opening an event initializes every metadata field.

Definition at line 425 of file test_events.cpp.

426{
427 auto info = mxlEventInfo{};
428 auto payload = static_cast<std::uint8_t*>(nullptr);
429 // Check the initial open, reopening after cancel, and reopening after commit.
430 for (auto attempt = unsigned{0}; attempt < 3; ++attempt)
431 {
432 CAPTURE(attempt);
433 // Poison all fields first so initialization cannot pass by relying on zeroed caller storage.
434 std::memset(&info, 0xA5, sizeof info);
436 REQUIRE(payload != nullptr);
438 REQUIRE(info.size == sizeof info);
439 REQUIRE(info.timestamp == 0);
440 REQUIRE(info.flags == 0);
441 REQUIRE(info.registryType == MXL_EVENT_REGISTRY_TYPE_MXL);
442 REQUIRE(std::ranges::all_of(info.dataItemType,
443 [](auto value) noexcept
444 {
445 // Every byte must be reset, including bytes that held metadata from a previous open.
446 return value == 0;
447 }));
448 REQUIRE(info.eventSize == 0);
449 REQUIRE(info.index == MXL_UNDEFINED_INDEX);
450 REQUIRE(info.offset == 0);
451 REQUIRE(info.complete == 1);
452 REQUIRE(std::ranges::all_of(info.reserved,
453 [](auto value) noexcept
454 {
455 // Every byte must be reset, including bytes that held metadata from a previous open.
456 return value == 0;
457 }));
458
459 info.timestamp = 42;
460 info.registryType = MXL_EVENT_REGISTRY_TYPE_SMPTE;
461 std::strcpy(info.dataItemType, "010203");
462 info.eventSize = 1;
463 info.complete = 0;
464 payload[0] = 0xAB;
465 if (attempt == 1)
466 {
468 }
469 else
470 {
472 }
473 }
474 checkHead(0);
475}
@ MXL_EVENT_REGISTRY_TYPE_MXL
Namespaced application DIT strings, such as x-mxl:example.
Definition flowinfo.h:130

◆ TEST_CASE_METHOD() [17/19]

TEST_CASE_METHOD ( EventFixture ,
"Repeated event writer acquisition shares publication state" ,
"" [events] )
Test
Repeated event writer acquisition shares publication state.

Definition at line 965 of file test_events.cpp.

966{
967 // Releasing a second reference must leave the original writer and its publication state intact.
968 auto same = mxlFlowWriter{};
969 auto created = true;
970 REQUIRE(mxlCreateFlowWriter(producer, definition, "", &same, nullptr, &created) == MXL_STATUS_OK);
971 REQUIRE_FALSE(created);
972 REQUIRE(same == writer);
973 write(1);
974 REQUIRE(mxlReleaseFlowWriter(producer, same) == MXL_STATUS_OK);
975 read(1);
976 write(2);
977 read(2);
978}

◆ TEST_CASE_METHOD() [18/19]

TEST_CASE_METHOD ( EventFixture ,
"Two event fragments preserve continuity and reassemble across ring wrap" ,
"" [events][fragmentation] )
Test
Two event fragments preserve continuity and reassemble across ring wrap.

Definition at line 656 of file test_events.cpp.

657{
658 // Put the first fragment in the final physical slot and the second in slot zero.
659 for (auto i = std::uint64_t{0}; i < config.event.eventCount - 1; ++i)
660 {
661 write(i);
662 read(i);
663 }
664 auto message = std::vector<std::uint8_t>{};
665 // Exceed one slot's payload capacity so the message necessarily needs two entries.
666 message.resize(config.event.eventPayloadSize + 13);
667 for (auto i = std::size_t{0}; i < message.size(); ++i)
668 {
669 message[i] = static_cast<std::uint8_t>((i * 37) + 11);
670 }
671 constexpr auto timestamp = std::uint64_t{123456789};
672 auto const split = config.event.eventPayloadSize;
673 auto const bytes = std::span<std::uint8_t const>{message};
674 writeFragment(timestamp, bytes.first(split), 0, false);
675 writeFragment(timestamp, bytes.subspan(split), split, true);
676
677 auto const [first, firstPayload] = readFragment();
678 REQUIRE(first.timestamp == timestamp);
679 REQUIRE(first.offset == 0);
680 REQUIRE(first.complete == 0);
681 REQUIRE(first.eventSize == split);
682 REQUIRE(std::equal(firstPayload.begin(), firstPayload.end(), bytes.begin()));
683
684 auto const [second, secondPayload] = readFragment();
685 REQUIRE(second.timestamp == timestamp);
686 REQUIRE(second.offset == split);
687 REQUIRE(second.offset == first.offset + first.eventSize);
688 REQUIRE(second.complete == 1);
689 REQUIRE(second.eventSize == 13);
690 REQUIRE(std::equal(secondPayload.begin(), secondPayload.end(), bytes.begin() + split));
691
692 auto assembled = std::vector<std::uint8_t>{firstPayload};
693 assembled.insert(assembled.end(), secondPayload.begin(), secondPayload.end());
694 REQUIRE(assembled.size() == first.eventSize + second.eventSize);
695 REQUIRE(assembled == message);
696 checkHead(config.event.eventCount);
697
698 // Completion ends the sequence; the following independent event starts at zero again.
699 write(timestamp + 1);
700 read(timestamp + 1);
701}

◆ TEST_CASE_METHOD() [19/19]

TEST_CASE_METHOD ( EventFixture ,
"Unfragmented events have zero offset and are complete" ,
"" [events][fragmentation] )
Test
Unfragmented events have zero offset and are complete.

Definition at line 639 of file test_events.cpp.

640{
641 auto const message = std::vector<std::uint8_t>{0x00, 0x12, 0xFF, 0x34, 0x56};
642 // Independent events always start at zero, regardless of the preceding event's size.
643 for (auto const timestamp : {std::uint64_t{1234}, std::uint64_t{5678}})
644 {
645 writeFragment(timestamp, message, 0, true);
646 auto const [info, payload] = readFragment();
647 REQUIRE(info.timestamp == timestamp);
648 REQUIRE(info.offset == 0);
649 REQUIRE(info.complete == 1);
650 REQUIRE(info.eventSize == message.size());
651 REQUIRE(payload == message);
652 }
653}