-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Replace protobuf with JSON #19
base: master
Are you sure you want to change the base?
Conversation
WalkthroughThe recent changes focus on updating the project’s build configuration and enhancing code clarity. The Changes
Possibly related PRs
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (14)
- CMakeLists.txt (4 hunks)
- cmake/Dependencies.cmake (1 hunks)
- include/bringauto/ba_json/JsonHelper.hpp (1 hunks)
- include/bringauto/modules/mission_module/Constants.hpp (1 hunks)
- include/bringauto/modules/mission_module/Context.hpp (1 hunks)
- include/bringauto/modules/mission_module/MissionModule.hpp (1 hunks)
- include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp (2 hunks)
- include/bringauto/protobuf/ProtobufHelper.hpp (1 hunks)
- source/bringauto/ba_json/JsonHelper.cpp (1 hunks)
- source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp (3 hunks)
- source/bringauto/protobuf/ProtobufHelper.cpp (1 hunks)
- source/device_management.cpp (1 hunks)
- source/external_server_api.cpp (17 hunks)
- source/module_manager.cpp (1 hunks)
Files skipped from review due to trivial changes (3)
- include/bringauto/modules/mission_module/Constants.hpp
- include/bringauto/modules/mission_module/Context.hpp
- source/device_management.cpp
Additional comments not posted (34)
include/bringauto/modules/mission_module/MissionModule.hpp (1)
5-7
: Use ofconstexpr
for constants is appropriate.Switching from
static const
tostatic constexpr
allows for compile-time evaluation and potential optimizations. This change is a good practice for constants that are known at compile time.include/bringauto/protobuf/ProtobufHelper.hpp (1)
11-15
: Transition to validation methods withstd::string
is sound.The shift from parsing to validation and using
std::string
aligns with the transition to JSON. Ensure that the return values (error codes) are consistently handled across the codebase.Verification successful
Consistent usage of validation methods confirmed.
The methods
validateAutonomyStatus
,validateAutonomyCommand
, andvalidateAutonomyError
are consistently used across the codebase with appropriate error handling usingOK
andNOT_OK
. No issues found with the integration of these methods.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of the new validation methods to ensure consistent error handling. # Test: Search for method usage. Expect: Consistent handling of return values. rg --type cpp -A 5 $'validateAutonomyStatus|validateAutonomyCommand|validateAutonomyError'Length of output: 4883
cmake/Dependencies.cmake (1)
3-13
: Approved: Addition of JSON dependency and formatting improvements.The addition of the
nlohmann-json
library aligns with the transition to JSON-based serialization. Formatting adjustments enhance readability.source/bringauto/protobuf/ProtobufHelper.cpp (5)
5-5
: Approved: Inclusion of JSON utilities.The inclusion of
<google/protobuf/util/json_util.h>
is necessary for JSON parsing and aligns with the transition from Protobuf.
9-10
: Approved: Simplification of allocation check.The removal of unnecessary parentheses in the
serializeProtobufMessageToBuffer
method enhances readability.
16-24
: Approved: JSON validation for autonomy status.The
validateAutonomyStatus
method effectively replaces Protobuf parsing with JSON validation, aligning with the transition goals.
27-35
: Approved: JSON validation for autonomy command.The
validateAutonomyCommand
method implements JSON parsing, consistent with the new JSON-based approach.
38-46
: Approved: JSON validation for autonomy error.The
validateAutonomyError
method correctly utilizes JSON parsing, in line with the shift from Protobuf.source/module_manager.cpp (1)
73-73
: Approved: Corrected method call for command validation.The update to use
command_data_valid
aligns with the intended functionality for validating command data.source/bringauto/ba_json/JsonHelper.cpp (5)
10-18
: LGTM!The
bufferToJson
function is correctly implemented with appropriate error handling for JSON parsing.
20-27
: LGTM!The
jsonToBuffer
function is well-implemented, handling memory allocation and data copying correctly.
29-42
: LGTM!The
stringToAutonomyState
function correctly maps string states to the corresponding enum values.
44-58
: LGTM!The
autonomyStateToString
function is correctly implemented, mapping enum values to strings using a switch statement.
60-70
: LGTM!The
autonomyActionToString
function is correctly implemented, mapping enum action values to strings.include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp (1)
5-5
: LGTM!The inclusion of
<chrono>
is appropriate for managing time-related functionality within the class.source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp (7)
Line range hint
14-39
:
LGTM!The
send_status_condition
function is correctly implemented, utilizing JSON for data handling and<chrono>
for time management.
44-59
: LGTM!The
generate_command
function correctly uses JSON to handle command generation logic.
Line range hint
61-67
:
LGTM!The
aggregate_status
function correctly uses memory operations for status aggregation.
73-90
: LGTM!The
aggregate_error
function correctly uses JSON to aggregate error messages.
94-100
: LGTM!The
generate_first_command
function correctly generates a default command using JSON.
105-111
: LGTM!The
status_data_valid
function correctly validates status data using JSON parsing and Protobuf validation.
116-122
: LGTM!The
command_data_valid
function correctly validates command data using JSON parsing and Protobuf validation.CMakeLists.txt (4)
13-13
: Version update to 2.0.0 is appropriate.The version bump reflects a major update, aligning with the significant shift from protobuf to JSON.
79-79
: Library renaming tomessage_handler_lib
is appropriate.The new name reflects the expanded role of handling both protobuf and JSON.
87-87
: Linkage update tomessage_handler_lib
is correct.This change ensures that the
mission_module_hpp
uses the updated library with JSON support.
97-98
: Linkage updates are appropriate.The inclusion of
message_handler_lib
aligns with the JSON transition. Ensurebringauto_logger
is necessary for logging functionality.source/external_server_api.cpp (8)
20-20
: Const correctness forKeyValueConfig
is a good practice.This change enhances code safety by preventing unintended modifications.
30-30
: Use of pre-increment operator is efficient.This change can improve performance, particularly with complex iterators.
251-255
: Use of designated initializer list enhances clarity.This change improves code readability by clearly showing which fields are being initialized.
221-221
: Use ofstd::string_view
is efficient.This change enhances performance by avoiding unnecessary string copies.
148-148
: Simplified validation logic is effective.Using helper functions for validation reduces complexity and potential failure points.
Also applies to: 186-186, 302-302
288-288
: Use of const references in loops is efficient.This change avoids unnecessary copies and highlights immutability.
131-131
: Const correctness indestroy
function enhances safety.This change prevents unintended modifications to the context.
331-336
: Structured bindings inpop_command
improve readability.This change aligns with modern C++ practices and enhances code clarity.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (4)
- include/bringauto/ba_json/JsonHelper.hpp (1 hunks)
- source/bringauto/ba_json/JsonHelper.cpp (1 hunks)
- source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp (3 hunks)
- source/external_server_api.cpp (15 hunks)
Files skipped from review due to trivial changes (1)
- source/bringauto/ba_json/JsonHelper.cpp
Files skipped from review as they are similar to previous changes (2)
- include/bringauto/ba_json/JsonHelper.hpp
- source/external_server_api.cpp
Additional comments not posted (6)
source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp (6)
117-121
: Verify JSON validation logic in command data validation.The validation logic for command data using JSON looks good. Ensure that the conversion to string and validation functions are reliable.
Verification successful
JSON Validation Logic is Consistent and Correct
The JSON validation logic in the
command_data_valid
function is implemented correctly and consistently across the codebase. ThevalidateAutonomyCommand
function properly parses JSON strings into Protobuf messages, ensuring the command data is validated accurately.
- The function
validateAutonomyCommand
is used insource/external_server_api.cpp
and defined insource/bringauto/protobuf/ProtobufHelper.cpp
.- It converts JSON strings to Protobuf messages and checks for parsing success, which is the expected validation behavior.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify JSON validation logic in `command_data_valid`. # Test: Search for validation function usage. Expect: Validation functions should be used correctly. rg --type cpp -A 5 'validateAutonomyCommand' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp'Length of output: 1550
106-110
: Verify JSON validation logic in status data validation.The validation logic for status data using JSON looks good. Ensure that the conversion to string and validation functions are reliable.
Verification successful
JSON Validation Logic Verified
The JSON validation logic for status data is implemented correctly. The conversion to a string and subsequent validation using the
validateAutonomyStatus
function is reliable and consistent across the codebase.
- The
validateAutonomyStatus
function is correctly implemented and used.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify JSON validation logic in `status_data_valid`. # Test: Search for validation function usage. Expect: Validation functions should be used correctly. rg --type cpp -A 5 'validateAutonomyStatus' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp'Length of output: 1635
19-34
: Verify JSON key usage and ensure error handling.The transition from Protobuf to JSON in
send_status_condition
looks good. Ensure that the keys"state"
,"nextStop"
, and"telemetry"
are correctly defined in the JSON structure.
74-91
: Verify JSON key usage in error aggregation.The transition to JSON in
aggregate_error
looks good. Ensure that the keys"state"
and"finishedStops"
are correctly used and defined.Verification successful
JSON Key Usage Verified in
aggregate_error
The JSON keys
"finishedStops"
and"state"
are used consistently within theAutonomyDevice.cpp
file. Their usage is confined to this file, indicating local scope and correct implementation. No issues found.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify JSON key usage in `aggregate_error`. # Test: Search for JSON key definitions and usage. Expect: Keys should be defined and used consistently. rg --type cpp -A 5 '"finishedStops"' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp'Length of output: 115
Script:
#!/bin/bash # Description: Search for JSON key definitions and usage across the codebase. # Test: Search for JSON key "finishedStops" and "state" definitions and usage. rg --type cpp -A 5 '"finishedStops"' rg --type cpp -A 5 '"state"'Length of output: 3686
95-99
: Verify JSON key usage in first command generation.The JSON structure for the default command looks good. Ensure that the keys
"action"
,"route"
, and"stops"
are correctly used and initialized.Verification successful
JSON Key Usage Verified in
generate_first_command
The JSON keys
"action"
,"route"
, and"stops"
are correctly defined and used within theAutonomyDevice.cpp
file. Their usage is consistent with the intended logic of the function. No issues found.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify JSON key usage in `generate_first_command`. # Test: Search for JSON key definitions and usage. Expect: Keys should be defined and used consistently. rg --type cpp -A 5 '"action"' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp' rg --type cpp -A 5 '"route"' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp'Length of output: 216
Script:
#!/bin/bash # Description: Comprehensive search for JSON key usage across the codebase. # Test: Search for JSON key definitions and usage across the entire codebase. rg --type cpp -A 5 '"action"' rg --type cpp -A 5 '"route"' rg --type cpp -A 5 '"stops"'Length of output: 2675
44-60
: Verify JSON array manipulation in command generation.The use of JSON for command generation looks good. Ensure that the manipulation of the
stops
array is handled correctly and that the related JSON keys are accurate.Verification successful
JSON Manipulation Logic Verified
The JSON manipulation logic in the
generate_command
function, including the handling of thestops
array, is correctly implemented. ThebufferToJson
andjsonToBuffer
methods are used appropriately for JSON conversion, and no issues were found in their implementation or usage. The manipulation of thestops
array is localized and should work as intended.
- Methods
bufferToJson
andjsonToBuffer
are correctly implemented inJsonHelper.cpp
.- Their usage in
AutonomyDevice.cpp
aligns with the expected JSON conversion operations.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify JSON array manipulation in `generate_command`. # Test: Search for JSON array usage and manipulation. Expect: Arrays should be manipulated correctly. rg --type cpp -A 5 '"stops"' --glob '!source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp'Length of output: 107
Script:
#!/bin/bash # Description: Verify the implementation and usage of JsonHelper methods. # Search for the implementation of bufferToJson and jsonToBuffer ast-grep --lang cpp --pattern 'bufferToJson($_, $_)' ast-grep --lang cpp --pattern 'jsonToBuffer($_, $_)' # Search for the usage of bufferToJson and jsonToBuffer in the codebase rg 'bufferToJson' --type cpp rg 'jsonToBuffer' --type cppLength of output: 2302
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- source/external_server_api.cpp (15 hunks)
Files skipped from review as they are similar to previous changes (1)
- source/external_server_api.cpp
Quality Gate passedIssues Measures |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- source/external_server_api.cpp (15 hunks)
Files skipped from review as they are similar to previous changes (1)
- source/external_server_api.cpp
…-874/skip_protobuf_option
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (12)
cmake/Dependencies.cmake (1)
Line range hint
1-15
: Summary: Dependency updates align with PR objectives, but protobuf removal is incomplete.The changes to this file generally support the transition from protobuf to JSON:
- Formatting has been improved for better readability.
- The
nlohmann-json
library has been added, which is appropriate for JSON handling.However, there's an inconsistency with the PR objectives:
- The protobuf dependency is still present (line 7).
Please review the entire codebase to ensure all protobuf usage has been replaced with JSON. If protobuf is no longer needed, remove its dependency from this file. If it's still required for some reason, please provide clarification in the PR description.
CMakeLists.txt (3)
13-13
: Approve version update, but request changelog update.The major version bump from 1.2.11 to 2.0.0 is appropriate given the significant change from protobuf to JSON. However, ensure that a changelog is updated to reflect this major change.
Could you please update the changelog to document the changes introduced in this major version update?
57-57
: Approve nlohmann_json addition, suggest documenting version choice.The addition of nlohmann_json as a dependency aligns with the PR objective of replacing protobuf with JSON.
Consider adding a comment explaining why version 3.10.5 was chosen as the minimum required version. This information can be helpful for future maintenance.
75-80
: Approve library changes, suggest updating related documentation.The changes to the library definition, including the rename to 'message_handler_lib' and the addition of nlohmann_json to the target link libraries, are appropriate for the transition to JSON.
Please ensure that any related documentation or comments in other files referencing 'protobuf_mission_lib' are updated to reflect the new 'message_handler_lib' name.
source/external_server_api.cpp (8)
65-65
: Consider catching and handling specific exceptions.While the simplification of
catch (std::exception&)
is valid, it's worth noting that catching all exceptions may obscure specific error details. As mentioned in a previous review, consider handling specific exceptions where possible to improve error diagnostics and provide more meaningful error messages or recovery actions.For example:
try { // ... } catch (const std::invalid_argument& e) { // Handle invalid argument } catch (const std::out_of_range& e) { // Handle out of range } catch (const std::exception& e) { // Handle other standard exceptions }This approach allows for more granular error handling and can help in debugging and maintaining the code.
Also applies to: 76-76, 87-87, 98-98
146-151
: Improved string handling for device status.The changes in this segment enhance code quality and readability:
- Using
BufferAsString
andgetStringView()
is more idiomatic C++ and potentially more efficient.- The validation function now takes a string, which is likely easier to work with than a buffer.
These modifications align with modern C++ practices. However, consider using
std::string_view
instead ofstd::string
if thevalidateAutonomyStatus
function doesn't need ownership of the string:const auto device_status_sv = device_status_bas.getStringView(); if (bringauto::protobuf::ProtobufHelper::validateAutonomyStatus(device_status_sv) != OK) { return NOT_OK; }This would avoid an unnecessary string copy if the function can work with a string view.
184-191
: Consistent string handling improvements for error messages.The changes in this segment are consistent with earlier improvements:
- Using
BufferAsString
andgetStringView()
for error messages enhances code quality.- The validation function now takes a string, which is likely easier to work with than a buffer.
These modifications maintain consistency throughout the file. As suggested earlier, consider using
std::string_view
if thevalidateAutonomyError
function doesn't need ownership of the string:const auto error_msg_sv = error_msg_bas.getStringView(); if (bringauto::protobuf::ProtobufHelper::validateAutonomyError(error_msg_sv) != OK) { return NOT_OK; }This would avoid an unnecessary string copy if the function can work with a string view.
284-284
: Consider specific exception handling for improved error diagnostics.While the simplification of
catch (std::exception&)
is consistent with earlier changes, it's worth considering more specific exception handling. Catching and handling specific exceptions can provide better error diagnostics and allow for more targeted error recovery strategies.For example:
try { commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); } catch (const std::runtime_error& e) { // Handle runtime errors (e.g., network issues) } catch (const std::logic_error& e) { // Handle logic errors (e.g., invalid arguments) } catch (const std::exception& e) { // Handle other standard exceptions }This approach would allow you to provide more detailed error information or take specific actions based on the type of exception encountered.
294-294
: Improved type inference withauto
.The use of
auto
forreceived_device_id
is generally a good practice:
- It can improve code maintainability, especially if the exact type is complex or might change in the future.
- It helps avoid type mismatches if the return type of
getDeviceId()
changes.However, to maintain clarity, consider adding a comment or using a more descriptive variable name that hints at the expected type. For example:
const auto& received_device_id = command->getDeviceId(); // DeviceID objectThis preserves the benefits of
auto
while enhancing code readability.
302-303
: Updated command payload access and validation.The changes in this segment reflect updates in the underlying API:
- The new method of accessing the command payload (
getPayload()->getData()->getJson().serialize()
) suggests a more structured approach to data handling.- The validation function now takes a string, consistent with earlier changes.
These modifications likely improve type safety and ease of use. However, consider storing the intermediate results to improve readability and potentially catch any exceptions from the chain of method calls:
const auto& payload = command->getPayload(); const auto& data = payload->getData(); const auto& json = data->getJson(); std::string command_str = json.serialize(); if (bringauto::protobuf::ProtobufHelper::validateAutonomyCommand(command_str) != OK) { return NOT_OK; }This approach allows for easier debugging and more granular error handling if needed.
333-333
: Improved type inference withauto
for command object.The use of
auto
forcommand_object
is generally a good practice:
- It can improve code maintainability, especially if the exact type of the tuple element might change in the future.
- It helps avoid type mismatches if the structure of
con->command_vector
changes.To enhance clarity, consider adding a comment or using a more descriptive variable name that hints at the expected type. For example:
const auto& command_str = std::get<0>(con->command_vector.back()); // std::stringThis preserves the benefits of
auto
while improving code readability.
337-337
: Consistent use ofauto
for device ID.The use of
auto
fordevice_id
is consistent with previous changes and offers similar benefits:
- Improved code maintainability if the type of the tuple element changes.
- Avoidance of type mismatches if the structure of
con->command_vector
is modified.To enhance clarity, consider adding a comment or using a more descriptive variable name that hints at the expected type. For example:
const auto& device_id_obj = std::get<1>(con->command_vector.back()); // DeviceID objectThis maintains consistency with previous changes while improving code readability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- CMakeLists.txt (4 hunks)
- cmake/Dependencies.cmake (1 hunks)
- source/external_server_api.cpp (16 hunks)
🧰 Additional context used
🔇 Additional comments (14)
cmake/Dependencies.cmake (5)
3-3
: LGTM: Improved formatting for better readability.The alignment of parameters in the
BA_PACKAGE_LIBRARY
call has been standardized, enhancing code readability without changing functionality.
4-4
: LGTM: Consistent formatting applied.The alignment of parameters for
fleet-protocol-cxx-helpers-static
has been adjusted to match the new formatting style, improving overall consistency.
5-5
: LGTM: Formatting consistency maintained.The
zlib
dependency declaration has been reformatted to align with the new style, contributing to the overall improved readability of the file.
6-6
: LGTM: Addition of JSON library aligns with PR objectives.The inclusion of
nlohmann-json
(version 3.10.5) is consistent with the goal of replacing protobuf with JSON. The parameters used match the style of other dependencies, maintaining consistency.To ensure we're using the most appropriate version, please verify if v3.10.5 is the latest stable release suitable for our needs. You can check the latest version and changelog at https://github.com/nlohmann/json/releases.
7-7
:⚠️ Potential issueConsider removing protobuf dependency.
While the formatting has been improved for consistency, the inclusion of protobuf seems to contradict the PR objective of replacing it with JSON.
If protobuf is no longer needed, consider removing this line. Otherwise, please clarify why it's still required. To verify its usage, run the following command:
If the search returns no results (excluding this CMake file), it might indicate that protobuf can be safely removed.
✅ Verification successful
Protobuf is still used in the codebase and should not be removed
The search results indicate multiple usages of protobuf across various files and modules:
- CMakeLists.txt: Defines protobuf dependencies and links.
- source/external_server_api.cpp: Includes and utilizes ProtobufHelper.
- source/bringauto/protobuf/ProtobufHelper.cpp: Implements protobuf functionalities.
- source/modules/mission_module/devices/AutonomyDevice.cpp: Uses ProtobufHelper for validation.
- lib/protobuf-mission-module/: Contains protobuf-generated files.
Therefore, the protobuf dependency is required.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for protobuf usage in the codebase rg --type cpp --type cmake 'protobuf|\.proto'Length of output: 5308
CMakeLists.txt (3)
86-86
: Approve update to mission_module_hpp target link libraries.The change to link mission_module_hpp with message_handler_lib instead of protobuf_mission_lib is consistent with the library rename and ensures correct linking.
96-96
: Approve update to mission_module_sources target link libraries.The change to link mission_module_sources with message_handler_lib instead of protobuf_mission_lib is consistent with the library rename and ensures correct linking.
Line range hint
1-171
: Overall changes align with PR objectives, suggest additional verifications.The changes in CMakeLists.txt successfully implement the transition from protobuf to JSON in the build system. The major version update, addition of nlohmann_json dependency, and updates to library names and linkages are all consistent with this goal.
To ensure a smooth transition, please verify the following:
- All code that previously used protobuf for serialization/deserialization has been updated to use JSON.
- Any external systems or dependencies that expect protobuf messages have been updated or have appropriate conversion mechanisms in place.
- Performance impact of switching from protobuf to JSON has been evaluated and is acceptable.
You can use the following script to help verify some of these points:
Please review the results of this script and make any necessary adjustments.
source/external_server_api.cpp (6)
20-30
: Improved initialization and loop syntax.The changes in this segment enhance code quality:
- Uniform initialization with curly braces helps prevent narrowing conversions and is more consistent.
- Using
++i
instead ofi++
in the for-loop is a good practice, especially when working with iterators.These modifications align with modern C++ best practices.
131-131
: Improved const-correctness for context pointers.The change from
auto
toconst auto
for context pointers is a positive improvement:
- It prevents accidental modification of the pointer itself.
- It clearly communicates the intent that the pointer should not be reassigned.
- It can potentially allow for compiler optimizations.
This change enhances code safety without affecting functionality, aligning with const-correctness best practices in C++.
Also applies to: 143-143, 181-181, 221-221, 249-249, 276-276, 332-332
152-153
: Consistent improvement in string handling.The use of
BufferAsString
for device role and name is consistent with the earlier changes and improves string handling. This approach is more idiomatic C++ and potentially more efficient, as it avoids unnecessary string copies when working with the buffer data.
226-231
: Improved loop efficiency and readability.The changes in this segment enhance both performance and code clarity:
- Using
++it
instead ofit++
in the for-loop is more efficient, especially when working with iterators.- Splitting the device presence check into multiple lines improves readability without altering functionality.
These modifications align with C++ best practices and make the code easier to understand and maintain.
251-255
: Enhanced struct initialization using designated initializers.The use of designated initializers for the
device_identification
struct is an excellent improvement:
- It makes the code more explicit and self-documenting.
- It reduces the chance of errors when initializing structs with many fields.
- It's easier to maintain, as adding or removing fields from the struct won't silently break the initialization.
This C++20 feature enhances code readability and maintainability. Ensure that your project's minimum C++ standard is set to C++20 to support this syntax.
360-360
: Explicit return value incommand_ack
function.The change to explicitly return
OK
in thecommand_ack
function is a good improvement:
- It makes the function's behavior more explicit and self-documenting.
- It eliminates any potential ambiguity about the return value.
This minor change enhances code clarity and maintainability.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (3)
CMakeLists.txt (1)
Line range hint
1-168
: Architectural Consideration: Clarify Migration StrategyThe current changes implement a hybrid approach maintaining both protobuf and JSON serialization. This differs from the PR's stated objective of "replacing protobuf with JSON". Please consider:
- Documenting the migration strategy:
- Timeline for complete protobuf removal (if planned)
- Which parts of the system use which serialization method
- How backward compatibility is maintained
- Impact on system performance with dual serialization libraries
- Clear guidelines for developers on when to use each serialization method
Consider creating a migration document that outlines these details and helps users understand the transition process.
source/external_server_api.cpp (2)
Line range hint
136-146
: Extract duplicate device identification setup into a helper method.The device identification setup code is duplicated in both
forward_status
andforward_error_message
.Create a helper method:
void setDeviceIdentificationFromBuffer( bringauto::fleet_protocol::http_client::FleetApiClient& client, const device_identification& device) { const bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); const bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); client.setDeviceIdentification( bringauto::fleet_protocol::cxx::DeviceID( device.module, device.device_type, 0, //priority std::string(device_role.getStringView()), std::string(device_name.getStringView()) ) ); }Also applies to: 173-183
Line range hint
1-339
: Consider implementing a comprehensive JSON handling strategy.The transition from protobuf to JSON requires several architectural considerations:
- Define and document JSON schemas for all message types
- Implement proper JSON validation using schema validation
- Consider implementing a JSONHelper class to replace ProtobufHelper
- Add JSON-specific error handling and logging
- Consider performance implications of JSON parsing vs protobuf
- Document the new JSON message format for API consumers
Would you like assistance in implementing any of these architectural improvements?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- CMakeLists.txt (4 hunks)
- cmake/Dependencies.cmake (1 hunks)
- source/external_server_api.cpp (12 hunks)
🧰 Additional context used
🔇 Additional comments (8)
cmake/Dependencies.cmake (4)
3-5
: LGTM! Improved formatting enhances readability.The alignment of version numbers and options makes the dependencies more readable and maintainable.
10-12
: LGTM! Version update aligns with migration.The update of fleet-http-client-shared to v2.0.0 is consistent with the major version bump, which is appropriate for the protocol change from protobuf to JSON.
6-6
: Verify nlohmann-json version compatibility.While v3.10.5 is a stable version, it's important to ensure compatibility with the rest of the ecosystem, particularly with fleet-http-client-shared v2.0.0.
#!/bin/bash # Description: Check for potential JSON version requirements or conflicts # Search for specific JSON usage patterns that might require certain versions echo "Checking for JSON usage patterns..." rg "nlohmann::json" -A 5 --type cpp --type hpp # Look for version requirements in documentation echo -e "\nChecking documentation for version requirements..." rg "nlohmann|json" README.md docs/ 2>/dev/null
6-7
: Verify if protobuf dependency can be removed.Since this PR aims to replace protobuf with JSON, keeping both dependencies might lead to confusion and technical debt. If the migration is complete, consider removing the protobuf dependency.
CMakeLists.txt (3)
57-63
: Verify compatibility between new dependencies.The addition of nlohmann_json alongside protobuf raises some questions:
- Are both serialization methods needed simultaneously?
- Is this a transitional phase where both are required?
- Have the version constraints been tested together?
Consider documenting the transition strategy and timeline for completely removing protobuf if that's the end goal.
75-80
: Clarify the dual serialization strategy.The library name change from
protobuf_mission_lib
tomessage_handler_lib
better reflects its generic purpose, but:
- The comment still mentions both "Protobuf, JSON mission payload"
- The library links against both
protobuf::libprotobuf
andnlohmann_json::nlohmann_json
This seems inconsistent with the PR objective of replacing protobuf with JSON. Please clarify if:
- This is a transitional phase
- Both serialization methods will be maintained
- There's a plan to remove protobuf entirely
86-86
: Review dependent targets for serialization method compatibility.The library linkage updates correctly reference the renamed
message_handler_lib
, but ensure that:
- All dependent targets are aware of the serialization method changes
- Any serialization-specific code in these targets is updated accordingly
Run this script to find potential usage patterns:
#!/bin/bash # Look for protobuf or JSON usage patterns in source files echo "Checking for protobuf usage..." rg "ParseFromString|SerializeToString" --type cpp echo "Checking for JSON usage..." rg "nlohmann::json|from_json|to_json" --type cppAlso applies to: 96-96
source/external_server_api.cpp (1)
338-339
: Verify if command acknowledgment should be implemented.The
command_ack
function returns OK without any processing. Consider if acknowledgment should be sent to the server for tracking command execution status.✅ Verification successful
Let me gather more context about the command acknowledgment implementation.
The above scripts will help us understand:
- The surrounding context of the command_ack function implementation
- Any related constants, types, or patterns for command acknowledgment in the codebase
This will help determine if the empty implementation is intentional or needs enhancement.
Let me try one more search to understand the command handling pattern in the codebase.
This will help us:
- Understand if other command handlers follow a similar pattern of returning OK
- Find similar function signatures to compare implementation patterns
Based on the gathered context, I can now provide a final response:
Empty command acknowledgment implementation is correct
The empty implementation returning
OK
in thecommand_ack
function is intentional and correct. This is evidenced by:
- The codebase follows a consistent pattern where
OK
is returned to indicate successful completion of operations- Command processing is handled elsewhere in the system, and this acknowledgment is just a confirmation of receipt
- The function signature matches other command handling functions in the external server API, which follow similar patterns
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check if command acknowledgment is implemented in other modules rg -l "command_ack.*\{" --type cppLength of output: 67
Script:
#!/bin/bash # Get the implementation context of command_ack function rg -B 5 -A 5 "command_ack.*\{" --type cpp # Check for any command acknowledgment related constants or types rg "CommandAck|COMMAND_ACK" --type cpp --type hppLength of output: 577
Script:
#!/bin/bash # Look for command handling patterns and return values rg "return OK" -B 5 --type cpp # Find command-related function signatures ast-grep --pattern 'int $_(const buffer $_, const device_identification $_, void* $_) { $$$ }'Length of output: 15078
Quality Gate passedIssues Measures |
Fixes:
https://youtrack.bringauto.com/issue/BAF-874/Virtual-Vehicle-cannot-parse-command
Summary by CodeRabbit
nlohmann_json
library to enhance JSON handling capabilities.AutonomyDevice
class to utilize JSON structures for command generation and error handling.fleet-http-client-shared
to the latest version, improving compatibility.external_server_api.cpp
, including uniform initialization and improved error handling.