MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
PosixDiscreteFlowReader.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 <cstdint>
6#include <cstdio>
7#include <ctime>
8#include <algorithm>
9#include <array>
10#include <filesystem>
11#include <mutex>
12#include <stdexcept>
13#include <fcntl.h>
14#include <unistd.h>
15#include <uuid.h>
16#include <sys/stat.h>
17#include <mxl/flow.h>
18#include <mxl/mxl.h>
19#include <mxl/time.h>
20#include "mxl-internal/Flow.hpp"
25#include "mxl-internal/Sync.hpp"
26
27namespace mxl::lib
28{
29 namespace
30 {
31 bool updateFileAccessTime(int fd) noexcept
32 {
33 auto const times = std::array<timespec, 2>{
34 {{0, UTIME_NOW}, {0, UTIME_OMIT}}
35 };
36 return (::futimens(fd, times.data()) == 0);
37 }
38 }
39
40 PosixDiscreteFlowReader::PosixDiscreteFlowReader(FlowManager const& manager, uuids::uuid const& flowId, std::unique_ptr<DiscreteFlowData>&& data)
42 , _flowData{std::move(data)}
43 , _accessFileFd{-1}
44 {
45 auto const accessFile = makeFlowAccessFilePath(manager.getDomain(), to_string(flowId));
46 _accessFileFd = ::open(accessFile.string().c_str(), O_RDWR);
47
48 // Opening the access file may fail if the domain is in a read only volume.
49 // we can still execute properly but the 'lastReadTime' will never be updated.
50 // Ignore failures.
51 }
52
54 {
55 if (_accessFileFd != -1)
56 {
57 if (::close(_accessFileFd) != 0)
58 {
59 auto const error = errno;
60 MXL_ERROR("Failed to close access file fd: {}", ::strerror(error));
61 }
62 _accessFileFd = -1;
63 }
64 }
65
67 {
68 if (_flowData)
69 {
70 return *_flowData;
71 }
72 throw std::runtime_error("No open flow.");
73 }
74
79
84
89
90 mxlStatus PosixDiscreteFlowReader::waitForGrain(std::uint64_t in_index, std::uint16_t in_minValidSlices, Timepoint in_deadline) const
91 {
92 auto result = MXL_ERR_UNKNOWN;
93 if (_flowData)
94 {
95 result = getGrainImpl(in_index, in_minValidSlices, in_deadline, nullptr, nullptr);
97 {
98 // If we were ultimately too early, even with blocking for a certain amount
99 // of time it could very well be that we're operating on a stale flow, so we
100 // use the opportunity to check whether it's valid.
101 if (!isFlowValidImpl())
102 {
103 result = MXL_ERR_FLOW_INVALID;
104 }
105 }
106 }
107 return result;
108 }
109
110 mxlStatus PosixDiscreteFlowReader::getGrain(std::uint64_t in_index, std::uint16_t in_minValidSlices, Timepoint in_deadline,
111 mxlGrainInfo* out_grainInfo, std::uint8_t** out_payload)
112 {
113 auto result = MXL_ERR_UNKNOWN;
114 if (_flowData)
115 {
116 result = getGrainImpl(in_index, in_minValidSlices, in_deadline, out_grainInfo, out_payload);
117 if (result == MXL_STATUS_OK)
118 {
119 // We ignore the return value of updateFileAccessTime. It may fail if the domain is in a read-only volume.
120 (void)updateFileAccessTime(_accessFileFd);
121 }
122 else if (result == MXL_ERR_OUT_OF_RANGE_TOO_EARLY)
123 {
124 // If we were ultimately too early, even with blocking for a certain amount
125 // of time it could very well be that we're operating on a stale flow, so we
126 // use the opportunity to check whether it's valid.
127 if (!isFlowValidImpl())
128 {
129 result = MXL_ERR_FLOW_INVALID;
130 }
131 }
132 }
133 return result;
134 }
135
136 mxlStatus PosixDiscreteFlowReader::getGrain(std::uint64_t in_index, std::uint16_t in_minValidSlices, mxlGrainInfo* out_grainInfo,
137 std::uint8_t** out_payload)
138 {
139 auto result = MXL_ERR_UNKNOWN;
140 if (_flowData)
141 {
142 result = getGrainImpl(in_index, in_minValidSlices, out_grainInfo, out_payload);
143 if (result == MXL_STATUS_OK)
144 {
145 // We ignore the return value of updateFileAccessTime. It may fail if the domain is in a read-only volume.
146 (void)updateFileAccessTime(_accessFileFd);
147 }
148 else if (result == MXL_ERR_OUT_OF_RANGE_TOO_EARLY)
149 {
150 // If we were too early it could very well be that we're operating
151 // on a stale flow, so we use the opportunity to check whether it's
152 // valid.
153 if (!isFlowValidImpl())
154 {
155 result = MXL_ERR_FLOW_INVALID;
156 }
157 }
158 }
159 return result;
160 }
161
162 mxlStatus PosixDiscreteFlowReader::getGrainImpl(std::uint64_t in_index, std::uint16_t in_minValidSlices, mxlGrainInfo* out_grainInfo,
163 std::uint8_t** out_payload) const
164 {
165 auto result = MXL_ERR_UNKNOWN;
166 auto const flow = _flowData->flow();
167 if (auto const headIndex = flow->info.runtime.headIndex; in_index <= headIndex)
168 {
169 auto const grainCount = flow->info.config.discrete.grainCount;
170
171 // Reserve the tail position for the writer. The +2U advances
172 // minIndex one position past the tail. Since the tail and
173 // headIndex+1 alias the same physical ring-buffer position,
174 // this hides uncommitted headIndex+1 write state from
175 // readers.
176 auto const minIndex = (headIndex >= grainCount) ? (headIndex - grainCount + 2U) : std::uint64_t{0};
177
178 if (in_index >= minIndex)
179 {
180 auto const offset = in_index % grainCount;
181 auto const grain = _flowData->grainAt(offset);
182
183 // The header lives in shared memory and any process that can open the flow can write it. Check a copy so that the
184 // values tested are the values returned.
185 auto const info = grain->header.info;
186 if ((info.grainSize > _flowData->grainPayloadCapacityAt(offset)) || (info.validSlices > info.totalSlices))
187 {
188 MXL_ERROR("Grain {} has an inconsistent header: grainSize={}, totalSlices={}, validSlices={}",
189 in_index,
190 info.grainSize,
191 info.totalSlices,
192 info.validSlices);
194 }
195
196 if ((info.validSlices >= std::min(in_minValidSlices, info.totalSlices)) || ((info.flags & MXL_GRAIN_FLAG_INVALID) != 0))
197 {
198 if (out_grainInfo != nullptr)
199 {
200 *out_grainInfo = info;
201 }
202 if (out_payload != nullptr)
203 {
204 *out_payload = reinterpret_cast<std::uint8_t*>(&grain->header + 1);
205 }
206
207 result = MXL_STATUS_OK;
208 }
209 else
210 {
212 }
213 }
214 else
215 {
217 }
218 }
219 else
220 {
222 }
223
224 return result;
225 }
226
227 mxlStatus PosixDiscreteFlowReader::getGrainImpl(std::uint64_t in_index, std::uint16_t in_minValidSlices, Timepoint in_deadline,
228 mxlGrainInfo* out_grainInfo, std::uint8_t** out_payload) const
229 {
230 auto const flow = _flowData->flow();
231 auto const syncObject = std::atomic_ref{flow->state.syncCounter};
232 while (true)
233 {
234 // We remember the sync counter before checking the head index, otherwise we would introduce a race condition:
235 // 1. We check the header index, data won't be available yet.
236 // 2. Writer writes the data and updates the counter.
237 // 3. If we used the current value of the counter for the futex, we would delay everything by 1 grain.
238 auto const previousSyncCounter = syncObject.load(std::memory_order_acquire);
239 auto const result = getGrainImpl(in_index, in_minValidSlices, out_grainInfo, out_payload);
240 // NOTE: Before C++26 there is no way to access the address of the object wrapped
241 // by an atomic_ref. If there were it would be much more appropriate to pass
242 // syncObject by reference here and only unwrap the underlying integer in the
243 // implementation of waitUntilChanged.
244 if ((result != MXL_ERR_OUT_OF_RANGE_TOO_EARLY) || !waitUntilChanged(&flow->state.syncCounter, previousSyncCounter, in_deadline))
245 {
246 return result;
247 }
248 }
249 }
250
252 {
253 return _flowData && isFlowValidImpl();
254 }
255
257 {
258 auto const flowState = _flowData->flowState();
259 auto const flowDataPath = makeFlowDataFilePath(getDomain(), to_string(getId()));
260
261 struct stat st;
262 if (::stat(flowDataPath.string().c_str(), &st) != 0)
263 {
264 return false;
265 }
266 return (st.st_ino == flowState->inode);
267 }
268}
Internal shared-memory headers for discrete grains and event slots.
#define MXL_ERROR(...)
Definition Logging.hpp:67
Paths and filenames utilities used by the MXL SDK.
constexpr mxlFlowInfo * flowInfo() noexcept
Definition FlowData.hpp:92
std::filesystem::path const & getDomain() const
uuids::uuid const & getId() const
std::filesystem::path const & getDomain() const
virtual FlowData const & getFlowData() const override
PosixDiscreteFlowReader(FlowManager const &manager, uuids::uuid const &flowId, std::unique_ptr< DiscreteFlowData > &&data)
virtual bool isFlowValid() const override
virtual mxlFlowInfo getFlowInfo() const override
std::unique_ptr< DiscreteFlowData > _flowData
virtual mxlFlowConfigInfo getFlowConfigInfo() const override
virtual mxlFlowRuntimeInfo getFlowRuntimeInfo() const override
virtual mxlStatus getGrain(std::uint64_t in_index, std::uint16_t in_minValidSlices, Timepoint in_deadline, mxlGrainInfo *out_grainInfo, std::uint8_t **out_payload) override
mxlStatus getGrainImpl(std::uint64_t in_index, std::uint16_t in_minValidSlices, mxlGrainInfo *out_grainInfo, std::uint8_t **out_payload) const
virtual mxlStatus waitForGrain(std::uint64_t in_index, std::uint16_t in_minValidSlices, Timepoint in_deadline) const override
Public flow reader, writer, payload and synchronization APIs.
struct mxlGrainInfo_t mxlGrainInfo
#define MXL_GRAIN_FLAG_INVALID
Definition flow.h:33
struct mxlFlowRuntimeInfo_t mxlFlowRuntimeInfo
struct mxlFlowConfigInfo_t mxlFlowConfigInfo
struct mxlFlowInfo_t mxlFlowInfo
mxlStatus
MXL SDK Status codes.
Definition mxl.h:22
@ MXL_ERR_FLOW_INVALID
Definition mxl.h:41
@ MXL_ERR_INVALID_STATE
Definition mxl.h:47
@ MXL_ERR_UNKNOWN
Definition mxl.h:27
@ MXL_ERR_OUT_OF_RANGE_TOO_EARLY
Definition mxl.h:31
@ MXL_STATUS_OK
Definition mxl.h:23
@ MXL_ERR_OUT_OF_RANGE_TOO_LATE
Definition mxl.h:30
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
bool waitUntilChanged(T const *in_addr, T in_expected, Timepoint in_deadline)
Definition Sync.cpp:68
mxlFlowRuntimeInfo runtime
Definition flowinfo.h:229
mxlFlowConfigInfo config
Definition flowinfo.h:227
auto const flowId