11#include <system_error>
40 std::filesystem::path createTemporaryFlowDirectory(std::filesystem::path
const& base)
42 auto pathBuffer = (base /
".mxl-tmp-XXXXXXXXXXXXXXXX").
string();
43 if (::mkdtemp(pathBuffer.data()) ==
nullptr)
45 auto const error = errno;
46 MXL_ERROR(
"mkdtemp failed for path '{}' (errno {}: {}).", base.string(), error, std::strerror(error));
47 throw std::filesystem::filesystem_error{
48 "Could not create temporary directory.", base, std::error_code{error, std::generic_category()}
54 bool publishFlowDirectory(std::filesystem::path
const& source, std::filesystem::path
const& dest)
57 std::filesystem::perms::group_read | std::filesystem::perms::group_exec | std::filesystem::perms::others_read |
58 std::filesystem::perms::others_exec,
59 std::filesystem::perm_options::add);
62 if (::renameat2(AT_FDCWD, source.c_str(), AT_FDCWD, dest.c_str(), RENAME_NOREPLACE) < 0)
63#elif defined __APPLE__
64 if (::renamex_np(source.c_str(), dest.c_str(), RENAME_EXCL) < 0)
67 auto const error = errno;
71 case ENOTEMPTY:
return false;
73 throw std::system_error{error, std::system_category(),
"Failed to publish flow directory by renaming it to its public name."};
89 void writeFlowDescriptor(std::filesystem::path
const& flowDir, std::string
const&
flowDef)
92 if (
auto out = std::ofstream{flowJsonFile, std::ios::out | std::ios::trunc}; out)
98 throw std::filesystem::filesystem_error{
99 "Failed to create flow resource definition.", flowJsonFile, std::make_error_code(std::errc::io_error)};
104 std::uint32_t maxSyncBatchSizeHintOpt, std::uint32_t maxCommitBatchSizeHintOpt)
108 auto const idSpan =
flowId.as_bytes();
109 std::memcpy(result.id, idSpan.data(), idSpan.size());
110 result.format = format;
111 result.grainRate = grainRate;
113 result.maxCommitBatchSizeHint = maxCommitBatchSizeHintOpt;
114 result.maxSyncBatchSizeHint = maxSyncBatchSizeHintOpt;
118 result.deviceIndex = -1;
128 result.lastReadTime = result.lastWriteTime;
133 FlowState initFlowState(std::filesystem::path
const& flowDataPath)
139 if (::stat(flowDataPath.string().c_str(), &st) != 0)
141 auto const error = errno;
142 throw std::filesystem::filesystem_error{
143 "Could not stat flow data file.", flowDataPath, std::error_code{error, std::generic_category()}
148 result.inode = st.st_ino;
156 :
_mxlDomain{std::filesystem::canonical(in_mxlDomain)}
158 if (!exists(in_mxlDomain) || !is_directory(in_mxlDomain))
160 throw std::filesystem::filesystem_error{
161 "Path does not exist or is not a directory.", in_mxlDomain, std::make_error_code(std::errc::no_such_file_or_directory)};
166 mxlDataFormat flowFormat, std::size_t grainCount,
mxlRational const& grainRate, std::size_t grainPayloadSize, std::size_t grainNumOfSlices,
167 std::array<uint32_t, MXL_MAX_PLANES_PER_GRAIN> grainSliceLengths, std::uint32_t maxSyncBatchSizeHintOpt,
168 std::uint32_t maxCommitBatchSizeHintOpt)
170 auto const uuidString = uuids::to_string(
flowId);
171 MXL_DEBUG(
"Create discrete flow. id: {}, grainCount: {}, grain payload size: {}", uuidString, grainCount, grainPayloadSize);
173 flowFormat = sanitizeFlowFormat(flowFormat);
176 throw std::runtime_error{
"Attempt to create discrete flow with unsupported or non matching format."};
179 auto const tempDirectory = createTemporaryFlowDirectory(
_mxlDomain);
184 std::filesystem::remove_all(tempDirectory, ec);
187 MXL_WARN(
"Failed to remove temporary flow directory: {}", ec.message());
192 writeFlowDescriptor(tempDirectory,
flowDef);
196 if (
auto out = std::ofstream{readAccessFile, std::ios::out | std::ios::trunc}; !out)
198 throw std::filesystem::filesystem_error{
199 "Failed to create flow access file.", readAccessFile, std::make_error_code(std::errc::file_exists)};
205 auto& info = *flowData->flowInfo();
207 info.size =
sizeof info;
208 info.config.common = initCommonFlowConfigInfo(
flowId, flowFormat, grainRate, maxSyncBatchSizeHintOpt, maxCommitBatchSizeHintOpt);
209 info.config.discrete = {};
210 info.config.discrete.grainCount = grainCount;
211 std::ranges::copy(grainSliceLengths, info.config.discrete.sliceSizes);
213 info.runtime = initFlowRuntimeInfo();
215 auto& state = *flowData->flowState();
216 state = initFlowState(flowDataPath);
219 if (!create_directory(grainDir))
221 throw std::filesystem::filesystem_error{
"Could not create grain directory.", grainDir, std::make_error_code(std::errc::io_error)};
224 for (
auto i = std::size_t{0}; i < grainCount; ++i)
227 MXL_TRACE(
"Creating grain: {}", grainPath.string());
230 auto const grain = flowData->emplaceGrain(grainPath.string().c_str(), grainPayloadSize);
231 auto&
gInfo = grain->header.info;
232 gInfo.grainSize = grainPayloadSize;
233 gInfo.totalSlices = grainNumOfSlices;
234 gInfo.validSlices = 0;
240 if (publishFlowDirectory(tempDirectory, finalDir))
242 return {
true, std::move(flowData)};
247 if (!existingFlowData)
249 throw std::runtime_error(
"Could not open existing flow because it is of a different format");
252 return {
false, std::move(existingFlowData)};
257 std::size_t eventCount,
mxlRational const& grainRate, std::size_t eventPayloadSize)
259 auto const uuidString = uuids::to_string(
flowId);
260 MXL_DEBUG(
"Create event flow. id: {}, eventCount: {}, event payload size: {}", uuidString, eventCount, eventPayloadSize);
263 if ((eventCount < 2) || (eventCount > 65536) || (eventPayloadSize == 0) || (eventPayloadSize > 1048576))
265 throw std::invalid_argument{
"Invalid event buffer dimensions."};
268 auto const tempDirectory = createTemporaryFlowDirectory(
_mxlDomain);
272 auto ec = std::error_code{};
273 std::filesystem::remove_all(tempDirectory, ec);
276 MXL_WARN(
"Failed to remove temporary flow directory: {}", ec.message());
281 writeFlowDescriptor(tempDirectory,
flowDef);
285 if (
auto out = std::ofstream{readAccessFile, std::ios::out | std::ios::trunc}; !out)
287 throw std::filesystem::filesystem_error{
288 "Failed to create flow access file.", readAccessFile, std::make_error_code(std::errc::file_exists)};
294 auto& info = *flowData->flowInfo();
296 info.size =
sizeof info;
297 info.config.common = initCommonFlowConfigInfo(
flowId, flowFormat, grainRate, 1, 1);
298 info.config.event = {};
299 info.config.event.eventCount = eventCount;
300 info.config.event.eventPayloadSize = eventPayloadSize;
302 info.runtime = initFlowRuntimeInfo();
305 auto& state = *flowData->flowState();
306 state = initFlowState(flowDataPath);
311 if (publishFlowDirectory(tempDirectory, finalDir))
313 return {
true, std::move(flowData)};
318 if (!existingFlowData)
320 throw std::runtime_error(
"Could not open existing flow because it is of a different format");
323 return {
false, std::move(existingFlowData)};
329 std::size_t bufferLength, std::uint32_t maxSyncBatchSizeHintOpt, std::uint32_t maxCommitBatchSizeHintOpt)
331 auto const uuidString = uuids::to_string(
flowId);
332 MXL_DEBUG(
"Create continuous flow. id: {}, channel count: {}, word size: {}, buffer length: {}",
338 flowFormat = sanitizeFlowFormat(flowFormat);
341 throw std::runtime_error{
"Attempt to create continuous flow with unsupported or non matching format."};
344 auto const tempDirectory = createTemporaryFlowDirectory(
_mxlDomain);
348 auto ec = std::error_code{};
349 std::filesystem::remove_all(tempDirectory, ec);
352 MXL_WARN(
"Failed to remove temporary flow directory: {}", ec.message());
357 writeFlowDescriptor(tempDirectory,
flowDef);
362 auto& info = *flowData->flowInfo();
364 info.size =
sizeof info;
365 info.config.common = initCommonFlowConfigInfo(
flowId, flowFormat, sampleRate, maxSyncBatchSizeHintOpt, maxCommitBatchSizeHintOpt);
366 info.config.continuous = {};
367 info.config.continuous.channelCount = channelCount;
368 info.config.continuous.bufferLength = bufferLength;
370 info.runtime = initFlowRuntimeInfo();
372 auto& state = *flowData->flowState();
373 state = initFlowState(flowDataPath);
378 if (publishFlowDirectory(tempDirectory, finalDir))
380 return {
true, std::move(flowData)};
385 if (!existingFlowData)
387 throw std::runtime_error{
"Could not open existing flow because it is of a different format"};
390 return {
false, std::move(existingFlowData)};
398 throw std::invalid_argument{
"Attempt to open flow with invalid access mode."};
401 auto uuid = uuids::to_string(in_flowId);
410 throw std::invalid_argument{
411 fmt::format(
"Unsupported flow data version: {}, supported is: {}", flowSegment.get()->info.version,
FLOW_DATA_VERSION)};
420 auto data = std::make_unique<EventFlowData>(std::move(flowSegment));
431 throw std::runtime_error{
"Attempt to open flow with unsupported data format."};
436 throw std::filesystem::filesystem_error{
"Flow file not found.", flowFile, std::make_error_code(std::errc::no_such_file_or_directory)};
443 auto flowData = std::make_unique<DiscreteFlowData>(std::move(sharedFlowInstance));
445 auto const grainCount = flowData->flowInfo()->config.discrete.grainCount;
449 if (exists(grainDir) && is_directory(grainDir))
452 for (
auto i = 0U; i < grainCount; ++i)
455 MXL_TRACE(
"Opening grain: {}", grainPath);
457 flowData->emplaceGrain(grainPath.c_str(), 0U);
462 throw std::filesystem::filesystem_error{
463 "Grain directory not found.", grainDir, std::make_error_code(std::errc::no_such_file_or_directory)};
473 auto flowData = std::make_unique<ContinuousFlowData>(std::move(sharedFlowInstance));
485 auto const span = uuids::span<std::uint8_t,
sizeof flowData->flowInfo()->config.common.id>{
486 const_cast<std::uint8_t*
>(flowData->flowInfo()->config.common.id),
sizeof flowData->flowInfo()->config.common.id};
487 auto const id = uuids::uuid(span);
500 auto uuid = uuids::to_string(
flowId);
507 auto const removed = remove_all(flowPath);
510 MXL_TRACE(
"Flow not found or already deleted: {}", uuid);
525 auto base = std::filesystem::path{
_mxlDomain};
527 auto flowIds = std::vector<uuids::uuid>{};
528 if (exists(base) && is_directory(base))
530 for (
auto const& entry : std::filesystem::directory_iterator{
_mxlDomain})
535 auto id = uuids::uuid::from_string(entry.path().stem().string());
538 flowIds.push_back(*
id);
545 throw std::filesystem::filesystem_error{
"Base directory not found.", base, std::make_error_code(std::errc::no_such_file_or_directory)};
553 auto const uuid = uuids::to_string(
flowId);
556 if (
auto in = std::ifstream{flowJsonFile, std::ios::in}; in)
558 auto const result = std::string{std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{}};
561 throw std::runtime_error{
"Error while reading the flow definition."};
567 if (!exists(flowJsonFile))
569 throw std::filesystem::filesystem_error{
"Failed to open flow resource definition - file not found.",
571 std::make_error_code(std::errc::no_such_file_or_directory)};
573 throw std::runtime_error{
"Failed to open flow resource definition."};
Paths and filenames utilities used by the MXL SDK.
bool deleteFlow(std::unique_ptr< FlowData > &&flowData)
std::unique_ptr< DiscreteFlowData > openDiscreteFlow(std::filesystem::path const &flowDir, SharedMemoryInstance< Flow > &&sharedFlowInstance)
std::filesystem::path _mxlDomain
std::unique_ptr< ContinuousFlowData > openContinuousFlow(std::filesystem::path const &flowDir, SharedMemoryInstance< Flow > &&sharedFlowInstance)
std::vector< uuids::uuid > listFlows() const
std::pair< bool, std::unique_ptr< EventFlowData > > createOrOpenEventFlow(uuids::uuid const &flowId, std::string const &flowDef, std::size_t eventCount, mxlRational const &grainRate, std::size_t eventPayloadSize)
Create an event flow atomically, or open the existing flow with the same ID.
FlowManager(std::filesystem::path const &in_mxlDomain)
std::string getFlowDef(uuids::uuid const &flowId) const
std::pair< bool, std::unique_ptr< DiscreteFlowData > > createOrOpenDiscreteFlow(uuids::uuid const &flowId, std::string const &flowDef, mxlDataFormat flowFormat, std::size_t grainCount, mxlRational const &grainRate, std::size_t grainPayloadSize, std::size_t grainNumOfSlices, std::array< std::uint32_t, MXL_MAX_PLANES_PER_GRAIN > grainSliceLengths, std::uint32_t maxSyncBatchSizeHintOpt=1, std::uint32_t maxCommitBatchSizeHintOpt=1)
std::filesystem::path const & getDomain() const
std::pair< bool, std::unique_ptr< ContinuousFlowData > > createOrOpenContinuousFlow(uuids::uuid const &flowId, std::string const &flowDef, mxlDataFormat flowFormat, mxlRational const &sampleRate, std::size_t channelCount, std::size_t sampleWordSize, std::size_t bufferLength, std::uint32_t maxSyncBatchSizeHintOpt=1, std::uint32_t maxCommitBatchSizeHintOpt=1)
std::unique_ptr< FlowData > openFlow(uuids::uuid const &flowId, AccessMode mode)
Public flow reader, writer, payload and synchronization APIs.
@ MXL_PAYLOAD_LOCATION_HOST_MEMORY
struct mxlCommonFlowConfigInfo_t mxlCommonFlowConfigInfo
struct mxlFlowRuntimeInfo_t mxlFlowRuntimeInfo
std::filesystem::path makeChannelDataFilePath(std::filesystem::path const &flowDirectory)
std::filesystem::path makeEventDataFilePath(std::filesystem::path const &flowDirectory)
Locate an event ring file within its flow directory.
std::filesystem::path makeFlowDescriptorFilePath(std::filesystem::path const &flowDirectory)
std::filesystem::path makeFlowAccessFilePath(std::filesystem::path const &flowDirectory)
constexpr auto GRAIN_HEADER_VERSION
The version of the grain header structs in shared memory that we expect an support.
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
constexpr Deferred< F > defer(F &&f) noexcept
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX
std::unique_ptr< To > dynamic_pointer_cast(std::unique_ptr< From > &&source) noexcept
std::filesystem::path makeGrainDirectoryName(std::filesystem::path const &flowDirectory)
std::filesystem::path makeFlowDirectoryName(std::filesystem::path const &domain, std::string const &uuid)
constexpr auto FLOW_DATA_VERSION
The version of the flow data structs in shared memory that we expect and support.
std::filesystem::path makeGrainDataFilePath(std::filesystem::path const &grainDirectory, unsigned int index)
#define MXL_UNDEFINED_INDEX
struct mxlRational_t mxlRational
mxlGrainInfo gInfo
Open the grain.