MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
test_flowmanager.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
4#include <chrono>
5#include <cstdio>
6#include <cstdlib>
7#include <algorithm>
8#include <atomic>
9#include <filesystem>
10#include <list>
11#include <memory>
12#include <thread>
13#include <uuid.h>
14#include <catch2/catch_test_macros.hpp>
15#include <fmt/format.h>
19#include "../../tests/Utils.hpp"
20
21using namespace mxl::lib;
22
23TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Flow Manager : Create Manager", "[flow manager]")
24{
25 remove_all(domain);
26 // This should throw since the folder should not exist.
27 REQUIRE_THROWS(
28 [&]()
29 {
30 (void)std::make_shared<FlowManager>(domain);
31 }());
32
33 // Create the mxl domain path.
34 REQUIRE(create_directory(domain));
35
36 auto const manager = std::make_shared<FlowManager>(domain);
37 REQUIRE(manager->listFlows().size() == 0);
38}
39
40TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Flow Manager : Create Video Flow Structure", "[flow manager]")
41{
42 auto const flowDef = mxl::tests::readFile("data/v210_flow.json");
43 auto const flowId = *uuids::uuid::from_string("5fbec3b1-1b0f-417d-9059-8b94a47197ed");
44 auto const grainRate = mxlRational{60000, 1001};
45
46 auto const payloadSize = 1024;
47 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
48
49 auto manager = std::make_shared<FlowManager>(domain);
50 auto [created, flowData] = manager->createOrOpenDiscreteFlow(flowId, flowDef, MXL_DATA_FORMAT_VIDEO, 5, grainRate, payloadSize, 1, sliceSizes);
51
52 REQUIRE(flowData != nullptr);
53 REQUIRE(flowData->isValid());
54 REQUIRE(flowData->grainCount() == 5);
55
56 auto const flowDirectory = makeFlowDirectoryName(domain, uuids::to_string(flowId));
57 REQUIRE(exists(flowDirectory));
58 REQUIRE(is_directory(flowDirectory));
59
60 // Check that the flow SHM storage exists
61 auto const flowFile = makeFlowDataFilePath(flowDirectory);
62 REQUIRE(exists(flowFile));
63 REQUIRE(is_regular_file(flowFile));
64
65 // Check that the flow access file for the SHM storage exists
66 auto const flowAccessFile = makeFlowAccessFilePath(flowDirectory);
67 REQUIRE(exists(flowAccessFile));
68 REQUIRE(is_regular_file(flowAccessFile));
69
70 // Check that the resource definition exists and is a regular file
71 auto const resourceDefinitionFile = makeFlowDescriptorFilePath(flowDirectory);
72 REQUIRE(exists(resourceDefinitionFile));
73 REQUIRE(is_regular_file(resourceDefinitionFile));
74
75 // Check that the resource definition contains a literal copy of the
76 // definiton passed to the manager.
77 REQUIRE(mxl::tests::readFile(resourceDefinitionFile) == flowDef);
78
79 // Expect no channel data storage in this flow
80 auto const channelDataFile = makeChannelDataFilePath(flowDirectory);
81 REQUIRE(!exists(channelDataFile));
82
83 // Count the grains.
84 auto const grainDir = makeGrainDirectoryName(flowDirectory);
85 REQUIRE(exists(grainDir));
86 REQUIRE(is_directory(grainDir));
87
88 auto grainCount = std::size_t{0};
89 for (auto const& entry : std::filesystem::directory_iterator{grainDir})
90 {
91 if (is_regular_file(entry))
92 {
93 grainCount += 1U;
94 }
95 }
96 REQUIRE(grainCount == 5U);
97
98 // Should not throw, existing flow should be opened.
99 {
100 auto [created, flow] = manager->createOrOpenDiscreteFlow(flowId, flowDef, MXL_DATA_FORMAT_VIDEO, 5, grainRate, payloadSize, 1, sliceSizes);
101 REQUIRE_FALSE(created);
102 }
103
104 bool thrown = false;
105 // Should throw, because the existing flow is a discrete flow.
106 try
107 {
108 auto const sampleRate = mxlRational{48000, 1};
109 auto [flow, created] = manager->createOrOpenContinuousFlow(flowId, flowDef, MXL_DATA_FORMAT_AUDIO, sampleRate, 8, sizeof(float), 8192);
110 }
111 catch (std::exception const& ex)
112 {
113 MXL_ERROR(ex.what());
114 thrown = true;
115 }
116
117 // For some reason REQUIRE_THROWS([](){}) does not work as expected.
118 REQUIRE(thrown);
119
120 REQUIRE(manager->listFlows().size() == 1);
121
122 // Close the flow. it should not be available for a get operation after being closed.
123 flowData.reset();
124
125 REQUIRE(manager->listFlows().size() == 1);
126
127 // Delete the flow.
128 manager->deleteFlow(flowId);
129
130 REQUIRE(manager->listFlows().size() == 0);
131
132 // Confirm that files on disk do not exist anymore
133 REQUIRE(!exists(flowDirectory));
134}
135
136TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Flow Manager : Create Audio Flow Structure", "[flow manager]")
137{
138 auto const flowDef = mxl::tests::readFile("data/audio_flow.json");
139 auto const flowId = *uuids::uuid::from_string("b3bb5be7-9fe9-4324-a5bb-4c70e1084449");
140 auto const flowString = to_string(flowId);
141 auto const sampleRate = mxlRational{48000, 1};
142
143 auto manager = std::make_shared<FlowManager>(domain);
144 auto [created, flowData] = manager->createOrOpenContinuousFlow(flowId, flowDef, MXL_DATA_FORMAT_AUDIO, sampleRate, 2, sizeof(float), 4096);
145
146 REQUIRE(flowData != nullptr);
147 REQUIRE(flowData->isValid());
148 REQUIRE(flowData->channelCount() == 2U);
149 REQUIRE(flowData->sampleWordSize() == sizeof(float));
150 REQUIRE(flowData->channelBufferLength() == 4096U);
151 REQUIRE(flowData->channelDataLength() == (flowData->channelCount() * flowData->channelBufferLength()));
152 REQUIRE(flowData->channelDataSize() == (flowData->channelDataLength() * flowData->sampleWordSize()));
153
154 auto const flowDirectory = makeFlowDirectoryName(domain, uuids::to_string(flowId));
155 REQUIRE(exists(flowDirectory));
156 REQUIRE(is_directory(flowDirectory));
157
158 // Check that the flow SHM storage exists
159 auto const flowFile = makeFlowDataFilePath(flowDirectory);
160 REQUIRE(exists(flowFile));
161 REQUIRE(is_regular_file(flowFile));
162
163 // Check that the resource definition exists and is a regular file
164 auto const resourceDefinitionFile = makeFlowDescriptorFilePath(flowDirectory);
165 REQUIRE(exists(resourceDefinitionFile));
166 REQUIRE(is_regular_file(resourceDefinitionFile));
167
168 // Check that the resource definition contains a literal copy of the
169 // definiton passed to the manager.
170 REQUIRE(mxl::tests::readFile(resourceDefinitionFile) == flowDef);
171
172 // Check that the channel data SHM storage exists
173 auto const channelDataFile = makeChannelDataFilePath(flowDirectory);
174 REQUIRE(exists(channelDataFile));
175 REQUIRE(is_regular_file(channelDataFile));
176
177 // Expect no grains in this flow
178 auto const grainDir = makeGrainDirectoryName(flowDirectory);
179 REQUIRE(!exists(grainDir));
180
181 {
182 auto [created, flowData] = manager->createOrOpenContinuousFlow(flowId, flowDef, MXL_DATA_FORMAT_AUDIO, sampleRate, 8, sizeof(float), 8192);
183 REQUIRE_FALSE(created);
184 }
185
186 auto const payloadSize = 1024;
187 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
188
189 // This should throw since the flow exists but is in a different format.
190 REQUIRE_THROWS(
191 [&]()
192 {
193 auto const grainRate = mxlRational{60000, 1001};
194 manager->createOrOpenDiscreteFlow(flowId, flowDef, MXL_DATA_FORMAT_VIDEO, 5, grainRate, payloadSize, 1, sliceSizes);
195 }());
196
197 REQUIRE(manager->listFlows().size() == 1);
198
199 // Close the flow. It should not be available for a get operation after being closed.
200 flowData.reset();
201
202 REQUIRE(manager->listFlows().size() == 1);
203
204 // Delete the flow.
205 manager->deleteFlow(flowId);
206
207 REQUIRE(manager->listFlows().size() == 0);
208
209 // Confirm that files on disk do not exist anymore
210 REQUIRE(!exists(flowDirectory));
211}
212
213TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Flow Manager : Open, List, and Error Conditions", "[flow manager]")
214{
215 auto manager = std::make_shared<FlowManager>(domain);
216
217 //
218 // 1) Create & open a discrete flow
219 //
220 auto const flowId1 = *uuids::uuid::from_string("11111111-1111-1111-1111-111111111111");
221 auto const flowDef1 = mxl::tests::readFile("data/v210_flow.json");
222 auto const grainRate = mxlRational{60000, 1001};
223 {
224 auto const payloadSize = 512;
225 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
226
227 auto [created,
228 flowData1] = manager->createOrOpenDiscreteFlow(flowId1, flowDef1, MXL_DATA_FORMAT_VIDEO, 3, grainRate, payloadSize, 0, sliceSizes);
229 REQUIRE(flowData1->grainCount() == 3U);
230 // close writer
231 flowData1.reset();
232 }
233 // open in read-only mode
234 {
235 auto openData1 = manager->openFlow(flowId1, AccessMode::READ_ONLY);
236 REQUIRE(openData1);
237 auto* d = dynamic_cast<DiscreteFlowData*>(openData1.get());
238 REQUIRE(d);
239 REQUIRE(d->grainCount() == 3U);
240 }
241
242 //
243 // 2) Create & open a continuous flow
244 //
245 auto const flowId2 = *uuids::uuid::from_string("22222222-2222-2222-2222-222222222222");
246 auto const flowDef2 = mxl::tests::readFile("data/audio_flow.json");
247 auto const sampleRate = mxlRational{48000, 1};
248 {
249 auto [created, flowData2] = manager->createOrOpenContinuousFlow(flowId2, flowDef2, MXL_DATA_FORMAT_AUDIO, sampleRate, 4, sizeof(float), 2048);
250 REQUIRE(flowData2->channelCount() == 4U);
251 flowData2.reset();
252 }
253 {
254 auto openData2 = manager->openFlow(flowId2, AccessMode::READ_WRITE);
255 REQUIRE(openData2);
256 auto* c = dynamic_cast<ContinuousFlowData*>(openData2.get());
257 REQUIRE(c);
258 REQUIRE(c->channelCount() == 4U);
259 }
260
261 //
262 // 3) listFlows should report both flows
263 //
264 {
265 auto flows = manager->listFlows();
266 REQUIRE(flows.size() == 2);
267 }
268
269 //
270 // 4) deleteFlow(nullptr) returns false
271 //
272 {
273 auto empty = std::unique_ptr<FlowData>{};
274 REQUIRE(manager->deleteFlow(std::move(empty)) == false);
275 }
276
277 //
278 // 5) delete by ID and verify removal
279 //
280 REQUIRE(manager->deleteFlow(flowId1));
281 REQUIRE(manager->listFlows().size() == 1);
282 REQUIRE(manager->deleteFlow(flowId2));
283 REQUIRE(manager->listFlows().empty());
284
285 //
286 // 6) openFlow invalid mode should throw
287 //
288 REQUIRE_THROWS_AS(manager->openFlow(flowId1, AccessMode::CREATE_READ_WRITE), std::invalid_argument);
289
290 //
291 // 7) opening a non-existent flow throws filesystem_error
292 //
293 auto const flowId3 = *uuids::uuid::from_string("33333333-3333-3333-3333-333333333333");
294 REQUIRE_THROWS_AS(manager->openFlow(flowId3, AccessMode::READ_ONLY), std::filesystem::filesystem_error);
295
296 //
297 // 8) listFlows skips invalid directories
298 //
299 {
300 // manually drop a bogus folder
301 auto invalidDir = domain / "not-a-valid-uuid.mxl-flow";
302 REQUIRE(create_directory(invalidDir));
303 manager = std::make_shared<FlowManager>(domain);
304 auto flows2 = manager->listFlows();
305 REQUIRE(flows2.empty());
306 }
307
308 //
309 // 9) listFlows on missing domain throws
310 //
311 remove_all(domain);
312 REQUIRE_THROWS_AS(manager->listFlows(), std::filesystem::filesystem_error);
313
314 //
315 // 10) unsupported formats should be rejected
316 //
317 auto const payloadSize = 512;
318 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
319 auto const badId = *uuids::uuid::from_string("44444444-4444-4444-4444-444444444444");
320 REQUIRE_THROWS_AS(manager->createOrOpenDiscreteFlow(badId, flowDef1, MXL_DATA_FORMAT_UNSPECIFIED, 1, grainRate, payloadSize, 1, sliceSizes),
321 std::runtime_error);
322 REQUIRE_THROWS_AS(manager->createOrOpenContinuousFlow(badId, flowDef2, MXL_DATA_FORMAT_VIDEO, sampleRate, 1, 4, 1024), std::runtime_error);
323}
324
325// Re-creation after deletion
326TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: re-create flow after deletion", "[flow manager][reuse]")
327{
328 auto mgr = std::make_shared<FlowManager>(domain);
329 auto const id = *uuids::uuid::from_string("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
330 auto const def = mxl::tests::readFile("data/v210_flow.json");
331 auto const rate = mxlRational{50, 1};
332
333 auto const payloadSize = 512;
334 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
335 // Create discrete flow #1
336 auto [created1, f1] = mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes);
337 REQUIRE(f1);
338 REQUIRE(mgr->listFlows().size() == 1);
339
340 // Delete it
341 REQUIRE(mgr->deleteFlow(id));
342 REQUIRE(mgr->listFlows().empty());
343
344 // Re-create with same ID
345 auto [created2, f2] = mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 2, rate, payloadSize, 1, sliceSizes);
346 REQUIRE(f2);
347 REQUIRE(mgr->listFlows().size() == 1);
348}
349
350TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: open existing flow leaves no temporary directory", "[flow manager][reuse]")
351{
352 auto const countTemporaryDirectories = [this]
353 {
354 return std::ranges::count_if(std::filesystem::directory_iterator{domain},
355 [](auto const& entry) { return entry.path().filename().string().starts_with(".mxl-tmp-"); });
356 };
357
358 auto const mgr = std::make_shared<FlowManager>(domain);
359 auto const initialCount = countTemporaryDirectories();
360
361 SECTION("discrete")
362 {
363 auto const id = *uuids::uuid::from_string("c1c1c1c1-c1c1-c1c1-c1c1-c1c1c1c1c1c1");
364 auto const def = mxl::tests::readFile("data/v210_flow.json");
365 auto const payloadSize = 512;
366 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
367
368 auto [created1, f1] = mgr->createOrOpenDiscreteFlow(
369 id, def, MXL_DATA_FORMAT_VIDEO, 1, mxlRational{.numerator = 50, .denominator = 1}, payloadSize, 1, sliceSizes);
370 REQUIRE(created1);
371 auto [created2, f2] = mgr->createOrOpenDiscreteFlow(
372 id, def, MXL_DATA_FORMAT_VIDEO, 1, mxlRational{.numerator = 50, .denominator = 1}, payloadSize, 1, sliceSizes);
373 REQUIRE_FALSE(created2);
374 REQUIRE(f2);
375 REQUIRE(countTemporaryDirectories() == initialCount);
376 }
377
378 SECTION("continuous")
379 {
380 auto const id = *uuids::uuid::from_string("c2c2c2c2-c2c2-c2c2-c2c2-c2c2c2c2c2c2");
381 auto const def = mxl::tests::readFile("data/audio_flow.json");
382
383 auto [created1, f1] = mgr->createOrOpenContinuousFlow(
384 id, def, MXL_DATA_FORMAT_AUDIO, mxlRational{.numerator = 48000, .denominator = 1}, 8, sizeof(float), 4096);
385 REQUIRE(created1);
386 auto [created2, f2] = mgr->createOrOpenContinuousFlow(
387 id, def, MXL_DATA_FORMAT_AUDIO, mxlRational{.numerator = 48000, .denominator = 1}, 8, sizeof(float), 4096);
388 REQUIRE_FALSE(created2);
389 REQUIRE(f2);
390 REQUIRE(countTemporaryDirectories() == initialCount);
391 }
392
393 SECTION("event")
394 {
395 auto const id = *uuids::uuid::from_string("c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3");
396 auto const def = mxl::tests::readFile("data/event_flow.json");
397
398 auto [created1, f1] = mgr->createOrOpenEventFlow(id, def, 4, mxlRational{.numerator = 20, .denominator = 1}, 64);
399 REQUIRE(created1);
400 auto [created2, f2] = mgr->createOrOpenEventFlow(id, def, 4, mxlRational{.numerator = 20, .denominator = 1}, 64);
401 REQUIRE_FALSE(created2);
402 REQUIRE(f2);
403 REQUIRE(countTemporaryDirectories() == initialCount);
404 }
405}
406
407// Test robustness: corrupted flow directory with missing descriptor
408TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: corrupted flow with missing descriptor", "[flow manager][corruption]")
409{
410 auto mgr = std::make_shared<FlowManager>(domain);
411 auto const id = *uuids::uuid::from_string("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
412 auto const def = mxl::tests::readFile("data/v210_flow.json");
413 auto const rate = mxlRational{50, 1};
414
415 // Create and publish
416 auto const payloadSize = 512;
417 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
418 auto [created, flow] = mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes);
419 flow.reset();
420 REQUIRE(mgr->listFlows().size() == 1);
421
422 // Manually remove the descriptor JSON to simulate corruption
423 auto flowDir = makeFlowDirectoryName(domain, uuids::to_string(id));
424 auto descFile = makeFlowDescriptorFilePath(flowDir);
425 REQUIRE(exists(descFile));
426 remove(descFile);
427
428 // By design decision, corrupted flows are not filtered out
429 auto ids = mgr->listFlows();
430 REQUIRE(ids.size() == 1);
431
432 auto rd = mgr->openFlow(id, AccessMode::READ_ONLY);
433 REQUIRE(rd);
434 auto* d = dynamic_cast<DiscreteFlowData*>(rd.get());
435 REQUIRE(d);
436 REQUIRE(d->grainCount() == 1U);
437}
438
439// Concurrent createDiscreteFlow with same UUID
440TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: concurrent createDiscreteFlow same UUID", "[flow manager][concurrency]")
441{
442 auto mgr = std::make_shared<FlowManager>(domain);
443 auto const id = *uuids::uuid::from_string("cccccccc-cccc-cccc-cccc-cccccccccccc");
444 auto const def = mxl::tests::readFile("data/v210_flow.json");
445 auto const rate = mxlRational{50, 1};
446
447 auto success = std::atomic<int>{0};
448 auto failure = std::atomic<int>{0};
449 auto worker = [&](std::uint32_t payloadSize)
450 {
451 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
452 auto [created, f] = mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes);
453 if (created)
454 {
455 ++success;
456 }
457 else
458 {
459 ++failure;
460 }
461 };
462
463 auto t1 = std::thread{worker, 64u};
464 auto t2 = std::thread{worker, 128u};
465 t1.join();
466 t2.join();
467
468 // Exactly one must succeed, and one must fail
469 REQUIRE(success.load() == 1);
470 REQUIRE(failure.load() == 1);
471 REQUIRE(mgr->listFlows().size() == 1);
472}
473
474// deleteFlow on read-only domain
475TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: deleteFlow on read-only domain", "[flow manager][deletion]")
476{
477 auto mgr = std::make_shared<FlowManager>(domain);
478 auto const id = *uuids::uuid::from_string("dddddddd-dddd-dddd-dddd-dddddddddddd");
479 auto const def = mxl::tests::readFile("data/v210_flow.json");
480 auto const rate = mxlRational{50, 1};
481
482 auto const payloadSize = 512;
483 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
484 auto [created, f] = mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes);
485 f.reset();
486 REQUIRE(mgr->listFlows().size() == 1);
487
488 // Make domain read-only
489 permissions(domain,
490 std::filesystem::perms::owner_all | std::filesystem::perms::group_all | std::filesystem::perms::others_all,
491 std::filesystem::perm_options::remove);
492
493 // DeleteFlow should respect filesystem permissions but return false instead of throwing
494 // When domain is read-only, deletion operations fail and method returns false
495 // This test verifies that permission errors are handled gracefully
496 REQUIRE(mgr->deleteFlow(id) == false);
497
498 // Restore full permissions for cleanup and verification
499 permissions(domain, std::filesystem::perms::owner_all, std::filesystem::perm_options::add);
500
501 // Since deletion failed due to permissions, the flow should still exist
502 REQUIRE(mgr->listFlows().size() == 1);
503}
504
505TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: deleteFlow returns false for non-existent flow", "[flow manager][deletion]")
506{
507 auto mgr = std::make_shared<FlowManager>(domain);
508 auto const nonExistentId = *uuids::uuid::from_string("99999999-9999-9999-9999-999999999999");
509
510 // Try to delete a flow that doesn't exist
511 REQUIRE(mgr->deleteFlow(nonExistentId) == false);
512}
513
514// Concurrent listFlows + deleteFlow does not crash
515TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: concurrent listFlows and deleteFlow", "[flow manager][concurrency]")
516{
517 auto mgr = std::make_shared<FlowManager>(domain);
518 auto ids = std::vector<uuids::uuid>{};
519 for (int i = 0; i < 5; ++i)
520 {
521 // Last segment must be exactly 12 hex digits: 11 zeros + one hex digit
522 auto id = *uuids::uuid::from_string(fmt::format("eeeeeeee-eeee-eeee-eeee-00000000000{:X}", i));
523 ids.push_back(id);
524
525 auto const payloadSize = 512;
526 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
527 mgr->createOrOpenDiscreteFlow(
528 id, mxl::tests::readFile("data/v210_flow.json"), MXL_DATA_FORMAT_VIDEO, 1, mxlRational{50, 1}, payloadSize, 1, sliceSizes);
529 }
530
531 auto done = std::atomic<bool>{false};
532 auto lister = std::thread{[&]()
533 {
534 while (!done)
535 {
536 auto list = mgr->listFlows();
537 // no crash, and size never exceeds 5
538 REQUIRE(list.size() <= 5);
539 std::this_thread::sleep_for(std::chrono::milliseconds(10));
540 }
541 }};
542
543 // Delete them one by one
544 for (auto& id : ids)
545 {
546 mgr->deleteFlow(id);
547 }
548 done = true;
549 lister.join();
550
551 REQUIRE(mgr->listFlows().empty());
552}
553
554// Multiple FlowManager instances on same domain
555TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: multiple instances share domain", "[flow manager]")
556{
557 auto domain = mxl::tests::makeTempDomain();
558 auto mgr1 = std::make_shared<FlowManager>(domain);
559 auto mgr2 = std::make_shared<FlowManager>(domain);
560
561 auto const id = *uuids::uuid::from_string("ffffffff-ffff-ffff-ffff-ffffffffffff");
562 auto const def = mxl::tests::readFile("data/v210_flow.json");
563 auto const rate = mxlRational{50, 1};
564
565 auto const payloadSize = 512;
566 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
567
568 auto f1 = mgr1->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes);
569 REQUIRE(mgr1->listFlows().size() == 1);
570 // mgr2 should see it too
571 REQUIRE(mgr2->listFlows().size() == 1);
572
573 // Delete via mgr2
574 REQUIRE(mgr2->deleteFlow(id));
575 REQUIRE(mgr1->listFlows().empty());
576 REQUIRE(mgr2->listFlows().empty());
577}
578
579// createFlow on unwritable domain
580TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: createFlow throws on unwritable domain", "[flow manager][error]")
581{
582 // remove write perms on domain
583 permissions(domain, std::filesystem::perms::owner_write, std::filesystem::perm_options::remove);
584
585 auto mgr = std::make_shared<FlowManager>(domain);
586 auto const id = *uuids::uuid::from_string("aaaaaaaa-0000-0000-0000-000000000000");
587 auto const def = mxl::tests::readFile("data/v210_flow.json");
588 auto const rate = mxlRational{50, 1};
589
590 // CreateFlow should respect filesystem permissions
591 // When domain is unwritable, creation operations should fail
592 // This test verifies proper permission enforcement
593 auto const payloadSize = 512;
594 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
595
596 REQUIRE_THROWS_AS(mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, rate, payloadSize, 1, sliceSizes),
597 std::filesystem::filesystem_error);
598
599 // restore perms so we can clean up
600 permissions(domain, std::filesystem::perms::owner_all, std::filesystem::perm_options::add);
601}
602
603TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "FlowManager: parallel flow writer creation", "[flow manager]")
604{
605 auto const numIterations = 10'000;
606 auto const numWorkers = 3;
607
608 struct Worker
609 {
610 std::unique_ptr<std::atomic<bool>> readySignal;
611 std::unique_ptr<FlowManager> mgr;
612 std::optional<std::thread> thread;
613 };
614
615 auto flowManager = std::make_unique<FlowManager>(domain);
616 auto workers = std::list<Worker>{};
617
618 auto createdSignal = std::atomic<int>{0}; // Signal from each worker that they are done creating/opening the flow.
619 auto numOpened = std::atomic<std::uint64_t>{0}; // Total number of flows that were opened.
620 auto numCreated = std::atomic<std::uint64_t>{0}; // Total number of flows that were created.
621
622 auto const def = mxl::tests::readFile("data/v210_flow.json");
623 auto const id = *uuids::uuid::from_string("5fbec3b1-1b0f-417d-9059-8b94a47197ed");
624 auto const payloadSize = 512;
625 auto const sliceSizes = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{payloadSize, 0, 0, 0};
626
627 auto workFn = [&](Worker* worker, int workerIndex)
628 {
629 for (auto i = 0; i < numIterations; ++i)
630 {
631 // Wait for the main threads signal to start
632 while (!worker->readySignal->exchange(false))
633 {
634 }
635
636 {
637 // Create or open the flow. This is where the race happens. Only one of the workers should be able to create the flow (created ==
638 // true). The others should still receive an opened flow that is writable, but created should be false.
639 auto [created,
640 flow] = worker->mgr->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, mxlRational{50, 1}, payloadSize, 1, sliceSizes);
641
642 // Writes the current iteration number into the padding of the header of the first grain.
643 *(reinterpret_cast<std::uint64_t*>(&flow->grainAt(0)->header.pad) + workerIndex) = i;
644
645 // Increment either numCreated or numOpened.
646 (created ? &numCreated : &numOpened)->fetch_add(1);
647 }
648
649 // Signal that we have completed to iteration
650 createdSignal.fetch_add(1);
651 }
652 };
653
654 // Create and start all the workers.
655 for (auto i = 0; i < numWorkers; ++i)
656 {
657 auto& w = workers.emplace_back(std::make_unique<std::atomic<bool>>(false), std::make_unique<FlowManager>(domain), std::nullopt);
658 w.thread = std::thread{workFn, &w, i};
659 }
660
661 for (auto i = 0; i < numIterations; ++i)
662 {
663 // Signal all workers
664 std::ranges::for_each(workers, [](Worker& w) { w.readySignal->store(true); });
665
666 // Wait for the workers to have opened and written to the shared memory
667 while (createdSignal.load() != static_cast<int>(workers.size()))
668 {
669 }
670 createdSignal.store(0);
671
672 // The flow should exist
673 REQUIRE(flowDirectoryExists(uuids::to_string(id)));
674
675 {
676 // We should be able to open the flow.
677 auto [created,
678 flow] = flowManager->createOrOpenDiscreteFlow(id, def, MXL_DATA_FORMAT_VIDEO, 1, mxlRational{50, 1}, payloadSize, 1, sliceSizes);
679 REQUIRE_FALSE(created); // The existing flow should be opened and not a new one created
680
681 // Prove that all workers have actually opened the same memory by checking the grain header padding.
682 // The workers should all have written the current iteration index here.
683 auto paddingStorage = reinterpret_cast<std::uint64_t*>(&flow->grainAt(0)->header.pad);
684 for (std::size_t w = 0; w < workers.size(); ++w)
685 {
686 REQUIRE(paddingStorage[w] == static_cast<std::uint64_t>(i));
687 }
688 }
689
690 // Delete the flow.
691 flowManager->deleteFlow(id);
692 }
693
694 std::ranges::for_each(workers, [](Worker& w) { w.thread->join(); });
695
696 // In each iteration the flow should have been created only once
697 REQUIRE(numCreated.load() == numIterations);
698
699 // In each iteration all workers that did not create the flow should have opened it.
700 REQUIRE(numOpened.load() == numIterations * (numWorkers - 1));
701}
#define MXL_ERROR(...)
Definition Logging.hpp:67
Paths and filenames utilities used by the MXL SDK.
@ MXL_DATA_FORMAT_AUDIO
Definition dataformat.h:28
@ MXL_DATA_FORMAT_UNSPECIFIED
Definition dataformat.h:26
@ MXL_DATA_FORMAT_VIDEO
Definition dataformat.h:27
std::filesystem::path makeChannelDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:47
std::filesystem::path makeFlowDescriptorFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:23
std::filesystem::path makeFlowAccessFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:29
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:17
std::filesystem::path makeGrainDirectoryName(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:35
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
Definition PathUtils.cpp:11
std::filesystem::path makeTempDomain()
Definition Utils.hpp:108
std::string readFile(std::filesystem::path const &filepath)
Definition Utils.hpp:78
struct mxlRational_t mxlRational
TEST_CASE_PERSISTENT_FIXTURE(mxl::tests::mxlDomainFixture, "Flow Manager : Create Manager", "[flow manager]")
constexpr auto w
auto const flowId
auto const rate
Compute the grain index for the flow rate and current TAI time.
auto flowDef
REQUIRE(timeDelta< 33 '366 '667LL)