libe3 0.6.1
C++ library for E3AP RAN vendor integration
Loading...
Searching...
No Matches
json_encoder.cpp
Go to the documentation of this file.
1/**
2 * @file json_encoder.cpp
3 * @brief JSON Encoder implementation
4 *
5 * SPDX-FileCopyrightText: Copyright (c) 2026 Northeastern University
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9#include "json_encoder.hpp"
10#include "libe3/logger.hpp"
11#include <iomanip>
12#include <optional>
13#include <sstream>
14#include <stdexcept>
15#include <utility>
16
17namespace libe3 {
18
19namespace {
20
21constexpr const char* LOG_TAG = "JsonEnc";
22
23std::string to_camel_case(const char* pascal) {
24 std::string s(pascal);
25 if (!s.empty()) s[0] = static_cast<char>(std::tolower(static_cast<unsigned char>(s[0])));
26 return s;
27}
28
29bool is_json_ws(char c) {
30 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
31}
32
33size_t skip_ws(const std::string& text, size_t pos) {
34 while (pos < text.size() && is_json_ws(text[pos])) {
35 ++pos;
36 }
37 return pos;
38}
39
40// Skips a JSON string starting at text[pos] == '"'. Returns the index just
41// past the closing quote, or nullopt on truncation/malformed escapes.
42std::optional<size_t> skip_json_string(const std::string& text, size_t pos) {
43 const size_t n = text.size();
44 if (pos >= n || text[pos] != '"') return std::nullopt;
45 ++pos;
46 while (pos < n) {
47 char c = text[pos];
48 if (c == '\\') {
49 if (pos + 1 >= n) return std::nullopt;
50 if (text[pos + 1] == 'u') {
51 if (pos + 6 > n) return std::nullopt; // \ u X X X X
52 pos += 6;
53 continue;
54 }
55 pos += 2;
56 continue;
57 }
58 if (c == '"') {
59 return pos + 1;
60 }
61 ++pos;
62 }
63 return std::nullopt;
64}
65
66// Skips one JSON value starting at text[pos] (already at its first byte).
67// Returns the index just past the value, or nullopt on anything unexpected
68// or truncated. Objects/arrays are skipped by depth-counting braces/brackets
69// (with nested strings skipped via skip_json_string so a brace/bracket
70// character inside a string is never mistaken for structure); scalars (
71// numbers, true/false/null) are skipped up to the next structural delimiter
72// or whitespace.
73std::optional<size_t> skip_json_value(const std::string& text, size_t pos) {
74 const size_t n = text.size();
75 if (pos >= n) return std::nullopt;
76 char c = text[pos];
77 if (c == '"') {
78 return skip_json_string(text, pos);
79 }
80 if (c == '{' || c == '[') {
81 char open = c;
82 char close = (open == '{') ? '}' : ']';
83 int depth = 1;
84 ++pos;
85 while (pos < n && depth > 0) {
86 char cc = text[pos];
87 if (cc == '"') {
88 auto after = skip_json_string(text, pos);
89 if (!after) return std::nullopt;
90 pos = *after;
91 continue;
92 }
93 if (cc == open) {
94 ++depth;
95 } else if (cc == close) {
96 --depth;
97 }
98 ++pos;
99 }
100 if (depth != 0) return std::nullopt;
101 return pos;
102 }
103 // Bare token: number, true, false, or null.
104 while (pos < n) {
105 char cc = text[pos];
106 if (cc == ',' || cc == '}' || cc == ']' || is_json_ws(cc)) {
107 break;
108 }
109 ++pos;
110 }
111 return pos;
112}
113
114// Locates the byte span [start, end) of the value bound to `key` as a
115// top-level member of the JSON object beginning at text[obj_start]. `text`
116// is assumed to have already been proven well-formed JSON by the caller
117// (decode()'s prior nlohmann::json::parse succeeded), so this only has to
118// locate an already-guaranteed-to-exist member, not defend against
119// arbitrary malformed input; every access is still bounds-checked and any
120// unexpected byte pattern bails out to nullopt (never guesses), so a bug
121// here can only cost a caller its fast path, never correctness -- callers
122// are expected to fall back to re-serializing the parsed subtree on a miss.
123// Does not unescape keys: a key that itself contains an escape sequence
124// simply won't match and triggers the fallback (no encoder in this file
125// produces escaped key names).
126std::optional<std::pair<size_t, size_t>> find_top_level_member_span(
127 const std::string& text, size_t obj_start, const std::string& key) {
128 const size_t n = text.size();
129 if (obj_start >= n || text[obj_start] != '{') {
130 return std::nullopt;
131 }
132
133 size_t pos = obj_start + 1;
134 while (true) {
135 pos = skip_ws(text, pos);
136 if (pos >= n) return std::nullopt;
137 if (text[pos] == '}') {
138 return std::nullopt; // key not found
139 }
140 if (text[pos] != '"') return std::nullopt;
141
142 size_t key_start = pos + 1;
143 auto after_key = skip_json_string(text, pos);
144 if (!after_key) return std::nullopt;
145 size_t key_end = *after_key - 1; // index of the closing quote
146
147 pos = skip_ws(text, *after_key);
148 if (pos >= n || text[pos] != ':') return std::nullopt;
149 pos = skip_ws(text, pos + 1);
150
151 size_t value_start = pos;
152 auto after_value = skip_json_value(text, pos);
153 if (!after_value) return std::nullopt;
154
155 bool key_matches = (key_end - key_start == key.size()) &&
156 text.compare(key_start, key.size(), key) == 0;
157 if (key_matches) {
158 return std::make_pair(value_start, *after_value);
159 }
160
161 pos = skip_ws(text, *after_value);
162 if (pos < n && text[pos] == ',') {
163 ++pos;
164 continue;
165 }
166 return std::nullopt; // '}' (key not found) or anything unexpected
167 }
168}
169
170// Decode only takes an object or array, so encode must not write anything else.
171bool is_json_container(const std::vector<uint8_t>& bytes) {
172 size_t i = 0;
173 while (i < bytes.size() && is_json_ws(static_cast<char>(bytes[i]))) ++i;
174 if (i == bytes.size() || (bytes[i] != '{' && bytes[i] != '[')) return false;
175 return nlohmann::json::accept(bytes);
176}
177
178// Throws std::invalid_argument, which encode() reports as ENCODE_FAILED.
179void require_json_container(const std::vector<uint8_t>& bytes, const char* field) {
180 if (!is_json_container(bytes)) {
181 throw std::invalid_argument(std::string(field) + " is not a JSON object or array ("
182 + std::to_string(bytes.size()) + " bytes)");
183 }
184}
185
186} // anonymous namespace
187
188
189// ============================================================================
190// Helper methods for type conversions
191// ============================================================================
192
193std::optional<PduType> JsonE3Encoder::string_to_pdu_type(const std::string& s) const {
194 if (s == "setupRequest") return PduType::SETUP_REQUEST;
195 if (s == "setupResponse") return PduType::SETUP_RESPONSE;
196 if (s == "subscriptionRequest") return PduType::SUBSCRIPTION_REQUEST;
197 if (s == "subscriptionDelete") return PduType::SUBSCRIPTION_DELETE;
198 if (s == "subscriptionResponse") return PduType::SUBSCRIPTION_RESPONSE;
199 if (s == "indicationMessage") return PduType::INDICATION_MESSAGE;
200 if (s == "dAppControlAction") return PduType::DAPP_CONTROL_ACTION;
201 if (s == "dAppReport") return PduType::DAPP_REPORT;
202 if (s == "xAppControlAction") return PduType::XAPP_CONTROL_ACTION;
203 if (s == "releaseMessage") return PduType::RELEASE_MESSAGE;
204 if (s == "messageAck") return PduType::MESSAGE_ACK; // DEPRECATED TO BE REMOVED
205 if (s == "controlResponse") return PduType::CONTROL_RESPONSE;
206 return std::nullopt;
207}
208
209ErrorCode JsonE3Encoder::string_to_error_code(const std::string& s) const {
210 if (s == "SUCCESS") return ErrorCode::SUCCESS;
211 if (s == "INVALID_PARAM") return ErrorCode::INVALID_PARAM;
212 if (s == "TIMEOUT") return ErrorCode::TIMEOUT;
213 if (s == "NOT_FOUND") return ErrorCode::NOT_FOUND;
214 return ErrorCode::GENERIC_ERROR;
215}
216
217// ============================================================================
218// Binary encoding helpers
219// ============================================================================
220
221std::vector<uint8_t> JsonE3Encoder::payload_from_json(const nlohmann::json& value) {
222 if (value.is_object() || value.is_array()) {
223 std::string text = value.dump();
224 return std::vector<uint8_t>(text.begin(), text.end());
225 }
226 throw std::invalid_argument("payload is not a JSON object or array");
227}
228
229std::vector<uint8_t> JsonE3Encoder::payload_member(const nlohmann::json& j,
230 const std::string& raw_json,
231 const char* key) {
232 auto it = j.find(key);
233 if (it == j.end()) return {};
234 if (it->is_object() || it->is_array()) {
235 size_t obj_start = raw_json.find_first_not_of(" \t\r\n");
236 auto span = (obj_start == std::string::npos)
237 ? std::nullopt
238 : find_top_level_member_span(raw_json, obj_start, key);
239 if (span) {
240 // Verbatim, like protocolData.
241 return std::vector<uint8_t>(raw_json.begin() + static_cast<long>(span->first),
242 raw_json.begin() + static_cast<long>(span->second));
243 }
244 }
245 return payload_from_json(*it);
246}
247
248// ============================================================================
249// Encoding helpers for each PDU type
250// ============================================================================
251
252nlohmann::json JsonE3Encoder::encode_setup_request(const SetupRequest& req) const {
253 nlohmann::json j;
254 j["e3apProtocolVersion"] = req.e3ap_protocol_version;
255 j["dAppName"] = req.dapp_name;
256 j["dAppVersion"] = req.dapp_version;
257 j["vendor"] = req.vendor;
258
259 return j;
260}
261
262namespace {
263
264// A refusal's reason is the same two optional members on three responses.
265template <typename Resp>
266void write_reason(nlohmann::json& j, const Resp& resp) {
267 if (resp.cause) j["cause"] = cause_to_string(*resp.cause);
268 if (resp.detail) j["detail"] = *resp.detail;
269}
270
271// Aerial sends the text as `message`; `detail` wins when both are there.
272template <typename Resp>
273void read_reason(const nlohmann::json& j, Resp& resp) {
274 if (auto it = j.find("cause"); it != j.end() && it->is_string()) {
275 resp.cause = cause_from_string(it->get<std::string>());
276 }
277 for (const char* key : {"detail", "message"}) {
278 if (auto it = j.find(key); it != j.end() && it->is_string()) {
279 resp.detail = it->get<std::string>();
280 break;
281 }
282 }
283}
284
285} // namespace
286
287nlohmann::json JsonE3Encoder::encode_setup_response(const SetupResponse& resp) const {
288 nlohmann::json j;
289 j["requestId"] = resp.request_id;
290 j["responseCode"] = (resp.response_code == ResponseCode::POSITIVE) ? "positive" : "negative";
291 if (resp.e3ap_protocol_version.has_value()) {
292 j["e3apProtocolVersion"] = resp.e3ap_protocol_version.value();
293 }
294 if (resp.dapp_identifier.has_value()) {
295 j["dAppIdentifier"] = resp.dapp_identifier.value();
296 }
297 j["ranIdentifier"] = resp.ran_identifier;
298 if (!resp.ran_function_list.empty()) {
299 nlohmann::json ran_funcs = nlohmann::json::array();
300 for (const auto& func : resp.ran_function_list) {
301 nlohmann::json func_obj;
302 func_obj["ranFunctionIdentifier"] = func.ran_function_identifier;
303 func_obj["telemetryIdentifierList"] = func.telemetry_identifier_list;
304 func_obj["controlIdentifierList"] = func.control_identifier_list;
305 require_json_container(func.ran_function_data, "ranFunctionData");
306 func_obj["ranFunctionData"] = nlohmann::json::parse(func.ran_function_data);
307 ran_funcs.push_back(func_obj);
308 }
309 j["ranFunctionList"] = ran_funcs;
310 }
311 write_reason(j, resp);
312 return j;
313}
314
315nlohmann::json JsonE3Encoder::encode_subscription_request(const SubscriptionRequest& req) const {
316 nlohmann::json j;
317 j["dAppIdentifier"] = req.dapp_identifier;
318 j["ranFunctionIdentifier"] = req.ran_function_identifier;
319 j["telemetryIdentifierList"] = req.telemetry_identifier_list;
320 j["controlIdentifierList"] = req.control_identifier_list;
321 if (req.subscription_time.has_value()) {
322 j["subscriptionTime"] = req.subscription_time.value();
323 }
324 if (req.periodicity.has_value()) {
325 j["periodicity"] = req.periodicity.value();
326 }
327 return j;
328}
329
330nlohmann::json JsonE3Encoder::encode_subscription_delete(const SubscriptionDelete& del) const {
331 nlohmann::json j;
332 j["dAppIdentifier"] = del.dapp_identifier;
333 j["subscriptionId"] = del.subscription_id;
334 return j;
335}
336
337nlohmann::json JsonE3Encoder::encode_subscription_response(const SubscriptionResponse& resp) const {
338 nlohmann::json j;
339 j["requestId"] = resp.request_id;
340 j["dAppIdentifier"] = resp.dapp_identifier;
341 j["responseCode"] = (resp.response_code == ResponseCode::POSITIVE) ? "positive" : "negative";
342 if (resp.subscription_id.has_value()) {
343 j["subscriptionId"] = resp.subscription_id.value();
344 }
345 if (resp.telemetry_identifier_list.has_value()) {
346 j["telemetryIdentifierList"] = *resp.telemetry_identifier_list;
347 }
348 if (resp.control_identifier_list.has_value()) {
349 j["controlIdentifierList"] = *resp.control_identifier_list;
350 }
351 if (resp.ran_function_identifier.has_value()) {
352 j["ranFunctionIdentifier"] = *resp.ran_function_identifier;
353 }
354 if (resp.periodicity.has_value()) {
355 j["periodicity"] = *resp.periodicity;
356 }
357 write_reason(j, resp);
358 return j;
359}
360
361std::optional<nlohmann::json> JsonE3Encoder::encode_indication_message(const IndicationMessage& msg) const {
362 if (!nlohmann::json::accept(msg.protocol_data)) {
363 E3_LOG_ERROR(LOG_TAG) << "Malformed protocolData for indication message "
364 << "(ranFunctionIdentifier=" << msg.ran_function_identifier
365 << ", payload size=" << msg.protocol_data.size() << " bytes)";
366 return std::nullopt; // caller reports ErrorCode::ENCODE_FAILED
367 }
368 nlohmann::json j;
369 j["dAppIdentifier"] = msg.dapp_identifier;
370 j["ranFunctionIdentifier"] = msg.ran_function_identifier;
371 // protocolData intentionally omitted: encode() splices the validated raw
372 // bytes verbatim into the dumped envelope instead of parsing them into a
373 // DOM here only to have root.dump() re-serialize them a moment later.
374 return j;
375}
376
377nlohmann::json JsonE3Encoder::encode_dapp_control_action(const DAppControlAction& action) const {
378 nlohmann::json j;
379 j["dAppIdentifier"] = action.dapp_identifier;
380 j["ranFunctionIdentifier"] = action.ran_function_identifier;
381 j["controlIdentifier"] = action.control_identifier;
382 // OPTIONAL: omitted entirely when unset, mirroring the ASN.1 absent field.
383 if (action.sequence_id != 0) j["sequenceId"] = action.sequence_id;
384 // OPTIONAL, written only when true: false and absent are the same.
385 if (action.request_ack) j["requestAck"] = true;
386 return j;
387}
388
389nlohmann::json JsonE3Encoder::encode_dapp_report(const DAppReport& report) const {
390 nlohmann::json j;
391 j["dAppIdentifier"] = report.dapp_identifier;
392 j["ranFunctionIdentifier"] = report.ran_function_identifier;
393 j["sequenceId"] = report.sequence_id;
394 return j;
395}
396
397nlohmann::json JsonE3Encoder::encode_xapp_control_action(const XAppControlAction& action) const {
398 nlohmann::json j;
399 j["dAppIdentifier"] = action.dapp_identifier;
400 j["ranFunctionIdentifier"] = action.ran_function_identifier;
401 j["sequenceId"] = action.sequence_id;
402 if (action.request_ack) j["requestAck"] = true;
403 return j;
404}
405
406// DEPRECATED TO BE REMOVED: libe3 does not send a messageAck; it reads one.
407nlohmann::json JsonE3Encoder::encode_message_ack(const MessageAck& ack) const {
408 nlohmann::json j;
409 j["requestId"] = ack.request_id;
410 j["responseCode"] = (ack.response_code == ResponseCode::POSITIVE) ? "positive" : "negative";
411 write_reason(j, ack);
412 return j;
413}
414
415nlohmann::json JsonE3Encoder::encode_control_response(const ControlResponse& resp) const {
416 nlohmann::json j;
417 j["requestId"] = resp.request_id;
418 j["dAppIdentifier"] = resp.dapp_identifier;
419 j["ranFunctionIdentifier"] = resp.ran_function_identifier;
420 j["controlIdentifier"] = resp.control_identifier;
421 j["responseCode"] = (resp.response_code == ResponseCode::POSITIVE) ? "positive" : "negative";
422 write_reason(j, resp);
423 // controlOutcome is spliced in by encode(), like actionData.
424 return j;
425}
426
427// ============================================================================
428// Decoding helpers for each PDU type
429// ============================================================================
430
431SetupRequest JsonE3Encoder::decode_setup_request(const nlohmann::json& j) const {
432 SetupRequest req;
433 req.e3ap_protocol_version = j.value("e3apProtocolVersion", "");
434 req.dapp_name = j.value("dAppName", "");
435 req.dapp_version = j.value("dAppVersion", "");
436 req.vendor = j.value("vendor", "");
437
438 return req;
439}
440
441SetupResponse JsonE3Encoder::decode_setup_response(const nlohmann::json& j) const {
442 SetupResponse resp;
443 resp.request_id = j.value("requestId", 0u);
444
445 std::string response_code_str = j.value("responseCode", "negative");
446 resp.response_code = (response_code_str == "positive") ? ResponseCode::POSITIVE : ResponseCode::NEGATIVE;
447
448 if (j.contains("e3apProtocolVersion")) {
449 resp.e3ap_protocol_version = j["e3apProtocolVersion"].get<std::string>();
450 }
451 if (j.contains("dAppIdentifier")) {
452 resp.dapp_identifier = j["dAppIdentifier"].get<uint32_t>();
453 }
454 resp.ran_identifier = j.value("ranIdentifier", "");
455 if (j.contains("ranFunctionList")) {
456 for (const auto& func_obj : j["ranFunctionList"]) {
457 RanFunctionDef func;
458 func.ran_function_identifier = func_obj.value("ranFunctionIdentifier", 0u);
459 func.telemetry_identifier_list = func_obj.value("telemetryIdentifierList", std::vector<uint32_t>{});
460 func.control_identifier_list = func_obj.value("controlIdentifierList", std::vector<uint32_t>{});
461 if (auto it = func_obj.find("ranFunctionData"); it != func_obj.end()) {
462 func.ran_function_data = payload_from_json(*it);
463 }
464 resp.ran_function_list.push_back(func);
465 }
466 }
467 read_reason(j, resp);
468 return resp;
469}
470
471SubscriptionRequest JsonE3Encoder::decode_subscription_request(const nlohmann::json& j) const {
472 SubscriptionRequest req;
473 req.dapp_identifier = j.value("dAppIdentifier", 0u);
474 req.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
475 req.telemetry_identifier_list = j.value("telemetryIdentifierList", std::vector<uint32_t>{});
476 req.control_identifier_list = j.value("controlIdentifierList", std::vector<uint32_t>{});
477 if (j.contains("subscriptionTime")) {
478 req.subscription_time = j["subscriptionTime"].get<uint32_t>();
479 }
480 if (j.contains("periodicity")) {
481 req.periodicity = j["periodicity"].get<uint32_t>();
482 }
483 return req;
484}
485
486SubscriptionDelete JsonE3Encoder::decode_subscription_delete(const nlohmann::json& j) const {
487 SubscriptionDelete del;
488 del.dapp_identifier = j.value("dAppIdentifier", 0u);
489 del.subscription_id = j.value("subscriptionId", 0u);
490 return del;
491}
492
493SubscriptionResponse JsonE3Encoder::decode_subscription_response(const nlohmann::json& j) const {
494 SubscriptionResponse resp;
495 resp.request_id = j.value("requestId", 0u);
496 resp.dapp_identifier = j.value("dAppIdentifier", 0u);
497 std::string response_code_str = j.value("responseCode", "negative");
498 resp.response_code = (response_code_str == "positive") ? ResponseCode::POSITIVE : ResponseCode::NEGATIVE;
499 if (j.contains("subscriptionId")) {
500 resp.subscription_id = j["subscriptionId"].get<uint32_t>();
501 }
502 // Aerial writes these as ...GrantedList; accepted for interop only, recheck later.
503 auto read_ids = [&j](const char* name, const char* alias) -> std::optional<std::vector<uint32_t>> {
504 auto it = j.find(name);
505 if (it == j.end()) it = j.find(alias);
506 if (it == j.end()) return std::nullopt;
507 return it->get<std::vector<uint32_t>>();
508 };
509 resp.telemetry_identifier_list = read_ids("telemetryIdentifierList", "telemetryGrantedList");
510 resp.control_identifier_list = read_ids("controlIdentifierList", "controlGrantedList");
511 if (j.contains("ranFunctionIdentifier")) {
512 resp.ran_function_identifier = j["ranFunctionIdentifier"].get<uint32_t>();
513 }
514 if (j.contains("periodicity")) {
515 resp.periodicity = j["periodicity"].get<uint32_t>();
516 }
517 read_reason(j, resp);
518 return resp;
519}
520
521IndicationMessage JsonE3Encoder::decode_indication_message(const nlohmann::json& j,
522 const std::string& raw_json) const {
523 IndicationMessage msg;
524 msg.dapp_identifier = j.value("dAppIdentifier", 0u);
525 msg.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
526
527 size_t obj_start = raw_json.find_first_not_of(" \t\r\n");
528 auto span = (obj_start == std::string::npos)
529 ? std::nullopt
530 : find_top_level_member_span(raw_json, obj_start, "protocolData");
531
532 if (span) {
533 // Verbatim splice: byte-identical to what the SM originally emitted,
534 // instead of re-dumping the parsed subtree (which would silently
535 // reorder keys / drop whitespace for non-canonical input).
536 msg.protocol_data.assign(raw_json.begin() + static_cast<long>(span->first),
537 raw_json.begin() + static_cast<long>(span->second));
538 } else {
539 E3_LOG_DEBUG(LOG_TAG) << "protocolData byte-range scan missed; falling back to DOM dump "
540 "(ranFunctionIdentifier=" << msg.ran_function_identifier << ")";
541 std::string dumped = j["protocolData"].dump();
542 msg.protocol_data.assign(dumped.begin(), dumped.end());
543 }
544 return msg;
545}
546
547DAppControlAction JsonE3Encoder::decode_dapp_control_action(const nlohmann::json& j,
548 const std::string& raw_json) const {
549 DAppControlAction action;
550 action.dapp_identifier = j.value("dAppIdentifier", 0u);
551 action.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
552 action.control_identifier = j.value("controlIdentifier", 0u);
553 action.sequence_id = j.value("sequenceId", 0u);
554 action.request_ack = j.value("requestAck", false);
555 action.action_data = payload_member(j, raw_json, "actionData");
556 return action;
557}
558
559DAppReport JsonE3Encoder::decode_dapp_report(const nlohmann::json& j,
560 const std::string& raw_json) const {
561 DAppReport report;
562 report.dapp_identifier = j.value("dAppIdentifier", 0u);
563 report.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
564 report.sequence_id = j.value("sequenceId", 0u);
565 report.report_data = payload_member(j, raw_json, "reportData");
566 return report;
567}
568
569XAppControlAction JsonE3Encoder::decode_xapp_control_action(const nlohmann::json& j,
570 const std::string& raw_json) const {
571 XAppControlAction action;
572 action.dapp_identifier = j.value("dAppIdentifier", 0u);
573 action.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
574 action.sequence_id = j.value("sequenceId", 0u);
575 action.request_ack = j.value("requestAck", false);
576 action.xapp_control_data = payload_member(j, raw_json, "xAppControlData");
577 return action;
578}
579
580// DEPRECATED TO BE REMOVED.
581MessageAck JsonE3Encoder::decode_message_ack(const nlohmann::json& j) const {
582 MessageAck ack;
583 ack.request_id = j.value("requestId", 0u);
584 std::string response_code_str = j.value("responseCode", "negative");
585 ack.response_code = (response_code_str == "positive") ? ResponseCode::POSITIVE : ResponseCode::NEGATIVE;
586 read_reason(j, ack);
587 return ack;
588}
589
590ControlResponse JsonE3Encoder::decode_control_response(const nlohmann::json& j,
591 const std::string& raw_json) const {
592 ControlResponse resp;
593 resp.request_id = j.value("requestId", 0u);
594 resp.dapp_identifier = j.value("dAppIdentifier", 0u);
595 resp.ran_function_identifier = j.value("ranFunctionIdentifier", 0u);
596 resp.control_identifier = j.value("controlIdentifier", 0u);
597 std::string response_code_str = j.value("responseCode", "negative");
598 resp.response_code = (response_code_str == "positive") ? ResponseCode::POSITIVE : ResponseCode::NEGATIVE;
599 read_reason(j, resp);
600 if (j.contains("controlOutcome")) {
601 std::vector<uint8_t> outcome = payload_member(j, raw_json, "controlOutcome");
602 if (!outcome.empty()) resp.control_outcome = std::move(outcome);
603 }
604 return resp;
605}
606
607// ReleaseMessage encode/decode
608nlohmann::json JsonE3Encoder::encode_release_message(const ReleaseMessage& msg) const {
609 nlohmann::json j;
610 j["dAppIdentifier"] = msg.dapp_identifier;
611 return j;
612}
613
614ReleaseMessage JsonE3Encoder::decode_release_message(const nlohmann::json& j) const {
615 ReleaseMessage msg;
616 msg.dapp_identifier = j.value("dAppIdentifier", 0u);
617 return msg;
618}
619
620// ============================================================================
621// Main encode/decode methods
622// ============================================================================
623
625 try {
626 nlohmann::json root;
627 root["type"] = to_camel_case(pdu_type_to_string(pdu.type));
628 root["id"] = pdu.message_id;
629 root["timestamp"] = pdu.timestamp;
630
631 // Set only for IndicationMessage: the SM's already-serialized payload,
632 // spliced verbatim into the dumped envelope below instead of being
633 // carried through the nlohmann tree (see encode_indication_message()).
634 std::optional<std::string> raw_protocol_data;
635 bool indication_payload_invalid = false;
636
637 // Spliced as top-level members so the hot path never parses or re-dumps them.
638 std::vector<std::pair<const char*, std::string>> raw_members;
639
640 // Encode payload fields directly into root (flat format)
641 std::visit([this, &root, &raw_protocol_data, &indication_payload_invalid, &raw_members](auto&& arg) {
642 using T = std::decay_t<decltype(arg)>;
643
644 nlohmann::json fields;
645 if constexpr (std::is_same_v<T, SetupRequest>) {
646 fields = encode_setup_request(arg);
647 }
648 else if constexpr (std::is_same_v<T, SetupResponse>) {
649 fields = encode_setup_response(arg);
650 }
651 else if constexpr (std::is_same_v<T, SubscriptionRequest>) {
652 fields = encode_subscription_request(arg);
653 }
654 else if constexpr (std::is_same_v<T, SubscriptionDelete>) {
655 fields = encode_subscription_delete(arg);
656 }
657 else if constexpr (std::is_same_v<T, SubscriptionResponse>) {
658 fields = encode_subscription_response(arg);
659 }
660 else if constexpr (std::is_same_v<T, IndicationMessage>) {
661 auto encoded_fields = encode_indication_message(arg);
662 if (!encoded_fields) {
663 indication_payload_invalid = true; // already logged with attribution
664 return;
665 }
666 fields = *encoded_fields;
667 raw_protocol_data.emplace(arg.protocol_data.begin(), arg.protocol_data.end());
668 }
669 else if constexpr (std::is_same_v<T, DAppControlAction>) {
670 fields = encode_dapp_control_action(arg);
671 require_json_container(arg.action_data, "actionData");
672 raw_members.emplace_back("actionData",
673 std::string(arg.action_data.begin(), arg.action_data.end()));
674 }
675 else if constexpr (std::is_same_v<T, DAppReport>) {
676 fields = encode_dapp_report(arg);
677 require_json_container(arg.report_data, "reportData");
678 raw_members.emplace_back("reportData",
679 std::string(arg.report_data.begin(), arg.report_data.end()));
680 }
681 else if constexpr (std::is_same_v<T, XAppControlAction>) {
682 fields = encode_xapp_control_action(arg);
683 require_json_container(arg.xapp_control_data, "xAppControlData");
684 raw_members.emplace_back("xAppControlData",
685 std::string(arg.xapp_control_data.begin(),
686 arg.xapp_control_data.end()));
687 }
688 else if constexpr (std::is_same_v<T, ReleaseMessage>) {
689 fields = encode_release_message(arg);
690 }
691 else if constexpr (std::is_same_v<T, MessageAck>) {
692 fields = encode_message_ack(arg);
693 }
694 else if constexpr (std::is_same_v<T, ControlResponse>) {
695 fields = encode_control_response(arg);
696 if (arg.control_outcome && !arg.control_outcome->empty()) {
697 require_json_container(*arg.control_outcome, "controlOutcome");
698 raw_members.emplace_back("controlOutcome",
699 std::string(arg.control_outcome->begin(),
700 arg.control_outcome->end()));
701 }
702 }
703 root.update(fields);
704 }, pdu.choice);
705
706 if (indication_payload_invalid) {
707 return tl::unexpected(ErrorCode::ENCODE_FAILED);
708 }
709
710 std::string json_str = root.dump();
711
712 if (raw_protocol_data) {
713 // root.dump() sorts object keys lexicographically (documented
714 // nlohmann behavior); with protocolData excluded from the tree,
715 // "ranFunctionIdentifier" is exactly where protocolData would
716 // have sorted to ('d' < 'p' < 'r'), so this reproduces the same
717 // key position (and, for well-formed payloads, the same bytes)
718 // as before.
719 size_t pos = json_str.find("\"ranFunctionIdentifier\"");
720 if (pos == std::string::npos) {
721 E3_LOG_ERROR(LOG_TAG) << "Internal error: indication envelope missing "
722 "ranFunctionIdentifier; cannot splice protocolData";
723 return tl::unexpected(ErrorCode::ENCODE_FAILED);
724 }
725 json_str.insert(pos, "\"protocolData\":" + *raw_protocol_data + ",");
726 }
727
728 // root always holds type/id/timestamp, so it ends in '}' after a member.
729 for (const auto& [key, raw] : raw_members) {
730 json_str.pop_back();
731 json_str += ",\"";
732 json_str += key;
733 json_str += "\":" + raw + "}";
734 }
735
736 EncodedMessage msg;
737 msg.buffer.assign(json_str.begin(), json_str.end());
739
740 E3_LOG_TRACE(LOG_TAG) << "Encoded " << pdu_type_to_string(pdu.type)
741 << " (" << msg.size() << " bytes)";
742
743 return msg;
744 }
745 catch (const std::exception& e) {
746 E3_LOG_ERROR(LOG_TAG) << "JSON encode error: " << e.what();
747 return tl::unexpected(ErrorCode::ENCODE_FAILED);
748 }
749}
750
752 return decode(encoded.data(), encoded.size());
753}
754
755EncodeResult<Pdu> JsonE3Encoder::decode(const uint8_t* data, size_t size) {
756 if (data == nullptr || size == 0) {
757 E3_LOG_ERROR(LOG_TAG) << "Cannot decode empty data";
758 return tl::unexpected(ErrorCode::DECODE_FAILED);
759 }
760
761 try {
762 std::string json_str(reinterpret_cast<const char*>(data), size);
763
764 E3_LOG_TRACE(LOG_TAG) << "Decoding JSON (" << size << " bytes)";
765
766 nlohmann::json root = nlohmann::json::parse(json_str);
767
768 Pdu pdu;
769
770 // Get PDU type
771 std::string pdu_type_str = root.value("type", "");
772 auto pdu_type = string_to_pdu_type(pdu_type_str);
773 if (!pdu_type) {
774 E3_LOG_ERROR(LOG_TAG) << "Unrecognized PDU type: " << pdu_type_str;
775 return tl::unexpected(ErrorCode::DECODE_FAILED);
776 }
777 pdu.type = *pdu_type;
778 pdu.message_id = root.value("id", 0u);
779 pdu.timestamp = root.value("timestamp", 0ull);
780
781 if (root.contains("data")) {
782 E3_LOG_ERROR(LOG_TAG) << "Nested \"data\" wrapper is not supported; use flat format";
783 return tl::unexpected(ErrorCode::DECODE_FAILED);
784 }
785
786 // Decode based on PDU type
787 switch (pdu.type) {
789 pdu.choice = decode_setup_request(root);
790 break;
792 pdu.choice = decode_setup_response(root);
793 break;
795 pdu.choice = decode_subscription_request(root);
796 break;
798 pdu.choice = decode_subscription_delete(root);
799 break;
801 pdu.choice = decode_subscription_response(root);
802 break;
804 pdu.choice = decode_indication_message(root, json_str);
805 break;
807 pdu.choice = decode_dapp_control_action(root, json_str);
808 break;
810 pdu.choice = decode_dapp_report(root, json_str);
811 break;
813 pdu.choice = decode_xapp_control_action(root, json_str);
814 break;
816 pdu.choice = decode_release_message(root);
817 break;
819 pdu.choice = decode_message_ack(root);
820 break;
822 pdu.choice = decode_control_response(root, json_str);
823 break;
824 default:
825 E3_LOG_ERROR(LOG_TAG) << "Unknown PDU type: " << pdu_type_str;
826 return tl::unexpected(ErrorCode::DECODE_FAILED);
827 }
828
829 E3_LOG_TRACE(LOG_TAG) << "Decoded " << pdu_type_to_string(pdu.type);
830 return pdu;
831 }
832 catch (const nlohmann::json::parse_error& e) {
833 E3_LOG_ERROR(LOG_TAG) << "JSON parse error: " << e.what();
834 return tl::unexpected(ErrorCode::DECODE_FAILED);
835 }
836 catch (const std::exception& e) {
837 E3_LOG_ERROR(LOG_TAG) << "JSON decode error: " << e.what();
838 return tl::unexpected(ErrorCode::DECODE_FAILED);
839 }
840}
841
842} // namespace libe3
EncodeResult< Pdu > decode(const EncodedMessage &encoded) override
Decode bytes to a PDU.
EncodeResult< EncodedMessage > encode(const Pdu &pdu) override
Encode a PDU to bytes.
JSON Encoder for E3AP PDUs.
Logging facility for libe3.
#define E3_LOG_TRACE(component)
Definition logger.hpp:229
#define E3_LOG_DEBUG(component)
Definition logger.hpp:228
#define E3_LOG_ERROR(component)
Definition logger.hpp:225
ErrorCode
Error codes returned by libe3 operations Use shared error-code list (see libe3/error_codes....
Definition types.hpp:177
const char * cause_to_string(Cause cause) noexcept
Convert Cause to the name E3AP gives it in JSON and in logs.
Definition types.hpp:751
ResponseCode
E3AP response codes.
Definition types.hpp:103
@ NEGATIVE
Request rejected.
Definition types.hpp:105
@ POSITIVE
Request accepted.
Definition types.hpp:104
const char * pdu_type_to_string(PduType type) noexcept
Convert PduType to string representation.
Definition types.hpp:701
@ SUBSCRIPTION_DELETE
Definition types.hpp:148
@ SUBSCRIPTION_RESPONSE
Definition types.hpp:149
@ SUBSCRIPTION_REQUEST
Definition types.hpp:147
@ XAPP_CONTROL_ACTION
Definition types.hpp:153
@ DAPP_CONTROL_ACTION
Definition types.hpp:151
@ MESSAGE_ACK
DEPRECATED TO BE REMOVED: libe3 no longer sends it, see CONTROL_RESPONSE.
Definition types.hpp:155
@ JSON
JSON encoding (for development/debugging).
Definition types.hpp:55
tl::expected< T, ErrorCode > EncodeResult
Result type for encoding/decoding operations.
Cause cause_from_string(const std::string &name) noexcept
Read a Cause from its E3AP name.
Definition types.hpp:778
E3AP Control Response structure.
Definition types.hpp:366
uint32_t request_id
Message id of the control this answers.
Definition types.hpp:367
E3AP dApp Control Action structure.
Definition types.hpp:332
uint32_t dapp_identifier
dApp that sends the control
Definition types.hpp:333
E3AP dApp Report structure.
Definition types.hpp:392
uint32_t dapp_identifier
dApp that sends the report
Definition types.hpp:393
Encoded message wrapper.
Definition types.hpp:219
std::vector< uint8_t > buffer
Encoded data buffer.
Definition types.hpp:220
const uint8_t * data() const noexcept
Definition types.hpp:236
EncodingFormat format
Format used for encoding.
Definition types.hpp:221
size_t size() const noexcept
Definition types.hpp:232
E3AP Indication Message structure.
Definition types.hpp:323
uint32_t dapp_identifier
dApp the indication is for
Definition types.hpp:324
E3AP Message Acknowledgment structure.
Definition types.hpp:351
uint32_t request_id
ID of the request being acknowledged.
Definition types.hpp:352
Generic E3AP PDU structure.
Definition types.hpp:448
PduType type
Which alternative of choice is set.
Definition types.hpp:449
PduChoice choice
The message itself.
Definition types.hpp:450
uint64_t timestamp
Producer timestamp, in nanoseconds since the Unix epoch.
Definition types.hpp:466
uint32_t message_id
Unique message identifier.
Definition types.hpp:451
E3AP Release Message structure.
Definition types.hpp:423
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:424
E3AP Setup Request structure.
Definition types.hpp:253
std::string e3ap_protocol_version
E3AP protocol version (e.g., "0.0.0"); 1..32 bytes over ASN.1.
Definition types.hpp:254
E3AP Setup Response structure.
Definition types.hpp:273
uint32_t request_id
ID of the corresponding SetupRequest.
Definition types.hpp:274
E3AP Subscription Delete structure.
Definition types.hpp:299
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:300
E3AP Subscription Request structure.
Definition types.hpp:287
uint32_t dapp_identifier
dApp identifier
Definition types.hpp:288
E3AP Subscription Response structure.
Definition types.hpp:307
uint32_t request_id
ID of the corresponding SubscriptionRequest.
Definition types.hpp:308
E3AP xApp Control Action structure.
Definition types.hpp:405
uint32_t dapp_identifier
dApp the control is for
Definition types.hpp:406