20#include <picojson/wrapper.h>
21#include <spdlog/cfg/env.h>
22#include <spdlog/sinks/stdout_color_sinks.h>
23#include <spdlog/spdlog.h>
39 constexpr auto MXL_HISTORY_DURATION_OPTION =
"urn:x-mxl:option:history_duration/v1.0";
41 std::once_flag loggingFlag;
43 void initializeLogging()
45 auto console = spdlog::stdout_color_mt(
"console");
46 spdlog::set_default_logger(console);
47 spdlog::cfg::load_env_levels(
"MXL_LOG_LEVEL");
55 bool parseOptionsJson(std::string
const& options, picojson::object& config)
57 picojson::value parsed;
58 std::string err =
parseJson(parsed, options);
61 MXL_ERROR(
"Failed to parse options json: {}", err);
65 if (!parsed.is<picojson::object>())
71 config = parsed.get<picojson::object>();
83 std::uint64_t readDomainHistoryDuration(std::filesystem::path
const& path, std::uint64_t fallback)
85 auto const file = std::ifstream{path};
89 auto error = std::error_code{};
90 if (std::filesystem::exists(path, error) || error)
92 MXL_ERROR(
"Failed to open domain options file: {}", path.string());
96 auto buffer = std::stringstream{};
98 auto const json =
buffer.str();
99 auto config = picojson::object{};
100 if (!parseOptionsJson(json, config))
102 MXL_ERROR(
"Failed to parse domain specific options: {}", json);
105 auto const it = config.find(MXL_HISTORY_DURATION_OPTION);
106 if ((it == config.end()) || !it->second.is<
double>())
113 MXL_TRACE(
"Found history duration option in domain specific options: {}ns", duration);
116 catch (std::invalid_argument
const& e)
118 MXL_ERROR(
"Ignoring domain history duration option: {}", e.what());
125 Instance::Instance(std::filesystem::path
const& mxlDomain, std::string
const& options, std::unique_ptr<FlowIoFactory>&& flowIoFactory,
126 DomainWatcher::ptr watcher)
138 std::call_once(loggingFlag, [&]() { initializeLogging(); });
140 MXL_DEBUG(
"Instance created. MXL Domain: {}", mxlDomain.string());
153 if (
writer.get()->isExclusive() ||
writer.get()->makeExclusive())
155 MXL_WARN(
"Cleaning up flow '{}' of leaked flow writer.", uuids::to_string(
id));
160 catch (std::exception
const& ex)
162 MXL_ERROR(
"Failed to clean up leaked flow writer: {}", ex.what());
166 spdlog::default_logger()->flush();
171 auto const id = uuids::uuid::from_string(
flowId);
174 throw std::invalid_argument{
"Invalid flow id: '" +
flowId +
"'."};
177 auto const lock = std::scoped_lock{
_mutex};
180 auto& v = (*pos).second;
189 return (*
_readers.try_emplace(pos, *
id, std::move(
reader))).second.get();
197 auto const&
id =
reader->getId();
199 auto const lock = std::scoped_lock{
_mutex};
202 if ((*pos).second.releaseReference())
207 group.removeReader(*
reader);
219 auto const id =
writer->getId();
221 auto const lock = std::scoped_lock{
_mutex};
224 if ((*pos).second.releaseReference())
241 auto const lock = std::scoped_lock{
_mutex};
244 auto created =
false;
245 auto flowData = std::unique_ptr<FlowData>{};
250 flowData = std::move(rFlowData);
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))
259 throw std::invalid_argument(
"Invalid event count.");
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;
269 flowData = std::move(rFlowData);
270 created = rWasCreated;
274 throw std::runtime_error(
"Invalid flow format.");
277 auto id = uuids::uuid{flowData->flowInfo()->config.common.id};
278 auto flowConfigInfo = flowData->flowInfo()->config;
282 auto& v = (*pos).second;
284 return {flowConfigInfo, v.get(), created};
290 return {flowConfigInfo, (*
_writers.try_emplace(pos,
id, std::move(
writer))).second.get(), created};
300 auto const grainCount =
_historyDuration * grainRate.numerator / (1'000'000'000ULL * grainRate.denominator);
315 return {std::move(flowData), created};
327 auto const bufferLength =
_historyDuration * sampleRate.numerator / (500'000'000ULL * sampleRate.denominator);
331 auto const lengthPerPage = 4096U / sampleWordSize;
333 auto const pageAlignedLength = ((bufferLength + lengthPerPage - 1U) / lengthPerPage) * lengthPerPage;
338 auto [created, flowData] =
_flowManager.createOrOpenContinuousFlow(parser.
getId(),
348 return {std::move(flowData), created};
366 auto count = std::size_t{};
369 auto const base = std::filesystem::path{
_flowManager.getDomain()};
370 if (!is_directory(base))
372 MXL_DEBUG(
"MXL domain {} does not exist or is not a directory", base.string());
375 for (
auto const& entry : std::filesystem::directory_iterator{base})
382 if (!std::filesystem::exists(flowDataFile))
384 MXL_DEBUG(
"Flow data file {} does not exist", flowDataFile.string());
389 constexpr auto flags = O_RDONLY | O_CLOEXEC;
391 constexpr auto flags = O_RDONLY | O_CLOEXEC | O_NOATIME;
393 auto const fd = ::open(flowDataFile.c_str(),
flags);
395 auto const active = ::flock(fd, LOCK_EX | LOCK_NB) < 0;
401 auto ec = std::error_code{};
402 std::filesystem::remove_all(entry.path(), ec);
405 MXL_DEBUG(
"Failed to remove '{}': {} (error code {})", entry.path().string(), ec.message(), ec.value());
411 catch (std::exception
const& e)
413 MXL_DEBUG(
"Failed to perform garbage collection: {}", e.what());
417 MXL_DEBUG(
"Failed to perform garbage collection");
427 if (!options.empty())
429 auto config = picojson::object{};
430 if (!parseOptionsJson(options, config))
432 MXL_ERROR(
"Failed to parse instance specific options: {}", options);
451 for (
auto current = std::next(prev); current !=
_syncGroups.end(); ++current)
453 if (&(*current) == group)
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.
FlowSynchronizationGroup * createFlowSynchronizationGroup()
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenDiscreteFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
std::map< uuids::uuid, RefCounted< FlowReader > > _readers
Maps flow uuids to flow readers.
std::string _options
For future use.
void releaseReader(FlowReader *reader)
~Instance()
Dtor. Release all readers and writers.
void releaseFlowSynchronizationGroup(FlowSynchronizationGroup const *group)
std::string getDomain() const
std::forward_list< FlowSynchronizationGroup > _syncGroups
The set of active flow synchronization groups.
std::unique_ptr< FlowIoFactory > _flowIoFactory
The I/O factor used to delegate the creation of readers and writers.
std::atomic_bool _stopping
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenContinuousFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
std::uint64_t _historyDuration
Ring buffer history duration in nanoseconds.
void releaseWriter(FlowWriter *writer)
std::tuple< mxlFlowConfigInfo, FlowWriter *, bool > createFlowWriter(std::string const &flowDef, std::optional< std::string > options={})
std::map< uuids::uuid, RefCounted< FlowWriter > > _writers
Maps flow uuids to flow writers.
std::uint64_t getHistoryDurationNs() const
FlowReader * getFlowReader(std::string const &flowId)
Instance(std::filesystem::path const &mxlDomain, std::string const &options, std::unique_ptr< FlowIoFactory > &&flowIoFactory, DomainWatcher::ptr watcher)
std::mutex _mutex
Protects the maps.
std::size_t garbageCollect() const
DomainWatcher::ptr _watcher
void parseOptions(std::string const &options)
std::string getFlowDef(uuids::uuid const &flowId) const
Public flow reader, writer, payload and synchronization APIs.
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
std::filesystem::path makeDomainOptionsFilePath(std::filesystem::path const &domain)
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX
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={})
uint8_t * buffer
Set a mark at the beginning and the end of the grain payload.
gInfo flags
Mark the grain as invalid.