MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
RCTarget.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Contributors to the Media eXchange Layer project.
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#include "RCTarget.hpp"
7#include <rdma/fabric.h>
8#include "Exception.hpp"
9#include "FabricAddress.hpp"
10#include "FabricInfo.hpp"
11#include "FabricInfoHelpers.hpp"
12#include "Format.hpp" // IWYU pragma: keep; Includes template specializations of fmt::formatter for our types
13#include "PassiveEndpoint.hpp"
14#include "Protocol.hpp"
15#include "Provider.hpp"
16#include "Region.hpp"
17#include "VariantUtils.hpp"
18
20{
21
22 std::pair<std::unique_ptr<RCTarget>, std::unique_ptr<TargetInfo>> RCTarget::setup(mxlFabricsTargetConfig const& config, FabricInfoView info,
23 TargetSetupOptions const& options)
24 {
25 requireCapability(info, FI_REMOTE_WRITE, "Interface is missing required remote write capability");
26 auto provider = providerFromString(info->fabric_attr->prov_name);
27 if (!provider)
28 {
29 throw Exception::invalidArgument("invalid provider: {}", info->fabric_attr->prov_name);
30 }
31
32 MXL_INFO("Setting up RC target with source address: {}", FabricAddress::fromSource(info).toString());
33
34 // Open fabric and domain. These represent the context of the local network fabric adapter that will be used
35 // to receive data.
36 // See fi_domain(3) and fi_fabric(3) for more complete information about these concepts.
37 auto fabric = Fabric::open(info);
38 auto domain = Domain::open(fabric);
39
40 auto pep = makeListener(fabric);
41
42 auto const mxlRegions = MxlRegions::forWriter(config.writer);
43 auto proto = selectIngressProtocol(mxlRegions.dataLayout(), mxlRegions.regions(), mxlRegions.maxSyncBatchSize());
44 auto targetInfo = std::make_unique<TargetInfo>(
45 pep.id(), pep.localAddress(), *provider, proto->registerMemory(domain), proto->bounceBufferInfo());
46
47 // Helper struct to enable the std::make_unique function to access the private constructor of this class.
48 struct MakeUniqueEnabler : RCTarget
49 {
50 MakeUniqueEnabler(PassiveEndpoint pep, std::unique_ptr<IngressProtocol> proto, std::shared_ptr<Domain> domain, TargetSetupOptions options)
51 : RCTarget(std::move(pep), std::move(proto), std::move(domain), options)
52 {}
53 };
54
55 // Return the constructed RCTarget and associated TargetInfo for remote peers to connect.
56 return {std::make_unique<MakeUniqueEnabler>(std::move(pep), std::move(proto), std::move(domain), options), std::move(targetInfo)};
57 }
58
59 RCTarget::RCTarget(PassiveEndpoint pep, std::unique_ptr<IngressProtocol> proto, std::shared_ptr<Domain> domain, TargetSetupOptions options)
60 : _pep(std::move(pep))
61 , _proto(std::move(proto))
62 , _domain(std::move(domain))
63 , _setupOptions(options)
65 {}
66
67 std::optional<Target::ReadResult> RCTarget::read()
68 {
69 return readNext<QueueReadMode::NonBlocking>(std::chrono::steady_clock::duration::zero());
70 }
71
72 std::optional<Target::ReadResult> RCTarget::readBlocking(std::chrono::steady_clock::duration timeout)
73 {
75 }
76
78 {
79 if (auto state = std::get_if<Connected>(&_state); state != nullptr)
80 {
81 MXL_INFO("Shutting down the connection.");
82 state->ep.shutdown();
83
84 auto const deadline = std::chrono::steady_clock::now() + ShutdownTimeout;
85 for (;;)
86 {
87 auto const remaining = deadline - std::chrono::steady_clock::now();
88 if (remaining <= std::chrono::steady_clock::duration::zero())
89 {
90 MXL_WARN("Did not receive a shutdown event within {} ms.",
91 std::chrono::duration_cast<std::chrono::milliseconds>(ShutdownTimeout).count());
92 break;
93 }
94
95 auto const event = state->ep.eventQueue()->readBlocking(remaining);
96 if (event && (event->isShutdown() || event->isError()))
97 {
98 break;
99 }
100 }
101 }
102
103 _state = Closed{};
104 }
105
106 template<QueueReadMode queueReadMode>
107 std::optional<Target::ReadResult> RCTarget::readNext(std::chrono::steady_clock::duration timeout)
108 {
109 auto result = std::optional<Target::ReadResult>{std::nullopt};
110
111 _state = std::visit(
113 [](std::monostate) -> State { throw Exception::invalidState("Target is in an invalid state and can no longer make progress"); },
114 [&](WaitForConnectionRequest state) -> State
115 {
116 try
117 {
118 auto event = readEventQueue<queueReadMode>(*_pep.eventQueue(), timeout);
119
120 // Check if the entry is available and is a connection request
121 if (event && event->isConnReq())
122 {
123 auto remoteAddr = FabricAddress::fromDestination(event->connReq().info());
124 MXL_INFO("Accept connection from: {}", remoteAddr.toString());
125
127 cqAttr.size = _setupOptions.cqDepth.value_or(CompletionQueue::Attributes::DEFAULT_SIZE);
128 auto cq = CompletionQueue::open(_domain, cqAttr);
129 auto endpoint = Endpoint::create(_domain, _pep.id(), event->connReq().info());
130 endpoint.bind(cq, FI_RECV);
131
133 endpoint.bind(eq);
134
135 // we are now ready to accept the connection
136 endpoint.accept();
137 MXL_DEBUG("Accepted the connection waiting for connected event notification.");
138
139 // Return the new state as the variant type
140 return RCTarget::WaitForConnection{std::move(endpoint)};
141 }
142
143 return state;
144 }
145 catch (FabricException const& ex)
146 {
147 if (ex.isInterrupted())
148 {
149 result = std::make_optional<Target::Interrupted>();
150 return state;
151 }
152
153 throw;
154 }
155 },
156 [&](WaitForConnection state) -> State
157 {
158 try
159 {
160 auto event = readEventQueue<queueReadMode>(*state.ep.eventQueue(), timeout);
161
162 if (event && event->isConnected())
163 {
164 MXL_INFO("Received connected event notification, now connected.");
165
166 // We have a connected event, so we can transition to the connected state
167 auto connected = Connected{.ep = std::move(state.ep)};
168
169 // The endpoint is now ready, initialize the protocol.
170 _proto->start(connected.ep);
171
172 return connected;
173 }
174
175 return WaitForConnection{std::move(state.ep)};
176 }
177 catch (FabricException const& ex)
178 {
179 if (ex.isInterrupted())
180 {
181 result = std::make_optional<Target::Interrupted>();
182 return WaitForConnection{.ep = std::move(state.ep)};
183 }
184
185 throw;
186 }
187 },
188 [&](RCTarget::Connected state) -> State
189 {
190 try
191 {
192 auto [completion, event] = readEndpointQueues<queueReadMode>(state.ep, timeout);
193
194 // A completion that was read together with the shutdown event belongs to data that has already arrived.
195 if (completion)
196 {
197 result = _proto->read(state.ep, *completion);
198 }
199
200 if (event && event.value().isShutdown())
201 {
202 MXL_INFO("Remote endpoint has shutdown the connection.");
203 catchAndLogFabricError([&]() { state.ep.shutdown(); },
204 "Failed to shut down the endpoint after the remote endpoint closed it");
205 return Draining{.ep = std::move(state.ep)};
206 }
207
208 return Connected{.ep = std::move(state.ep)};
209 }
210 catch (FabricException const& ex)
211 {
212 if (ex.isInterrupted())
213 {
214 result = std::make_optional<Target::Interrupted>();
215 return Connected{.ep = std::move(state.ep)};
216 }
217
218 throw;
219 }
220 },
221 [&](RCTarget::Draining state) -> State { return drain(std::move(state), result); },
222 [](RCTarget::Closed) -> State { throw Exception::invalidState("Target has been shut down and can no longer be used."); },
223 },
224 std::move(_state));
225
226 return result;
227 }
228
229 RCTarget::State RCTarget::drain(Draining state, std::optional<Target::ReadResult>& result)
230 {
231 // The connection is closed, so no new completions are expected. Read the queue without blocking until it returns a result or is
232 // empty. Completions of receive buffers that were cancelled by the shutdown produce no result.
233 while (auto completion = state.ep.completionQueue()->read())
234 {
235 try
236 {
237 result = _proto->read(state.ep, *completion);
238 }
239 catch (FabricException const& ex)
240 {
241 // The protocol posts a new receive buffer before it decodes the completion. Some providers refuse new receive buffers on a
242 // closed connection.
243 MXL_WARN("Failed to read a completion after the connection was shut down: {}", ex.what());
244 }
245
246 if (result)
247 {
248 return state;
249 }
250 }
251
252 MXL_INFO("Transitioning to listening to new connection.");
255 }
256
258 {
259 while (auto event = _pep.eventQueue()->read())
260 {
261 if (event->isConnReq())
262 {
263 MXL_INFO("Reject connection request from {} that arrived while connected.",
264 FabricAddress::fromDestination(event->connReq().info()).toString());
265 _pep.reject(*event);
266 }
267 }
268 }
269
270 PassiveEndpoint RCTarget::makeListener(std::shared_ptr<Fabric> const& fabric)
271 {
272 // Create a passive endpoint. A passive endpoint can be viewed like a bound TCP socket listening for
273 // incoming connections.
274 auto pep = PassiveEndpoint::create(fabric);
275
276 // Create an event queue for the passive endpoint. Incoming connections generate an entry in the event queue
277 // and be picked up when the Target tries to make progress.
279
280 // Transition the PassiveEndpoint into a listening state. Connections will be accepted from now on.
281 pep.listen();
282
283 return pep;
284 }
285}
#define MXL_WARN(...)
Definition Logging.hpp:56
#define MXL_DEBUG(...)
Definition Logging.hpp:34
#define MXL_INFO(...)
Definition Logging.hpp:45
static std::shared_ptr< CompletionQueue > open(std::shared_ptr< Domain > domain, Attributes const &attr=Attributes::defaults())
Create a new completion queue in the specified domain.
static std::shared_ptr< Domain > open(std::shared_ptr< Fabric > fabric)
Open a new domain associated with the specified fabric.
Definition Domain.cpp:30
static Endpoint create(std::shared_ptr< Domain > domain, FabricInfoView info)
Allocates (active) new endpoint.
Definition Endpoint.cpp:56
std::shared_ptr< CompletionQueue > completionQueue() const
Get the associated completion queue.
Definition Endpoint.cpp:195
static std::shared_ptr< EventQueue > open(std::shared_ptr< Fabric >, Attributes const &attr=Attributes::defaults())
Create a new event queue associated with the specified fabric.
static Exception invalidArgument(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_ARG exception.
Definition Exception.hpp:43
char const * what() const noexcept override
Implements std::exception, returns a descriptive string about the error.
Definition Exception.cpp:21
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
static FabricAddress fromSource(FabricInfoView info) noexcept
Build a FabricAddress from the source address of info.
static FabricAddress fromDestination(FabricInfoView info) noexcept
Build a FabricAddress from the destination address of info.
An internal exception type that extends.
Non-owning view of a FabricInfo. Returned when iterating over a FabricInfoList.
static std::shared_ptr< Fabric > open(FabricInfoView info)
Open a fabric object based on the provided FabricInfoView.
Definition Fabric.cpp:15
static MxlRegions forWriter(mxlFlowWriter)
Definition Region.cpp:110
RAII Wrapper around a libfabric passive endpoint (fid_pep).
static PassiveEndpoint create(std::shared_ptr< Fabric > fabric)
Allocate a new PassiveEndpoint associated with the given Fabric.
RCTarget(PassiveEndpoint pep, std::unique_ptr< IngressProtocol > proto, std::shared_ptr< Domain > domain, TargetSetupOptions options)
Construct a new RCTarget associated with the given domain and passive endpoint.
Definition RCTarget.cpp:59
std::optional< Target::ReadResult > readNext(std::chrono::steady_clock::duration timeout)
Internal method to drive progress based on the current state.
Definition RCTarget.cpp:107
virtual std::optional< Target::ReadResult > read()
Determine if new data can be consumed.
Definition RCTarget.cpp:67
static PassiveEndpoint makeListener(std::shared_ptr< Fabric > const &fabric)
Definition RCTarget.cpp:270
State drain(Draining state, std::optional< Target::ReadResult > &result)
Read the completions that are left after the Initiator closed the connection.
Definition RCTarget.cpp:229
std::shared_ptr< Domain > _domain
Definition RCTarget.hpp:138
std::unique_ptr< IngressProtocol > _proto
Definition RCTarget.hpp:137
TargetSetupOptions _setupOptions
Definition RCTarget.hpp:139
static std::pair< std::unique_ptr< RCTarget >, std::unique_ptr< TargetInfo > > setup(mxlFabricsTargetConfig const &config, FabricInfoView info, TargetSetupOptions const &options={})
Set up a fresh RCTarget and its associated TargetInfo based on the given configuration.
Definition RCTarget.cpp:22
std::variant< WaitForConnectionRequest, WaitForConnection, Connected, Draining, Closed > State
The internal state of the RCTarget.
Definition RCTarget.hpp:90
virtual std::optional< Target::ReadResult > readBlocking(std::chrono::steady_clock::duration timeout) final
Determine if new data can be consumed.
Definition RCTarget.cpp:72
static constexpr auto ShutdownTimeout
Upper bound for waiting on the local shutdown event in shutdown().
Definition RCTarget.hpp:94
virtual void shutdown() final
Shut down the target gracefully. Initiates a graceful shutdown of the target and blocks until the shu...
Definition RCTarget.cpp:77
void rejectPendingConnectionRequests()
Reject all connection requests that are queued on the passive endpoint.
Definition RCTarget.cpp:257
struct mxlFabricsTargetConfig_t mxlFabricsTargetConfig
std::optional< Event > readEventQueue(EventQueue &eq, std::chrono::steady_clock::duration timeout)
Helper to read an event queue with blocking or non-blocking behaviour.
std::pair< std::optional< Completion >, std::optional< Event > > readEndpointQueues(Endpoint &ep, std::chrono::steady_clock::duration timeout)
Helper to read both completion and event queues of an endpoint with blocking or non-blocking behaviou...
std::optional< Provider > providerFromString(std::string const &s) noexcept
Parse a provider name string, and return the enum value.
Definition Provider.cpp:49
void catchAndLogFabricError(F &&fun, std::string_view msg)
std::unique_ptr< IngressProtocol > selectIngressProtocol(DataLayout const &layout, std::vector< Region > regions, std::uint32_t maxSyncBatchSize)
Select an appropriate ingress protocol based on the data layout.
Definition Protocol.cpp:13
void requireCapability(FabricInfoView info, std::uint64_t cap, std::string_view message)
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
mxlFlowWriter writer
Definition fabrics.h:131
static constexpr std::size_t DEFAULT_SIZE
The completion-queue depth used when no explicit depth is requested.
static Attributes defaults()
Returns the a CompletionQueueAttr with all of its attributes set to reasonable defaults.
static Attributes defaults()
Creates a configuration with all values set to reasonable defaults.
The wait for connection request state.
Definition RCTarget.hpp:51
Provider-independent tuning options for target setup.
Definition Target.hpp:23