MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
Instance.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
5#include <cstddef>
6#include <cstdint>
7#include <cstring>
8#include <filesystem>
9#include <fstream>
10#include <memory>
11#include <mutex>
12#include <stdexcept>
13#include <string>
14#include <fcntl.h>
15#include <unistd.h>
16#include <uuid.h>
17#include <sys/file.h>
18#include <sys/stat.h>
19#include <sys/types.h>
20#include <picojson/wrapper.h>
21#include <spdlog/cfg/env.h>
22#include <spdlog/sinks/stdout_color_sinks.h>
23#include <spdlog/spdlog.h>
24#include <mxl/flow.h>
25#include <mxl/mxl.h>
26#include <mxl/time.h>
34
35namespace mxl::lib
36{
37 namespace
38 {
39 constexpr auto MXL_HISTORY_DURATION_OPTION = "urn:x-mxl:option:history_duration/v1.0";
40
41 std::once_flag loggingFlag;
42
43 void initializeLogging()
44 {
45 auto console = spdlog::stdout_color_mt("console");
46 spdlog::set_default_logger(console);
47 spdlog::cfg::load_env_levels("MXL_LOG_LEVEL");
48 }
49
55 bool parseOptionsJson(std::string const& options, picojson::object& config)
56 {
57 picojson::value parsed;
58 std::string err = parseJson(parsed, options);
59 if (!err.empty())
60 {
61 MXL_ERROR("Failed to parse options json: {}", err);
62 return false;
63 }
64
65 if (!parsed.is<picojson::object>())
66 {
67 return false;
68 }
69
70 // Assign the json object config
71 config = parsed.get<picojson::object>();
72
73 return true;
74 }
75
83 std::uint64_t readDomainHistoryDuration(std::filesystem::path const& path, std::uint64_t fallback)
84 {
85 auto const file = std::ifstream{path};
86 if (!file)
87 {
88 // Missing options are expected; report other open failures.
89 auto error = std::error_code{};
90 if (std::filesystem::exists(path, error) || error)
91 {
92 MXL_ERROR("Failed to open domain options file: {}", path.string());
93 }
94 return fallback;
95 }
96 auto buffer = std::stringstream{};
97 buffer << file.rdbuf();
98 auto const json = buffer.str();
99 auto config = picojson::object{};
100 if (!parseOptionsJson(json, config))
101 {
102 MXL_ERROR("Failed to parse domain specific options: {}", json);
103 return fallback;
104 }
105 auto const it = config.find(MXL_HISTORY_DURATION_OPTION);
106 if ((it == config.end()) || !it->second.is<double>())
107 {
108 return fallback;
109 }
110 try
111 {
112 auto const duration = jsonToInteger<std::uint64_t>(it->second, MXL_HISTORY_DURATION_OPTION);
113 MXL_TRACE("Found history duration option in domain specific options: {}ns", duration);
114 return duration;
115 }
116 catch (std::invalid_argument const& e)
117 {
118 MXL_ERROR("Ignoring domain history duration option: {}", e.what());
119 return fallback;
120 }
121 }
122
123 }
124
125 Instance::Instance(std::filesystem::path const& mxlDomain, std::string const& options, std::unique_ptr<FlowIoFactory>&& flowIoFactory,
126 DomainWatcher::ptr watcher)
127 : _flowManager{mxlDomain}
128 , _flowIoFactory{std::move(flowIoFactory)}
129 , _readers{}
130 , _writers{}
131 , _mutex{}
132 , _syncGroups{}
133 , _options{options}
134 , _historyDuration{200'000'000ULL}
135 , _watcher{std::move(watcher)}
136 , _stopping{false}
137 {
138 std::call_once(loggingFlag, [&]() { initializeLogging(); });
139 parseOptions(options);
140 MXL_DEBUG("Instance created. MXL Domain: {}", mxlDomain.string());
141 }
142
144 {
145 _stopping = true;
146 _watcher->stop();
147 MXL_DEBUG("Instance destroyed.");
148
149 for (auto& [id, writer] : _writers)
150 {
151 try
152 {
153 if (writer.get()->isExclusive() || writer.get()->makeExclusive())
154 {
155 MXL_WARN("Cleaning up flow '{}' of leaked flow writer.", uuids::to_string(id));
156
157 _flowManager.deleteFlow(id);
158 }
159 }
160 catch (std::exception const& ex)
161 {
162 MXL_ERROR("Failed to clean up leaked flow writer: {}", ex.what());
163 }
164 }
165
166 spdlog::default_logger()->flush();
167 }
168
170 {
171 auto const id = uuids::uuid::from_string(flowId);
172 if (!id.has_value())
173 {
174 throw std::invalid_argument{"Invalid flow id: '" + flowId + "'."};
175 }
176
177 auto const lock = std::scoped_lock{_mutex};
178 if (auto const pos = _readers.find(*id); pos != _readers.end())
179 {
180 auto& v = (*pos).second;
181 v.addReference();
182 return v.get();
183 }
184 else
185 {
186 auto flowData = _flowManager.openFlow(*id, AccessMode::READ_ONLY);
187 auto reader = _flowIoFactory->createFlowReader(_flowManager, *id, std::move(flowData));
188
189 return (*_readers.try_emplace(pos, *id, std::move(reader))).second.get();
190 }
191 }
192
194 {
195 if (reader)
196 {
197 auto const& id = reader->getId();
198
199 auto const lock = std::scoped_lock{_mutex};
200 if (auto const pos = _readers.find(id); pos != _readers.end())
201 {
202 if ((*pos).second.releaseReference())
203 {
204 // Remove from the synchronization groups
205 for (auto& group : _syncGroups)
206 {
207 group.removeReader(*reader);
208 }
209 _readers.erase(pos);
210 }
211 }
212 }
213 }
214
216 {
217 if (writer)
218 {
219 auto const id = writer->getId();
220 {
221 auto const lock = std::scoped_lock{_mutex};
222 if (auto const pos = _writers.find(id); pos != _writers.end())
223 {
224 if ((*pos).second.releaseReference())
225 {
226 // Delete the flow if we are the last writer.
227 if (writer->isExclusive() || writer->makeExclusive())
228 {
229 _flowManager.deleteFlow(id);
230 }
231
232 _writers.erase(pos);
233 }
234 }
235 }
236 }
237 }
238
239 std::tuple<mxlFlowConfigInfo, FlowWriter*, bool> Instance::createFlowWriter(std::string const& flowDef, std::optional<std::string> options)
240 {
241 auto const lock = std::scoped_lock{_mutex};
242 auto const parser = FlowParser{flowDef};
243 auto const optionsParser = (options) ? FlowOptionsParser{*options} : FlowOptionsParser{};
244 auto created = false;
245 auto flowData = std::unique_ptr<FlowData>{};
246
247 if (auto const format = parser.getFormat(); mxlIsDiscreteDataFormat(format))
248 {
249 auto [rFlowData, rCreated] = createOrOpenDiscreteFlowData(flowDef, parser, optionsParser);
250 flowData = std::move(rFlowData);
251 created = rCreated;
252 }
253 else if (format == MXL_DATA_FORMAT_EVENT)
254 {
255 auto const grainRate = parser.getGrainRate();
256 auto const eventCount = _historyDuration * __int128_t{grainRate.numerator} / (1'000'000'000 * __int128_t{grainRate.denominator});
257 if ((eventCount < 2) || (eventCount > 65536))
258 {
259 throw std::invalid_argument("Invalid event count.");
260 }
261 auto [wasCreated, data] = _flowManager.createOrOpenEventFlow(
262 parser.getId(), flowDef, static_cast<std::size_t>(eventCount), grainRate, parser.getPayloadSize());
263 flowData = std::move(data);
264 created = wasCreated;
265 }
266 else if (mxlIsContinuousDataFormat(format))
267 {
268 auto [rFlowData, rWasCreated] = createOrOpenContinuousFlowData(flowDef, parser, optionsParser);
269 flowData = std::move(rFlowData);
270 created = rWasCreated;
271 }
272 else
273 {
274 throw std::runtime_error("Invalid flow format.");
275 }
276
277 auto id = uuids::uuid{flowData->flowInfo()->config.common.id};
278 auto flowConfigInfo = flowData->flowInfo()->config;
279
280 if (auto const pos = _writers.find(id); pos != _writers.end())
281 {
282 auto& v = (*pos).second;
283 v.addReference();
284 return {flowConfigInfo, v.get(), created};
285 }
286 else
287 {
288 auto writer = _flowIoFactory->createFlowWriter(_flowManager, id, std::move(flowData));
289
290 return {flowConfigInfo, (*_writers.try_emplace(pos, id, std::move(writer))).second.get(), created};
291 }
292 }
293
294 std::pair<std::unique_ptr<FlowData>, bool> Instance::createOrOpenDiscreteFlowData(std::string const& flowDef, FlowParser const& parser,
295 FlowOptionsParser const& optionsParser)
296 {
297 // Read the mandatory grain_rate field
298 auto const grainRate = parser.getGrainRate();
299 // Compute the grain count based on our configured history duration
300 auto const grainCount = _historyDuration * grainRate.numerator / (1'000'000'000ULL * grainRate.denominator);
301
302 auto const batchSizeDefault = parser.getTotalPayloadSlices();
303
304 auto [created, flowData] = _flowManager.createOrOpenDiscreteFlow(parser.getId(),
305 flowDef,
306 parser.getFormat(),
307 grainCount,
308 grainRate,
309 parser.getPayloadSize(),
310 parser.getTotalPayloadSlices(),
311 parser.getPayloadSliceLengths(),
312 optionsParser.getMaxSyncBatchSizeHint().value_or(batchSizeDefault),
313 optionsParser.getMaxCommitBatchSizeHint().value_or(batchSizeDefault));
314
315 return {std::move(flowData), created};
316 }
317
318 std::pair<std::unique_ptr<FlowData>, bool> Instance::createOrOpenContinuousFlowData(std::string const& flowDef, FlowParser const& parser,
319 FlowOptionsParser const& optionsParser)
320 {
321 // Read the mandatory grain_rate field
322 auto const sampleRate = parser.getGrainRate();
323 // Compute the buffer length based on our configured history duration.
324 // The length is divided by 500M instead of 1B to effectively make it twice the
325 // history duration, which is necessary, because only half of the buffer is
326 // accessible for reading at any one point in time.
327 auto const bufferLength = _historyDuration * sampleRate.numerator / (500'000'000ULL * sampleRate.denominator);
328
329 auto const sampleWordSize = parser.getPayloadSize();
330 // FIXME: The page size is just an educated guess to round to for good measure
331 auto const lengthPerPage = 4096U / sampleWordSize;
332
333 auto const pageAlignedLength = ((bufferLength + lengthPerPage - 1U) / lengthPerPage) * lengthPerPage;
334
335 // Default to 10ms worth of samples
336 auto batchSizeDefault = parser.getGrainRate().numerator / (100U * parser.getGrainRate().denominator);
337
338 auto [created, flowData] = _flowManager.createOrOpenContinuousFlow(parser.getId(),
339 flowDef,
340 parser.getFormat(),
341 sampleRate,
342 parser.getChannelCount(),
343 sampleWordSize,
344 pageAlignedLength,
345 optionsParser.getMaxSyncBatchSizeHint().value_or(batchSizeDefault),
346 optionsParser.getMaxCommitBatchSizeHint().value_or(batchSizeDefault));
347
348 return {std::move(flowData), created};
349 }
350
351 std::string Instance::getDomain() const
352 {
353 return _flowManager.getDomain();
354 }
355
356 std::string Instance::getFlowDef(uuids::uuid const& flowId) const
357 {
358 return _flowManager.getFlowDef(flowId);
359 }
360
361 // This function is performed in a 'collaborative best effort' way.
362 // Exceptions thrown should not be propagated to the caller and cause disruptions to the application.
363 // On error the function will return 0 and log the error
364 std::size_t Instance::garbageCollect() const
365 {
366 auto count = std::size_t{};
367 try
368 {
369 auto const base = std::filesystem::path{_flowManager.getDomain()};
370 if (!is_directory(base))
371 {
372 MXL_DEBUG("MXL domain {} does not exist or is not a directory", base.string());
373 return count;
374 }
375 for (auto const& entry : std::filesystem::directory_iterator{base})
376 {
377 if (!is_directory(entry) || (entry.path().extension() != mxl::lib::FLOW_DIRECTORY_NAME_SUFFIX))
378 {
379 continue;
380 }
381 auto const flowDataFile = mxl::lib::makeFlowDataFilePath(_flowManager.getDomain(), entry.path().stem().string());
382 if (!std::filesystem::exists(flowDataFile))
383 {
384 MXL_DEBUG("Flow data file {} does not exist", flowDataFile.string());
385 continue;
386 }
387
388#ifdef __APPLE__
389 constexpr auto flags = O_RDONLY | O_CLOEXEC;
390#else
391 constexpr auto flags = O_RDONLY | O_CLOEXEC | O_NOATIME;
392#endif
393 auto const fd = ::open(flowDataFile.c_str(), flags);
394 // An exclusive lock indicates that no producer is using the flow.
395 auto const active = ::flock(fd, LOCK_EX | LOCK_NB) < 0;
396 ::close(fd);
397 if (active)
398 {
399 continue;
400 }
401 auto ec = std::error_code{};
402 std::filesystem::remove_all(entry.path(), ec);
403 if (ec)
404 {
405 MXL_DEBUG("Failed to remove '{}': {} (error code {})", entry.path().string(), ec.message(), ec.value());
406 continue;
407 }
408 ++count;
409 }
410 }
411 catch (std::exception const& e)
412 {
413 MXL_DEBUG("Failed to perform garbage collection: {}", e.what());
414 }
415 catch (...)
416 {
417 MXL_DEBUG("Failed to perform garbage collection");
418 }
419 return count;
420 }
421
422 void Instance::parseOptions(std::string const& options)
423 {
424 _historyDuration = readDomainHistoryDuration(makeDomainOptionsFilePath(_flowManager.getDomain()), _historyDuration);
425
426 // Instance options are validated but do not override domain history duration.
427 if (!options.empty())
428 {
429 auto config = picojson::object{};
430 if (!parseOptionsJson(options, config))
431 {
432 MXL_ERROR("Failed to parse instance specific options: {}", options);
433 }
434 }
435 MXL_DEBUG("History duration set to {} ns", _historyDuration);
436 }
437
438 std::uint64_t Instance::getHistoryDurationNs() const
439 {
440 return _historyDuration;
441 }
442
447
449 {
450 auto prev = _syncGroups.before_begin();
451 for (auto current = std::next(prev); current != _syncGroups.end(); ++current)
452 {
453 if (&(*current) == group)
454 {
455 _syncGroups.erase_after(prev);
456 return;
457 }
458 prev = current;
459 }
460 }
461} // namespace mxl::lib
#define MXL_ERROR(...)
Definition Logging.hpp:67
#define MXL_WARN(...)
Definition Logging.hpp:56
#define MXL_DEBUG(...)
Definition Logging.hpp:34
#define MXL_TRACE(...)
Definition Logging.hpp:23
Paths and filenames utilities used by the MXL SDK.
std::optional< std::uint32_t > getMaxCommitBatchSizeHint() const
std::optional< std::uint32_t > getMaxSyncBatchSizeHint() const
std::array< std::uint32_t, MXL_MAX_PLANES_PER_GRAIN > getPayloadSliceLengths() const
mxlDataFormat getFormat() const
std::size_t getTotalPayloadSlices() const
mxlRational getGrainRate() const
std::size_t getChannelCount() const
std::size_t getPayloadSize() const
uuids::uuid const & getId() const
FlowManager _flowManager
Performs flow CRUD operations.
Definition Instance.hpp:167
FlowSynchronizationGroup * createFlowSynchronizationGroup()
Definition Instance.cpp:443
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenDiscreteFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
Definition Instance.cpp:294
std::map< uuids::uuid, RefCounted< FlowReader > > _readers
Maps flow uuids to flow readers.
Definition Instance.hpp:173
std::string _options
For future use.
Definition Instance.hpp:184
void releaseReader(FlowReader *reader)
Definition Instance.cpp:193
~Instance()
Dtor. Release all readers and writers.
Definition Instance.cpp:143
void releaseFlowSynchronizationGroup(FlowSynchronizationGroup const *group)
Definition Instance.cpp:448
std::string getDomain() const
Definition Instance.cpp:351
std::forward_list< FlowSynchronizationGroup > _syncGroups
The set of active flow synchronization groups.
Definition Instance.hpp:181
std::unique_ptr< FlowIoFactory > _flowIoFactory
The I/O factor used to delegate the creation of readers and writers.
Definition Instance.hpp:170
std::atomic_bool _stopping
Definition Instance.hpp:191
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenContinuousFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
Definition Instance.cpp:318
std::uint64_t _historyDuration
Ring buffer history duration in nanoseconds.
Definition Instance.hpp:187
void releaseWriter(FlowWriter *writer)
Definition Instance.cpp:215
std::tuple< mxlFlowConfigInfo, FlowWriter *, bool > createFlowWriter(std::string const &flowDef, std::optional< std::string > options={})
Definition Instance.cpp:239
std::map< uuids::uuid, RefCounted< FlowWriter > > _writers
Maps flow uuids to flow writers.
Definition Instance.hpp:175
std::uint64_t getHistoryDurationNs() const
Definition Instance.cpp:438
FlowReader * getFlowReader(std::string const &flowId)
Definition Instance.cpp:169
Instance(std::filesystem::path const &mxlDomain, std::string const &options, std::unique_ptr< FlowIoFactory > &&flowIoFactory, DomainWatcher::ptr watcher)
Definition Instance.cpp:125
std::mutex _mutex
Protects the maps.
Definition Instance.hpp:178
std::size_t garbageCollect() const
Definition Instance.cpp:364
DomainWatcher::ptr _watcher
Definition Instance.hpp:189
void parseOptions(std::string const &options)
Definition Instance.cpp:422
std::string getFlowDef(uuids::uuid const &flowId) const
Definition Instance.cpp:356
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
Public flow reader, writer, payload and synchronization APIs.
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:17
std::filesystem::path makeDomainOptionsFilePath(std::filesystem::path const &domain)
Definition PathUtils.cpp:59
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX
Definition PathUtils.hpp:14
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
T jsonToInteger(picojson::value const &value, std::string_view name)
std::string parseJson(picojson::value &out, std::string_view text, JsonLimits const &limits={})
int64_t numerator
Definition rational.h:21
bool active
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.
mxlFlowReader reader
mxlFlowWriter writer
auto const flowId
auto flowDef
gInfo flags
Mark the grain as invalid.