libe3 0.6.1
C++ library for E3AP RAN vendor integration
Loading...
Searching...
No Matches
e3_dapp_session.cpp
Go to the documentation of this file.
1/**
2 * @file e3_dapp_session.cpp
3 * @brief Implementation of the batched dApp Python seam. See e3_dapp_session.hpp.
4 *
5 * SPDX-FileCopyrightText: Copyright (c) 2026 Northeastern University
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9#include "e3_dapp_session.hpp"
10
11#include <libe3/e3_agent.hpp>
12#include <libe3/latrec.h>
14
15#include <algorithm>
16#include <atomic>
17#include <chrono>
18#include <mutex>
19#include <optional>
20
21namespace libe3 {
22namespace py {
23
24namespace {
25// Map an optional negative sentinel to std::optional<uint32_t>.
26inline std::optional<uint32_t> opt_u32(int v) {
27 if (v < 0) return std::nullopt;
28 return static_cast<uint32_t>(v);
29}
30
31// Copy why a response was negative onto the event; a positive one has neither.
32inline void set_refusal(E3Event& ev, const std::optional<libe3::Cause>& cause,
33 const std::optional<std::string>& detail) {
34 if (cause) ev.cause = static_cast<int>(*cause);
35 if (detail) ev.detail = *detail;
36}
37} // namespace
38
39/// What a DAppSession holds: the agent, the event queue and the setup snapshot.
41 /**
42 * @brief Create the agent and the event queue
43 * @param config The agent's configuration
44 * @param queue_capacity Number of events the queue holds
45 */
46 explicit Impl(libe3::E3Config config, std::size_t queue_capacity)
47 : agent(std::make_unique<libe3::E3Agent>(std::move(config))),
48 queue(queue_capacity) {}
49
50 std::unique_ptr<libe3::E3Agent> agent; ///< The dApp agent
51 // Stable object (never moved) so a poll_events() reference stays valid; a
52 // prior stop() shut it down, and start() re-arms it in place (LockFreeQueue's
53 // shutdown is one-way, E3Agent itself is restartable).
54 libe3::LockFreeQueue<E3Event> queue; ///< Events waiting for poll_events()
55 std::atomic<unsigned long long> dropped{0}; ///< Events dropped because the queue was full
56
57 // SetupResponse snapshot for the setup accessors (written once on setup).
58 mutable std::mutex setup_mu; ///< Guards have_setup and setup
59 bool have_setup{false}; ///< Whether a setup response has been seen
60 libe3::SetupResponse setup; ///< The latest setup response
61
62 /**
63 * @brief Queue an event for poll_events()
64 * @param ev The event; it is dropped, and counted, if the queue is full
65 */
66 void enqueue(E3Event ev) {
67 const uint64_t seq = latrec_seq_next();
68 ev.trace_seq = seq;
69 const uint64_t kind = static_cast<uint64_t>(ev.kind);
70 // Before the push, for the same reason as the report queue: the
71 // binding's poll thread can drain this event and stamp
72 // SESSION_POLLED before this thread gets to issue its own stamp.
73 const uint64_t t_queued = latrec_tnow();
74 if (queue.push(std::move(ev)) != libe3::ErrorCode::SUCCESS) {
75 dropped.fetch_add(1, std::memory_order_relaxed);
77 } else {
78 latrec_tstamp_at(seq, LATREC_SESSION_QUEUED, kind, 0, t_queued);
79 }
80 }
81};
82
83DAppSession::DAppSession(libe3::E3Config config, std::size_t queue_capacity) {
84 config.role = libe3::E3Role::DAPP; // this seam is dApp-only
85 impl_ = std::make_unique<Impl>(std::move(config), queue_capacity);
86 Impl* impl = impl_.get();
87 auto& agent = *impl->agent;
88
89 agent.set_indication_handler([impl](const libe3::IndicationMessage& m) {
90 E3Event ev;
94 ev.payload = m.protocol_data; // one copy from libe3's const&
95 impl->enqueue(std::move(ev));
96 });
97
98 agent.set_xapp_control_handler([impl](const libe3::XAppControlAction& a) {
99 E3Event ev;
104 ev.request_id = a.message_id;
107 impl->enqueue(std::move(ev));
108 });
109
110 agent.set_subscription_response_handler([impl](const libe3::SubscriptionResponse& r) {
111 E3Event ev;
114 ev.request_id = r.request_id;
115 ev.subscription_id = r.subscription_id.value_or(0);
116 ev.response_code = static_cast<int>(r.response_code);
117 ev.ran_function_id = r.ran_function_identifier.value_or(0);
118 ev.periodicity = r.periodicity ? static_cast<long>(*r.periodicity) : -1;
119 set_refusal(ev, r.cause, r.detail);
121 ev.has_telemetry_granted = true;
123 }
125 ev.has_control_granted = true;
127 }
128 impl->enqueue(std::move(ev));
129 });
130
131 agent.set_setup_response_handler([impl](const libe3::SetupResponse& r) {
132 {
133 std::lock_guard<std::mutex> lk(impl->setup_mu);
134 impl->setup = r;
135 impl->have_setup = true;
136 }
137 E3Event ev;
139 ev.dapp_id = r.dapp_identifier.value_or(0);
140 ev.request_id = r.request_id;
141 ev.response_code = static_cast<int>(r.response_code);
142 set_refusal(ev, r.cause, r.detail);
143 impl->enqueue(std::move(ev));
144 });
145
146 agent.set_disconnect_handler([impl](libe3::DisconnectReason reason) {
147 E3Event ev;
149 ev.disconnect_reason = static_cast<int>(reason);
150 impl->enqueue(std::move(ev));
151 });
152
153 agent.set_message_ack_handler([impl](const libe3::MessageAck& ack) { // DEPRECATED TO BE REMOVED
154 E3Event ev;
156 ev.request_id = ack.request_id;
157 ev.response_code = static_cast<int>(ack.response_code);
158 set_refusal(ev, ack.cause, ack.detail);
159 impl->enqueue(std::move(ev));
160 });
161
162 agent.set_control_response_handler([impl](const libe3::ControlResponse& r) {
163 E3Event ev;
167 ev.control_id = r.control_identifier;
168 ev.request_id = r.request_id;
169 ev.response_code = static_cast<int>(r.response_code);
170 ev.cause = r.cause ? static_cast<int>(*r.cause) : -1;
171 if (r.detail) ev.detail = *r.detail;
172 if (r.control_outcome && !r.control_outcome->empty()) {
173 ev.has_outcome = true;
174 ev.payload = *r.control_outcome;
175 }
176 impl->enqueue(std::move(ev));
177 });
178}
179
180/// Stops the agent and drops the queue.
182 if (impl_) {
183 impl_->queue.shutdown();
184 if (impl_->agent) impl_->agent->stop();
185 }
186}
187
189 // Re-arm the inbound ring in place (a prior stop() shut it down; E3Agent is
190 // restartable). Re-arming the same object — rather than replacing it — keeps
191 // any reference held by a concurrent poll_events() valid.
192 impl_->queue.rearm();
193 return static_cast<int>(impl_->agent->start());
194}
195
196int DAppSession::wait_for_setup(int timeout_ms) {
197 return static_cast<int>(
198 impl_->agent->wait_for_setup(std::chrono::milliseconds(timeout_ms)));
199}
200
202 return static_cast<int>(impl_->agent->release());
203}
204
206 impl_->queue.shutdown();
207 impl_->agent->stop();
208}
209
211 auto id = impl_->agent->dapp_id();
212 return id ? static_cast<long>(*id) : -1;
213}
214
215std::string DAppSession::ran_identifier() const {
216 std::lock_guard<std::mutex> lk(impl_->setup_mu);
217 return impl_->have_setup ? impl_->setup.ran_identifier : std::string{};
218}
219
221 std::lock_guard<std::mutex> lk(impl_->setup_mu);
222 if (!impl_->have_setup) return -1;
223 return static_cast<int>(impl_->setup.response_code);
224}
225
227 std::lock_guard<std::mutex> lk(impl_->setup_mu);
228 return impl_->have_setup ? impl_->setup.ran_function_list.size() : 0;
229}
230
231uint32_t DAppSession::setup_ran_function_id(std::size_t i) const {
232 std::lock_guard<std::mutex> lk(impl_->setup_mu);
233 if (!impl_->have_setup || i >= impl_->setup.ran_function_list.size()) return 0;
234 return impl_->setup.ran_function_list[i].ran_function_identifier;
235}
236
237std::vector<uint32_t> DAppSession::setup_ran_function_telemetry(std::size_t i) const {
238 std::lock_guard<std::mutex> lk(impl_->setup_mu);
239 if (!impl_->have_setup || i >= impl_->setup.ran_function_list.size()) return {};
240 return impl_->setup.ran_function_list[i].telemetry_identifier_list;
241}
242
243std::vector<uint32_t> DAppSession::setup_ran_function_control(std::size_t i) const {
244 std::lock_guard<std::mutex> lk(impl_->setup_mu);
245 if (!impl_->have_setup || i >= impl_->setup.ran_function_list.size()) return {};
246 return impl_->setup.ran_function_list[i].control_identifier_list;
247}
248
249std::vector<uint8_t> DAppSession::setup_ran_function_data(std::size_t i) const {
250 std::lock_guard<std::mutex> lk(impl_->setup_mu);
251 if (!impl_->have_setup || i >= impl_->setup.ran_function_list.size()) return {};
252 return impl_->setup.ran_function_list[i].ran_function_data;
253}
254
255int64_t DAppSession::subscribe(uint32_t ran_function_id,
256 std::vector<uint32_t> telemetry_ids,
257 std::vector<uint32_t> control_ids,
258 int sub_time_ms,
259 int periodicity) {
260 uint32_t request_id = 0;
261 ErrorCode rc = impl_->agent->subscribe(
262 ran_function_id, std::move(telemetry_ids), std::move(control_ids),
263 opt_u32(sub_time_ms), opt_u32(periodicity), &request_id);
264 // On success return the assigned request id (positive, 1..4294967295) so Python
265 // can correlate the SubscriptionResponse by id; on failure return the
266 // ErrorCode (all error codes are negative, SUCCESS is 0).
267 if (rc == ErrorCode::SUCCESS) {
268 return static_cast<int64_t>(request_id);
269 }
270 return static_cast<int64_t>(rc);
271}
272
273int DAppSession::unsubscribe(uint32_t ran_function_id) {
274 return static_cast<int>(impl_->agent->unsubscribe(ran_function_id));
275}
276
277int64_t DAppSession::send_control(uint32_t ran_function_id, uint32_t control_id,
278 std::vector<uint8_t> action_data,
279 uint32_t sequence_id,
280 bool request_ack) {
281 uint32_t message_id = 0;
282 ErrorCode rc = impl_->agent->send_control(
283 ran_function_id, control_id, std::move(action_data), sequence_id, &message_id, request_ack);
284 // On success return the assigned message id so Python can correlate a later
285 // response by id; on failure return the ErrorCode (all error codes are
286 // negative, SUCCESS is 0).
287 if (rc == ErrorCode::SUCCESS) {
288 return static_cast<int64_t>(message_id);
289 }
290 return static_cast<int64_t>(rc);
291}
292
293int64_t DAppSession::send_report(uint32_t ran_function_id, std::vector<uint8_t> report_data,
294 uint32_t sequence_id) {
295 uint32_t message_id = 0;
296 ErrorCode rc = impl_->agent->send_report(
297 ran_function_id, std::move(report_data), sequence_id, &message_id);
298 // Same success/failure encoding as send_control() above.
299 if (rc == ErrorCode::SUCCESS) {
300 return static_cast<int64_t>(message_id);
301 }
302 return static_cast<int64_t>(rc);
303}
304
305int DAppSession::send_message_ack(uint32_t request_id, int response_code) { // DEPRECATED TO BE REMOVED
306 return static_cast<int>(impl_->agent->send_message_ack(
307 request_id, static_cast<libe3::ResponseCode>(response_code)));
308}
309
310int DAppSession::send_control_response(uint32_t request_id, uint32_t ran_function_id,
311 uint32_t control_id, int response_code, int cause,
312 std::string detail, std::vector<uint8_t> outcome) {
314 result.response_code = (response_code == 0) ? libe3::ResponseCode::POSITIVE
316 if (cause >= 0) result.cause = libe3::cause_from_value(cause);
317 if (!detail.empty()) result.detail = std::move(detail);
318 result.outcome = std::move(outcome);
319 return static_cast<int>(
320 impl_->agent->send_control_response(request_id, ran_function_id, control_id, result));
321}
322
323std::vector<E3Event> DAppSession::poll_events(std::size_t max_batch, int timeout_ms) {
324 std::vector<E3Event> out;
325 if (max_batch == 0) return out;
326 auto& queue = impl_->queue;
327 // libe3 does not start this thread, so it has no ring. The open happens
328 // once, on a per-batch call rather than a per-event one.
329 latrec_tls_open_as("libe3.session");
330
331 // timeout_ms <= 0 is a non-blocking poll (try_pop); a positive value blocks
332 // up to that long for the first event. (pop() spins/yields before checking
333 // the deadline, so 0 there would busy-wait.)
334 std::optional<E3Event> first =
335 (timeout_ms <= 0) ? queue.try_pop()
336 : queue.pop(std::chrono::milliseconds(timeout_ms));
337 if (!first) return out; // quiet tick, or shutdown after stop()
338
339 out.reserve(std::min(max_batch, queue.capacity()));
340 out.push_back(std::move(*first));
341 while (out.size() < max_batch) {
342 auto next = queue.try_pop();
343 if (!next) break;
344 out.push_back(std::move(*next));
345 }
346 // aux is the position in the batch and aux2 its size, so a backlog shows
347 // as batches reaching max_batch.
348 for (std::size_t i = 0; i < out.size(); ++i) {
349 latrec_tstamp(out[i].trace_seq, LATREC_SESSION_POLLED, i, out.size());
350 }
351 return out;
352}
353
354unsigned long long DAppSession::dropped_events() const {
355 return impl_->dropped.load(std::memory_order_relaxed);
356}
357
358} // namespace py
359} // namespace libe3
E3Agent - Main façade for RAN vendor integration.
Definition e3_agent.hpp:94
Lock-free bounded blocking queue.
uint32_t setup_ran_function_id(std::size_t i) const
RAN function id of an advertised entry.
int send_control_response(uint32_t request_id, uint32_t ran_function_id, uint32_t control_id, int response_code, int cause, std::string detail, std::vector< uint8_t > outcome)
Answer an xApp control that has request_ack (E3_EVENT_XAPP_CONTROL).
int setup_response_code() const
SetupResponse code.
int unsubscribe(uint32_t ran_function_id)
Delete a previously created subscription.
std::vector< E3Event > poll_events(std::size_t max_batch, int timeout_ms)
Drain up to max_batch inbound events, waiting up to timeout_ms for the first.
std::vector< uint8_t > setup_ran_function_data(std::size_t i) const
Opaque ranFunctionData bytes of an advertised entry.
std::vector< uint32_t > setup_ran_function_telemetry(std::size_t i) const
Telemetry ids of an advertised entry.
std::string ran_identifier() const
RAN identifier from the SetupResponse.
unsigned long long dropped_events() const
Total inbound events dropped due to ring overflow (backpressure).
void stop()
Stop the agent and shut down the ring so a blocked poll_events returns an empty batch (i....
int release()
Send a ReleaseMessage (session keeps running until stop).
int send_message_ack(uint32_t request_id, int response_code)
Acknowledge a request. DEPRECATED TO BE REMOVED: answer an xApp control with send_control_response.
int start()
Start the agent, re-arming the inbound ring so a stop()->start() cycle works again.
int wait_for_setup(int timeout_ms)
Block until the setup handshake completes.
~DAppSession()
Stops the agent and drops the queue.
int64_t send_report(uint32_t ran_function_id, std::vector< uint8_t > report_data, uint32_t sequence_id)
Send a dApp report to the RAN.
int64_t send_control(uint32_t ran_function_id, uint32_t control_id, std::vector< uint8_t > action_data, uint32_t sequence_id=0, bool request_ack=false)
Send a dApp control action to the RAN.
long dapp_id() const
dApp id assigned at setup.
int64_t subscribe(uint32_t ran_function_id, std::vector< uint32_t > telemetry_ids, std::vector< uint32_t > control_ids, int sub_time_ms, int periodicity)
Subscribe to a RAN function (after a positive setup).
std::size_t setup_ran_function_count() const
Number of RAN functions advertised in the SetupResponse.
DAppSession(libe3::E3Config config, std::size_t queue_capacity=8192)
Construct the session and register all inbound handlers.
std::vector< uint32_t > setup_ran_function_control(std::size_t i) const
Control ids of an advertised entry.
E3Agent - Main façade class for RAN vendors.
Python-facing dApp session over libe3 — batched, low-latency seam.
Lock-free per-thread latency stamp recorder (header-only, C99).
static void latrec_tstamp(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2)
Definition latrec.h:720
static uint64_t latrec_tnow(void)
Definition latrec.h:713
static void latrec_tstamp_at(uint64_t seq, uint8_t stage, uint64_t aux, uint64_t aux2, uint64_t t_ns)
Definition latrec.h:702
@ LATREC_DROP_SESSION_QUEUE
Definition latrec.h:385
@ LATREC_SESSION_POLLED
Definition latrec.h:234
@ LATREC_SESSION_QUEUED
Definition latrec.h:232
@ LATREC_DROP
Definition latrec.h:237
uint64_t latrec_seq_next(void)
Definition latrec.c:164
latrec_t * latrec_tls_open_as(const char *role)
Definition latrec.c:122
Lock-free bounded blocking queue for the E3AP hot paths.
@ E3_EVENT_SUBSCRIPTION_RESPONSE
RAN → dApp SubscriptionResponse.
@ E3_EVENT_SETUP_RESPONSE
RAN → dApp SetupResponse.
@ E3_EVENT_INDICATION
RAN → dApp IndicationMessage.
@ E3_EVENT_DISCONNECT
the RAN is gone; see E3Event::disconnect_reason
@ E3_EVENT_XAPP_CONTROL
xApp → dApp XAppControlAction
@ E3_EVENT_CONTROL_RESPONSE
RAN → dApp ControlResponse.
@ E3_EVENT_MESSAGE_ACK
RAN → dApp MessageAck. DEPRECATED TO BE REMOVED: libe3 does not send one.
ErrorCode
Error codes returned by libe3 operations Use shared error-code list (see libe3/error_codes....
Definition types.hpp:177
@ DAPP
dApp (connects to a RAN agent)
Definition types.hpp:79
ResponseCode
E3AP response codes.
Definition types.hpp:103
@ NEGATIVE
Request rejected.
Definition types.hpp:105
@ POSITIVE
Request accepted.
Definition types.hpp:104
Cause cause_from_value(long value) noexcept
Read a Cause from its wire value.
Definition types.hpp:790
DisconnectReason
Why a dApp's session with the RAN ended (see DisconnectHandler).
Definition types.hpp:136
E3AP Control Response structure.
Definition types.hpp:366
What a Service Model answers to a control (see ServiceModel::respond_to_control).
Definition types.hpp:382
ResponseCode response_code
Whether the control was applied.
Definition types.hpp:383
std::optional< std::string > detail
UTF-8 text for the cause, up to MAX_DETAIL_SIZE bytes.
Definition types.hpp:385
std::optional< Cause > cause
Why not (negative only).
Definition types.hpp:384
std::vector< uint8_t > outcome
Opaque service-model content; empty for none.
Definition types.hpp:386
Configuration for E3Agent.
Definition types.hpp:506
E3Role role
Role: RAN (today's default — binds sockets) or DAPP (connects).
Definition types.hpp:508
E3AP Indication Message structure.
Definition types.hpp:323
uint32_t ran_function_identifier
RAN function identifier.
Definition types.hpp:325
std::vector< uint8_t > protocol_data
Opaque payload of the service model.
Definition types.hpp:326
uint32_t dapp_identifier
dApp the indication is for
Definition types.hpp:324
E3AP Message Acknowledgment structure.
Definition types.hpp:351
std::optional< Cause > cause
Why the request was refused (negative only).
Definition types.hpp:354
ResponseCode response_code
Response code (positive/negative).
Definition types.hpp:353
std::optional< std::string > detail
UTF-8 text for the cause, up to MAX_DETAIL_SIZE bytes.
Definition types.hpp:355
uint32_t request_id
ID of the request being acknowledged.
Definition types.hpp:352
E3AP Setup Response structure.
Definition types.hpp:273
E3AP Subscription Response structure.
Definition types.hpp:307
std::optional< Cause > cause
Why the subscription was refused (negative only).
Definition types.hpp:316
std::optional< uint32_t > subscription_id
Subscription ID (optional).
Definition types.hpp:311
std::optional< std::vector< uint32_t > > telemetry_identifier_list
Granted telemetry ids (absent = not reported, empty = none granted).
Definition types.hpp:312
std::optional< uint32_t > ran_function_identifier
RAN function the grant is for.
Definition types.hpp:314
uint32_t request_id
ID of the corresponding SubscriptionRequest.
Definition types.hpp:308
std::optional< std::string > detail
UTF-8 text for the cause, up to MAX_DETAIL_SIZE bytes.
Definition types.hpp:317
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:309
std::optional< uint32_t > periodicity
Least microseconds the RAN keeps between two indications (absent = not reported).
Definition types.hpp:315
std::optional< std::vector< uint32_t > > control_identifier_list
Granted control ids (absent = not reported, empty = none granted).
Definition types.hpp:313
ResponseCode response_code
Response code (positive/negative).
Definition types.hpp:310
E3AP xApp Control Action structure.
Definition types.hpp:405
std::vector< uint8_t > xapp_control_data
Definition types.hpp:408
uint32_t dapp_identifier
dApp the control is for
Definition types.hpp:406
uint32_t ran_function_identifier
RAN function the control is for.
Definition types.hpp:407
What a DAppSession holds: the agent, the event queue and the setup snapshot.
void enqueue(E3Event ev)
Queue an event for poll_events().
std::mutex setup_mu
Guards have_setup and setup.
bool have_setup
Whether a setup response has been seen.
libe3::SetupResponse setup
The latest setup response.
std::atomic< unsigned long long > dropped
Events dropped because the queue was full.
std::unique_ptr< libe3::E3Agent > agent
The dApp agent.
Impl(libe3::E3Config config, std::size_t queue_capacity)
Create the agent and the event queue.
libe3::LockFreeQueue< E3Event > queue
Events waiting for poll_events().
One inbound E3AP event, POD-flat for a clean SWIG crossing.
uint32_t ran_function_id
RAN function (indication / xApp control / subscription response).
uint32_t sequence_id
loop correlation id (xApp control); echo it on the control you re-issue
int kind
one of E3EventKind
uint32_t dapp_id
dApp identifier the message targets
std::vector< uint32_t > control_granted
granted control ids
bool has_outcome
control response: payload is the Service Model's outcome
std::vector< uint32_t > telemetry_granted
granted telemetry ids
uint32_t request_id
request/message id (subscription response / control response / xApp control); for a control response,...
int disconnect_reason
disconnect: 0=released by RAN, 1=connection lost, -1=n/a
long periodicity
least microseconds the RAN keeps between two indications (subscription response), -1 = not reported
uint32_t subscription_id
subscription id (subscription response)
int response_code
0=positive, 1=negative, -1=n/a
bool has_control_granted
control_granted was reported
uint64_t trace_seq
set when queued; keys the [latrec] LQ-stage records
std::vector< uint8_t > payload
opaque E3SM bytes (indication / xApp control)
int cause
why a negative response (setup, subscription or control) was refused, a libe3::Cause value 0 to 14; -...
bool request_ack
xApp control: the RAN wants a control response; answer it with send_control_response
bool has_telemetry_granted
telemetry_granted was reported
uint32_t control_id
control identifier (control response)
std::string detail
the RAN's text for the refusal; empty = none given