24#include <catch2/catch_test_macros.hpp>
25#include <catch2/generators/catch_generators.hpp>
26#include <fmt/format.h>
41 constexpr auto id =
"cabbc00d-3860-4438-bc48-8ebdfe67305e";
43 constexpr auto definition = R
"({"id":"cabbc00d-3860-4438-bc48-8ebdfe67305e",
44 "format":"urn:x-nmos:format:event","label":"Events",
45 "grain_rate":{"numerator":20},
46 "tags":{"urn:x-nmos:tag:grouphint/v1.0":["Test:Events"]}})";
53 std::string definitionWithRate(
char const* grainRate)
56 auto flow = picojson::value{};
57 auto rate = picojson::value{};
58 REQUIRE(picojson::parse(flow, definition).empty());
60 flow.get<picojson::object>()[
"grain_rate"] =
rate;
61 return flow.serialize();
65 struct IndependentEventReader
70 explicit IndependentEventReader(std::filesystem::path
const& domain)
77 ~IndependentEventReader()
99 EventFixture(std::string
const&
flowDef = definition,
char const* domainOptions =
nullptr)
106 options << domainOptions;
125 std::filesystem::remove_all(domain);
136 auto payload =
static_cast<uint8_t*
>(
nullptr);
155 auto payload =
static_cast<uint8_t*
>(
nullptr);
161 auto value = uint64_t{};
162 std::memcpy(&value, payload,
sizeof value);
173 void writeFragment(std::uint64_t
timestamp, std::span<std::uint8_t const> bytes, std::uint32_t offset,
bool complete)
177 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
179 REQUIRE(bytes.size() <= config.event.eventPayloadSize);
182 std::strcpy(info.dataItemType,
"010203");
183 info.eventSize =
static_cast<std::uint32_t
>(bytes.size());
184 info.offset = offset;
185 info.complete = complete ? 1 : 0;
188 std::memcpy(payload, bytes.data(), bytes.size());
194 std::pair<mxlEventInfo, std::vector<std::uint8_t>> readFragment()
198 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
201 REQUIRE(info.size ==
sizeof info);
202 REQUIRE(info.eventSize <= config.event.eventPayloadSize);
204 REQUIRE(std::strcmp(info.dataItemType,
"010203") == 0);
206 info, std::vector<std::uint8_t>{payload, payload + info.eventSize}
214 void checkHead(uint64_t head)
219 REQUIRE(runtime.headIndex == head);
227 std::size_t eventCount{};
228 std::size_t announcementCount{};
229 std::uint8_t payloadType{};
230 std::uint16_t firstSequence{};
231 std::uint32_t firstTimestamp{};
232 std::vector<std::uint32_t> fragmentSizes{};
233 std::uint32_t dataItemType{0x100};
241 std::uint32_t readNetworkWord(std::span<std::uint8_t const, 4> bytes)
noexcept
244 return (std::uint32_t{bytes[0]} << 24) | (std::uint32_t{bytes[1]} << 16) | (std::uint32_t{bytes[2]} << 8) | std::uint32_t{bytes[3]};
262 void writeSt2110Packet(
mxlFlowWriter writer, std::span<std::uint8_t const> rtp, std::uint64_t taiEpoch, std::uint32_t capacity)
269 auto const timestamp = readNetworkWord(rtp.subspan<4, 4>());
271 auto const itemHeader = readNetworkWord(rtp.subspan<12, 4>());
272 auto const lengthWords = itemHeader & 0x1FFU;
274 REQUIRE(rtp.size() == 16 + (std::size_t{lengthWords} * 4));
275 auto const offsetWords = readNetworkWord(rtp.subspan<16, 4>());
276 REQUIRE(offsetWords <= std::numeric_limits<std::uint32_t>::max() / 4);
277 auto const data = rtp.subspan(20);
281 auto buffer =
static_cast<std::uint8_t*
>(
nullptr);
284 REQUIRE(data.size() <= capacity);
285 info.timestamp = taiEpoch + (std::uint64_t{
timestamp} * 1'000'000'000 / 48'000);
287 auto const dit = fmt::format(
"{:X}", itemHeader >> 10);
288 REQUIRE(dit.size() <
sizeof info.dataItemType);
289 std::memcpy(info.dataItemType, dit.c_str(), dit.size() + 1);
290 info.eventSize =
static_cast<std::uint32_t
>(data.size());
292 info.offset = offsetWords * 4;
293 info.complete =
static_cast<std::uint8_t
>((itemHeader >> 9) & 1U);
294 std::memcpy(
buffer, data.data(), data.size());
300TEST_CASE_METHOD(EventFixture,
"Event flow queue preserves timestamps and complete payloads",
"[events]")
308 auto payload =
static_cast<uint8_t*
>(
nullptr);
311 for (
auto timestamp : {0ULL, 0ULL, 3ULL, 500ULL, 500ULL, 900ULL})
325TEST_CASE(
"ST 2110-41 pcap packets round trip through the event ring",
"[events][pcap]")
328 auto const capture = GENERATE(
330 "data/ST2110-41-DIT-100-Serial-ADM-compressed-25frames.pcap", 25, 0, 122, 37158, 15804720, {1328}
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})")};
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);
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)
352 CAPTURE(packetIndex);
353 auto const rtp = std::span<std::uint8_t const>{datagram.payload};
354 if (datagram.dstPort == 9875)
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);
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);
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());
380 writeSt2110Packet(fixture.writer, rtp, taiEpoch, fixture.config.event.eventPayloadSize);
381 fixture.checkHead(packetIndex);
383 auto buffer =
static_cast<std::uint8_t*
>(
nullptr);
387 REQUIRE(info.size ==
sizeof info);
388 REQUIRE(info.timestamp == taiEpoch + (expectedTimestamp * 1'000'000'000 / 48'000));
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);
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());
406 REQUIRE(receivedEvent == originalEvent);
407 originalEvent.clear();
408 receivedEvent.clear();
414 REQUIRE(packetIndex == expectedPackets);
415 REQUIRE(completedEvents == capture.eventCount);
416 REQUIRE(announcements == capture.announcementCount);
417 REQUIRE(originalEvent.empty());
418 REQUIRE(receivedEvent.empty());
420 auto buffer =
static_cast<std::uint8_t*
>(
nullptr);
425TEST_CASE_METHOD(EventFixture,
"Opening an event initializes every metadata field",
"[events]")
428 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
430 for (
auto attempt =
unsigned{0}; attempt < 3; ++attempt)
434 std::memset(&info, 0xA5,
sizeof info);
438 REQUIRE(info.size ==
sizeof info);
442 REQUIRE(std::ranges::all_of(info.dataItemType,
443 [](
auto value)
noexcept
452 REQUIRE(std::ranges::all_of(info.reserved,
453 [](
auto value)
noexcept
461 std::strcpy(info.dataItemType,
"010203");
478TEST_CASE_METHOD(EventFixture,
"Event cancellation and invalid commits do not publish",
"[events]")
483 auto payload =
static_cast<uint8_t*
>(
nullptr);
489 info.timestamp = 1000;
501 info.timestamp = 1000;
513 REQUIRE(received.eventSize == 0);
515 REQUIRE(received.complete == 1);
519TEST_CASE_METHOD(EventFixture,
"Event commits reject earlier timestamps without publishing",
"[events][timestamps]")
521 auto timestamps = std::vector<std::uint64_t>{500};
522 SECTION(
"Before ring wraparound")
524 SECTION(
"After ring wraparound")
528 timestamps.push_back(500 + i);
531 SECTION(
"At the maximum timestamp")
533 timestamps.front() = std::numeric_limits<std::uint64_t>::max();
545 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
547 info.timestamp = timestamps.back() - 1;
555 REQUIRE(after.runtime.headIndex == before.runtime.headIndex);
556 REQUIRE(after.runtime.lastWriteTime == before.runtime.lastWriteTime);
558 auto receivedPayload =
static_cast<std::uint8_t*
>(
nullptr);
563 info.timestamp = timestamps.back();
565 checkHead(before.runtime.headIndex + 1);
567 REQUIRE(received.timestamp == timestamps.back());
568 REQUIRE(received.eventSize == 1);
569 REQUIRE(receivedPayload[0] == 0xAB);
573TEST_CASE(
"Reopened event writers restore the last committed timestamp",
"[events][timestamps]")
585 auto error = std::error_code{};
586 std::filesystem::remove_all(path, error);
590 auto const domain = Domain{};
592 auto const watcher = std::make_shared<mxl::lib::DomainWatcher>(domain.path);
594 auto const parsedFlowId = uuids::uuid::from_string(
id);
595 if (!parsedFlowId.has_value())
597 FAIL(
"Invalid event test flow UUID.");
600 auto const flowId = parsedFlowId.value();
601 auto const createWriter = [&](
bool expectedCreated)
605 REQUIRE(created == expectedCreated);
606 return factory.createEventFlowWriter(manager,
flowId, std::move(data));
608 auto writer = createWriter(
true);
612 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
619 auto const before =
writer->getFlowRuntimeInfo();
622 writer = createWriter(
false);
625 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
631 REQUIRE(
writer->getFlowRuntimeInfo().headIndex == before.headIndex);
632 REQUIRE(
writer->getFlowRuntimeInfo().lastWriteTime == before.lastWriteTime);
635 REQUIRE(
writer->getFlowRuntimeInfo().headIndex == before.headIndex + 1);
639TEST_CASE_METHOD(EventFixture,
"Unfragmented events have zero offset and are complete",
"[events][fragmentation]")
641 auto const message = std::vector<std::uint8_t>{0x00, 0x12, 0xFF, 0x34, 0x56};
643 for (
auto const timestamp : {std::uint64_t{1234}, std::uint64_t{5678}})
645 writeFragment(
timestamp, message, 0,
true);
646 auto const [info, payload] = readFragment();
650 REQUIRE(info.eventSize == message.size());
656TEST_CASE_METHOD(EventFixture,
"Two event fragments preserve continuity and reassemble across ring wrap",
"[events][fragmentation]")
664 auto message = std::vector<std::uint8_t>{};
667 for (
auto i = std::size_t{0}; i < message.size(); ++i)
669 message[i] =
static_cast<std::uint8_t
>((i * 37) + 11);
671 constexpr auto timestamp = std::uint64_t{123456789};
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);
677 auto const [first, firstPayload] = readFragment();
681 REQUIRE(first.eventSize == split);
682 REQUIRE(std::equal(firstPayload.begin(), firstPayload.end(), bytes.begin()));
684 auto const [second, secondPayload] = readFragment();
686 REQUIRE(second.offset == split);
687 REQUIRE(second.offset == first.offset + first.eventSize);
689 REQUIRE(second.eventSize == 13);
690 REQUIRE(std::equal(secondPayload.begin(), secondPayload.end(), bytes.begin() + split));
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);
704TEST_CASE_METHOD(EventFixture,
"Fragment offset mismatches expose discontinuities to the consumer",
"[events][fragmentation]")
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")
712 incorrectOffset =
static_cast<std::uint32_t
>(firstBytes.size() + 1);
714 SECTION(
"Overlap with the previous fragment")
716 incorrectOffset =
static_cast<std::uint32_t
>(firstBytes.size() - 1);
718 SECTION(
"Unexpected restart at offset zero")
722 writeFragment(
timestamp, firstBytes, 0,
false);
723 writeFragment(
timestamp, secondBytes, incorrectOffset,
true);
725 auto const [first, firstPayload] = readFragment();
729 REQUIRE(first.eventSize == firstBytes.size());
730 REQUIRE(firstPayload == firstBytes);
732 auto const [second, secondPayload] = readFragment();
733 REQUIRE(second.timestamp == first.timestamp);
734 REQUIRE(second.offset == incorrectOffset);
736 REQUIRE(second.eventSize == secondBytes.size());
737 REQUIRE(secondPayload == secondBytes);
740 auto const expectedOffset = first.offset + first.eventSize;
742 auto const discontinuity = second.offset != expectedOffset;
744 auto const validCompletion = !discontinuity && second.complete == 1;
745 REQUIRE_FALSE(validCompletion);
753TEST_CASE_METHOD(EventFixture,
"Event overrun recovers at oldest retained event and hides open slot",
"[events]")
756 for (
auto i = uint64_t{0}; i < 10; ++i)
762 auto payload =
static_cast<uint8_t*
>(
nullptr);
767 std::memset(payload, 255, 32);
781TEST_CASE_METHOD(EventFixture,
"Event readers have independent cursors and wake on commit",
"[events]")
788 auto future = std::async(std::launch::async,
793 auto payload =
static_cast<uint8_t*
>(
nullptr);
795 return std::pair{status, info.timestamp};
797 std::this_thread::sleep_for(std::chrono::milliseconds(10));
799 auto result = future.get();
803 auto payload =
static_cast<uint8_t*
>(
nullptr);
805 REQUIRE(info.timestamp == 100);
812TEST_CASE_METHOD(EventFixture,
"Event API rejects wrong handles and invalid arguments",
"[events]")
817 auto payload =
static_cast<uint8_t*
>(
nullptr);
829TEST_CASE(
"Event parser requires a positive grain rate",
"[events]")
837 REQUIRE(parser.getGrainRate().numerator == 20);
838 REQUIRE(parser.getGrainRate().denominator == 1);
840 REQUIRE_THROWS(parser.getTotalPayloadSlices());
841 for (
auto rate : {R
"({"numerator":0})", R"({"numerator":-1})", R"({"numerator":20,"denominator":0})"})
847 auto flow = picojson::value{};
848 REQUIRE(picojson::parse(flow, definition).empty());
849 flow.get<picojson::object>().erase(
"grain_rate");
854TEST_CASE(
"Event group hints validate names roles and scopes",
"[events][parser]")
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"];
861 for (
auto const hint : {
"group:role",
"group:role:device",
"group:role:node"})
864 hints = picojson::value{picojson::array{picojson::value{std::string{hint}}}};
867 for (
auto const hint : {
"",
":",
"group",
"group:",
":role",
"group::node",
"group:role:",
"group:role:invalid",
"group:role:node:extra"})
870 hints = picojson::value{picojson::array{picojson::value{std::string{hint}}}};
873 hints = picojson::value{picojson::array{}};
875 hints = picojson::value{picojson::array{picojson::value{
true}}};
880TEST_CASE(
"Event capacity follows grain rate and history duration",
"[events]")
882 SECTION(
"A different rate changes capacity")
885 auto fixture = EventFixture{definitionWithRate(R
"({"numerator":50})")};
886 REQUIRE(fixture.config.event.eventCount == 10);
887 REQUIRE(fixture.config.common.grainRate.numerator == 50);
889 SECTION("Fractional rates use integer division")
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);
897 SECTION("Large rational components do not overflow intermediate products")
900 auto fixture = EventFixture{definitionWithRate(R
"({"numerator":2000000000001,"denominator":100000000000})")};
901 REQUIRE(fixture.config.event.eventCount == 4);
903 SECTION("Domain history duration changes capacity")
906 auto fixture = EventFixture{definition, R
"({"urn:x-mxl:option:history_duration/v1.0":500000000})"};
907 REQUIRE(fixture.config.event.eventCount == 10);
912TEST_CASE_METHOD(EventFixture,
"Event capacity rejects too little or excessive history",
"[events]")
915 for (
auto rate : {R
"({"numerator":1})", R"({"numerator":5})", R"({"numerator":327685})"})
924TEST_CASE(
"Event capacity rejects overflow before narrowing",
"[events]")
929 options << R
"({"urn:x-mxl:option:history_duration/v1.0":9223372036854775808})";
935 auto flowDef = definitionWithRate(R
"({"numerator":4000000000000000512,"denominator":2000000000})");
938 std::filesystem::remove_all(domain);
943TEST_CASE_METHOD(EventFixture,
"Late event reader starts at oldest retained event and detects deleted flow",
"[events]")
946 for (
auto i = uint64_t{0}; i < 6; ++i)
960 auto payload =
static_cast<uint8_t*
>(
nullptr);
965TEST_CASE_METHOD(EventFixture,
"Repeated event writer acquisition shares publication state",
"[events]")
971 REQUIRE_FALSE(created);
987 std::filesystem::resize_file(eventFile, std::filesystem::file_size(eventFile) - 1);
996 REQUIRE(std::filesystem::is_regular_file(eventFile));
1001 REQUIRE_FALSE(std::filesystem::exists(flowDirectory /
"grains"));
1002 REQUIRE_FALSE(std::filesystem::exists(flowDirectory /
"producer"));
1004 for (
auto i = uint64_t{0}; i < 6; ++i)
1007 auto payload =
static_cast<uint8_t*
>(
nullptr);
1010 info.eventSize =
sizeof i;
1012 std::memcpy(payload, &i,
sizeof i);
1017 auto payload =
static_cast<uint8_t*
>(
nullptr);
1026TEST_CASE_METHOD(EventFixture,
"Event reader validates headers throughout the shared buffer",
"[events]")
1033 auto file = std::fstream{eventFile, std::ios::in | std::ios::out | std::ios::binary};
1037 auto const invalidVersion = uint32_t{0};
1038 file.write(
reinterpret_cast<char const*
>(&invalidVersion),
sizeof invalidVersion);
1056 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1062 info.timestamp = value;
1066 for (
auto i = std::uint32_t{0}; i < info.eventSize; ++i)
1068 payload[i] =
static_cast<std::uint8_t
>((value * 29) + (std::uint64_t{i} * 7));
1079 bool validPattern(
mxlEventInfo const& info, std::uint8_t
const* payload)
1087 for (
auto i = std::uint32_t{0}; i < info.
eventSize; ++i)
1089 if (payload[i] !=
static_cast<std::uint8_t
>((info.
timestamp * 29) + (std::uint64_t{i} * 7)))
1099TEST_CASE(
"Independent event readers each consume every publication",
"[events][concurrency]")
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)
1106 consumers.push_back(std::make_unique<IndependentEventReader>(fixture.domain));
1108 auto start = std::barrier{6};
1109 auto failed = std::atomic<bool>{
false};
1110 auto producer = std::async(std::launch::async,
1113 start.arrive_and_wait();
1114 for (
auto i = std::size_t{0}; i < total; ++i)
1116 if (writePattern(fixture.writer, 4000 + i) !=
MXL_STATUS_OK)
1124 auto readers = std::vector<std::future<std::vector<std::uint64_t>>>{};
1125 for (
auto const& consumer : consumers)
1127 readers.emplace_back(std::async(std::launch::async,
1128 [&,
reader = consumer->reader]
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))
1135 auto info = mxlEventInfo{};
1136 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1140 std::this_thread::yield();
1141 if (!validPattern(info, payload) || (info.
index != values.size()))
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)
1162 results.push_back(future.get());
1165 REQUIRE_FALSE(failed);
1166 for (
auto const& values : results)
1168 REQUIRE(values.size() == total);
1169 for (
auto i = std::size_t{0}; i < total; ++i)
1171 REQUIRE(values[i] == 4000 + i);
1174 fixture.checkHead(total - 1);
1178TEST_CASE_METHOD(EventFixture,
"Event snapshots survive overwrite and reads from independent readers",
"[events][concurrency]")
1183 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1185 auto other = IndependentEventReader{domain};
1186 auto future = std::async(std::launch::async,
1191 auto initialPayload =
static_cast<std::uint8_t*
>(
nullptr);
1196 for (
auto i = std::uint64_t{0}; i < 100; ++i)
1203 auto otherPayload =
static_cast<std::uint8_t*
>(
nullptr);
1205 !validPattern(otherInfo, otherPayload))
1213 REQUIRE(validPattern(info, payload));
1217TEST_CASE_METHOD(EventFixture,
"Event readers never expose torn payloads during concurrent wraparound",
"[events][concurrency]")
1221 auto consumers = std::vector<std::unique_ptr<IndependentEventReader>>{};
1222 for (
auto i = 0; i < 2; ++i)
1224 consumers.push_back(std::make_unique<IndependentEventReader>(domain));
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,
1235 start.arrive_and_wait();
1236 for (
auto i = std::uint64_t{0}; i < 6000; ++i)
1246 for (
auto thread =
unsigned{0}; thread < 2; ++thread)
1248 workers.emplace_back(std::async(std::launch::async,
1249 [&, eventReader = consumers[thread]->
reader]
1252 start.arrive_and_wait();
1253 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{10};
1257 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1261 std::this_thread::yield();
1262 if (!validPattern(info, payload))
1277 while (std::chrono::steady_clock::now() < deadline);
1281 start.arrive_and_wait();
1282 for (
auto& future : workers)
1292TEST_CASE(
"One event writer wakes independent readers in other processes",
"[events][concurrency][ipc]")
1298 std::array<int, 2> fds{-1, -1};
1325 ::kill(pid, SIGKILL);
1326 while (::waitpid(pid,
nullptr, 0) < 0 && errno == EINTR)
1333 auto fixture = EventFixture{definitionWithRate(R
"({"numerator":2560})")};
1334 auto ready = Pipe{};
1335 auto start = Pipe{};
1337 REQUIRE(::pipe(ready.fds.data()) == 0);
1338 REQUIRE(::pipe(start.fds.data()) == 0);
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)
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)
1348 argv[arg] = arguments[arg].data();
1350 REQUIRE(::posix_spawn(&children[i].pid, argv[0],
nullptr,
nullptr, argv.data(), environment.data()) == 0);
1353 for (
auto i = std::size_t{0}; i < children.size(); ++i)
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);
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)
1367 for (
auto i = std::uint64_t{0}; i < 256; ++i)
1370 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1373 REQUIRE(validPattern(info, payload));
1375 for (
auto& child : children)
1377 auto status =
int{};
1378 auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
1379 auto result = pid_t{0};
1382 result = ::waitpid(child.pid, &status, WNOHANG);
1387 std::this_thread::sleep_for(std::chrono::milliseconds{1});
1389 while (std::chrono::steady_clock::now() < deadline);
1393 REQUIRE(WEXITSTATUS(status) == 0);
1395 fixture.checkHead(255);
1397 fixture.write(9000);
1402TEST_CASE(
"Compact event slots preserve payload boundaries across wraparound",
"[events]")
1407 struct alignas(128) Block
1409 std::uint8_t bytes[128];
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})
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)
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
1433 REQUIRE(std::ranges::all_of(header.layoutPadding, isZero));
1434 REQUIRE(std::ranges::all_of(header.sequencePadding, isZero));
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)
1443 info.
size =
sizeof info;
1447 std::ranges::fill(payload,
static_cast<std::uint8_t
>(
index));
1450 REQUIRE_NOTHROW(Ring{memory.data(), count, capacity});
1451 for (
auto index = std::uint64_t{count};
index < std::uint64_t{count} * 2; ++
index)
1454 std::ranges::fill(payload, 0);
1455 REQUIRE(ring.read(
index, info, payload.data()) == Ring::ReadResult::Ready);
1458 REQUIRE(std::ranges::all_of(payload,
1459 [
index](
auto byte)
noexcept
1462 return byte ==
index;
1465 auto const sentinel = std::span{memory.back().bytes};
1466 REQUIRE(std::ranges::all_of(sentinel,
1467 [](
auto byte)
noexcept
1470 return byte == 0xCD;
1476TEST_CASE(
"Event atomic copies survive contention within the same mapping",
"[events][concurrency]")
1482 struct alignas(4096) Page
1484 std::uint8_t bytes[4096];
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,
1498 start.arrive_and_wait();
1499 for (
auto index = std::uint64_t{0};
index < total && !failed; ++
index)
1503 info.
size =
sizeof info;
1507 auto payload = std::array<std::uint8_t, 4096>{};
1508 for (
auto byte = std::uint32_t{0};
byte < info.
eventSize; ++byte)
1510 payload[byte] =
static_cast<std::uint8_t
>((info.
timestamp * 29) + (std::uint64_t{
byte} * 7));
1518 auto reader = std::async(std::launch::async,
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)
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)
1533 if (info.
timestamp != 4000 +
index || !validPattern(info, payload.data()))
1541 else if (result == Ring::ReadResult::Overwritten)
1545 else if (result == Ring::ReadResult::Invalid)
1551 std::this_thread::yield();
1560 start.arrive_and_wait();
1562 auto const received =
reader.get();
1563 REQUIRE_FALSE(failed);
1568TEST_CASE(
"Event sequence exhaustion cannot alias an empty slot",
"[events]")
1573 struct alignas(4096) Page
1575 std::uint8_t bytes[4096];
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;
1585 info.
size =
sizeof info;
1587 auto payload = std::array<std::uint8_t, 13>{};
1591 REQUIRE(ring.read(
index, info, payload.data()) == Ring::ReadResult::Ready);
1592 REQUIRE(std::ranges::all_of(payload,
1593 [](
auto byte)
noexcept
1596 return byte == 0xAB;
1599 REQUIRE(ring.read(Ring::MAX_INDEX + 1, info, payload.data()) == Ring::ReadResult::Pending);
1603TEST_CASE(
"Event publication retries only unpublished sequence tags",
"[events][recovery]")
1607 struct alignas(4096) Page
1609 std::uint8_t bytes[4096];
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};
1618 info.
size =
sizeof info;
1620 auto payload = std::array<std::uint8_t, 13>{};
1622 SECTION(
"Unpublished tag may be retried")
1624 slot->header.sequence = 0;
1625 REQUIRE(ring.read(0, info, payload.data()) == Ring::ReadResult::Pending);
1628 REQUIRE(ring.read(0, info, payload.data()) == Ring::ReadResult::Ready);
1629 REQUIRE(std::ranges::all_of(payload, [](
auto byte) {
return byte == 0xAB; }));
1632 SECTION(
"Completed tag may not be reused")
1637 SECTION(
"Newer writing tag may not be overwritten")
1639 slot->header.sequence = 2 << 1;
1645TEST_CASE_METHOD(EventFixture,
"Event indices identify queue position and skipped entries",
"[events]")
1649 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1652 auto const previous = info.
index;
1653 for (
auto i = 0; i < 6; ++i)
1657 auto const before = info;
1658 auto const beforePayload = payload;
1660 REQUIRE(std::memcmp(&before, &info,
sizeof info) == 0);
1661 REQUIRE(payload == beforePayload);
1668 for (
auto i = std::uint64_t{4}; i <= 6; ++i)
1682 auto const finalInfo = info;
1684 REQUIRE(std::memcmp(&finalInfo, &info,
sizeof info) == 0);
1688TEST_CASE(
"Event writer recovery preserves publication and timestamp order",
"[events][recovery]")
1692 auto const initialCount = GENERATE(std::uint64_t{0}, std::uint64_t{6});
1694 auto const crashStage = GENERATE(0, 1, 2);
1695 CAPTURE(initialCount, crashStage);
1703 auto error = std::error_code{};
1704 std::filesystem::remove_all(path, error);
1708 auto const domain = Domain{};
1710 auto watcher = std::make_shared<DomainWatcher>(domain.path);
1712 auto const flowId = uuids::uuid::from_string(
id).value();
1713 auto [created, data] = manager.createOrOpenEventFlow(
flowId, definition, 4,
mxlRational{20, 1}, 13);
1715 auto* flow = data->flow();
1718 info.
size =
sizeof info;
1721 auto bytes = std::array<std::uint8_t, 13>{};
1723 for (
auto i = std::uint64_t{0}; i < initialCount; ++i)
1727 flow->info.runtime.headIndex = i;
1731 auto* slot =
reinterpret_cast<Event*
>(
1732 static_cast<std::uint8_t*
>(mapping.data()) +
sizeof(
EventRingHeader) + ((initialCount % 4) * Ring::slotStride(13)));
1734 if (crashStage == 0)
1736 slot->header.sequence = initialCount << 1;
1737 std::memset(slot + 1, 0xCD, 13);
1742 if (crashStage == 2)
1744 flow->info.runtime.headIndex = initialCount;
1747 auto const previous = flow->state.syncCounter;
1748 auto waiter = std::async(std::launch::async,
1750 auto writer = factory.createEventFlowWriter(manager,
flowId, std::move(data));
1751 auto payload =
static_cast<std::uint8_t*
>(
nullptr);
1753 if (crashStage == 0)
1758 std::memcpy(payload, bytes.data(), bytes.size());
1763 REQUIRE(
writer->getFlowRuntimeInfo().headIndex == initialCount);
1769 REQUIRE(flow->state.syncCounter != previous);
1770 auto ring = Ring{mapping.data(), 4, 13};
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);
1781 REQUIRE(
writer->getFlowRuntimeInfo().headIndex == initialCount + 1);
Atomic single-producer event ring storage and snapshot protocol.
Internal shared-memory headers for discrete grains and event slots.
Minimal reader for the UDP datagrams in the pcap files used by the tests.
Non-owning single-producer event ring view safe for concurrent snapshot readers.
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.
Public flow reader, writer, payload and synchronization APIs.
MXL_EXPORT mxlStatus mxlFlowReaderGetEvent(mxlFlowReader reader, uint64_t timeoutNs, mxlEventInfo *event, uint8_t **payload)
MXL_EXPORT mxlStatus mxlFlowWriterOpenGrain(mxlFlowWriter writer, uint64_t index, mxlGrainInfo *mxlGrainInfo, uint8_t **payload)
MXL_EXPORT mxlStatus mxlReleaseFlowReader(mxlInstance instance, mxlFlowReader reader)
struct mxlFlowReader_t * mxlFlowReader
struct mxlGrainInfo_t mxlGrainInfo
struct mxlEventInfo_t mxlEventInfo
Metadata for one event queue entry, either a complete event or a fragment.
MXL_EXPORT mxlStatus mxlFlowReaderGetGrainNonBlocking(mxlFlowReader reader, uint64_t index, mxlGrainInfo *grain, uint8_t **payload)
MXL_EXPORT mxlStatus mxlFlowWriterCommitEvent(mxlFlowWriter writer, mxlEventInfo const *event)
struct mxlFlowWriter_t * mxlFlowWriter
MXL_EXPORT mxlStatus mxlReleaseFlowWriter(mxlInstance instance, mxlFlowWriter writer)
MXL_EXPORT mxlStatus mxlFlowReaderGetRuntimeInfo(mxlFlowReader reader, mxlFlowRuntimeInfo *info)
MXL_EXPORT mxlStatus mxlFlowReaderGetInfo(mxlFlowReader reader, mxlFlowInfo *info)
MXL_EXPORT mxlStatus mxlFlowWriterCancelEvent(mxlFlowWriter writer)
Cancel the open event without publishing or changing timestamp ordering.
MXL_EXPORT mxlStatus mxlCreateFlowWriter(mxlInstance instance, char const *flowDef, char const *options, mxlFlowWriter *writer, mxlFlowConfigInfo *configInfo, bool *created)
MXL_EXPORT mxlStatus mxlFlowReaderGetEventNonBlocking(mxlFlowReader reader, mxlEventInfo *event, uint8_t **payload)
Attempt to read one event entry without waiting for publication.
MXL_EXPORT mxlStatus mxlCreateFlowReader(mxlInstance instance, char const *flowId, char const *options, mxlFlowReader *reader)
MXL_EXPORT mxlStatus mxlFlowWriterOpenEvent(mxlFlowWriter writer, mxlEventInfo *event, uint8_t **payload)
@ MXL_EVENT_REGISTRY_TYPE_SMPTE
SMPTE registry DIT strings without the 0x prefix.
@ MXL_EVENT_REGISTRY_TYPE_MXL
Namespaced application DIT strings, such as x-mxl:example.
struct mxlFlowRuntimeInfo_t mxlFlowRuntimeInfo
struct mxlFlowConfigInfo_t mxlFlowConfigInfo
struct mxlFlowInfo_t mxlFlowInfo
MXL_EXPORT mxlStatus mxlDestroyInstance(mxlInstance in_instance)
mxlStatus
MXL SDK Status codes.
@ MXL_ERR_OUT_OF_RANGE_TOO_EARLY
@ MXL_ERR_INVALID_FLOW_WRITER
@ MXL_ERR_INVALID_FLOW_READER
@ MXL_ERR_OUT_OF_RANGE_TOO_LATE
MXL_EXPORT mxlInstance mxlCreateInstance(char const *in_mxlDomain, char const *in_options)
struct mxlInstance_t * mxlInstance
constexpr auto EVENT_HEADER_VERSION
Version stored in the public mxlEventInfo metadata of every published entry.
std::filesystem::path makeEventDataFilePath(std::filesystem::path const &flowDirectory)
Locate an event ring file within its flow directory.
std::filesystem::path makeDomainOptionsFilePath(std::filesystem::path const &domain)
bool waitUntilChanged(T const *in_addr, T in_expected, Timepoint in_deadline)
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
std::filesystem::path makeTempDomain()
std::vector< UdpDatagram > readUdpDatagrams(std::filesystem::path const &path)
#define MXL_UNDEFINED_INDEX
struct mxlRational_t mxlRational
uint32_t eventPayloadSize
uint32_t version
Structure version, currently 1.
uint32_t size
Size of this structure.
uint32_t eventSize
Number of payload bytes published in this entry, possibly zero. For fragments this is the fragment si...
uint64_t index
Zero-based queue position, assigned by the library on a successful read. Compare with mxlFlowRuntimeI...
uint8_t complete
1 for an unfragmented event or final fragment; 0 if more fragments follow.
uint32_t flags
Reserved; must be zero.
uint64_t timestamp
Application supplied TAI timestamp in nanoseconds since the epoch; must not decrease within a flow.
uint32_t offset
Logical byte offset within a fragmented event. Zero for unfragmented events and first fragments....
mxlCommonFlowConfigInfo common
mxlEventFlowConfigInfo event
Event queue geometry when common.format is MXL_DATA_FORMAT_EVENT.
Fixed part of an event slot; its payload follows immediately in the mapping.
TEST_CASE("ST 2110-41 pcap packets round trip through the event ring", "[events][pcap]")
TEST_CASE_METHOD(EventFixture, "Event flow queue preserves timestamps and complete payloads", "[events]")
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.
auto const rate
Compute the grain index for the flow rate and current TAI time.
REQUIRE(timeDelta< 33 '366 '667LL)