Skip to content
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

Open
wants to merge 26 commits into
base: master
Choose a base branch
from

Conversation

MarioIvancik
Copy link
Member

@MarioIvancik MarioIvancik commented Aug 14, 2024

Fixes:
https://youtrack.bringauto.com/issue/BAF-874/Virtual-Vehicle-cannot-parse-command

Summary by CodeRabbit

  • New Features
    • Updated the module versioning to signify significant enhancements and improved library management.
    • Integrated support for the nlohmann_json library to enhance JSON handling capabilities.
  • Bug Fixes
    • Improved control flow in the AutonomyDevice class to utilize JSON structures for command generation and error handling.
  • Chores
    • Updated library dependencies for fleet-http-client-shared to the latest version, improving compatibility.
    • Enhanced code clarity and safety in the external_server_api.cpp, including uniform initialization and improved error handling.

@MarioIvancik MarioIvancik self-assigned this Aug 14, 2024
Copy link
Contributor

coderabbitai bot commented Aug 14, 2024

Walkthrough

The recent changes focus on updating the project’s build configuration and enhancing code clarity. The CMakeLists.txt file has been modified to update the module version to 2.0.0, include a new dependency on nlohmann_json, and rename the library from protobuf_mission_lib to message_handler_lib. Additionally, the cmake/Dependencies.cmake file has been adjusted for improved readability and also includes the new JSON library. The source/external_server_api.cpp file has undergone several refactorings aimed at improving code consistency and maintainability.

Changes

Files Change Summary
CMakeLists.txt Updated module version to 2.0.0, added nlohmann_json dependency, renamed library to message_handler_lib, adjusted linking.
cmake/Dependencies.cmake Standardized formatting of BA_PACKAGE_LIBRARY calls, added nlohmann-json dependency.
source/external_server_api.cpp Improved code clarity through header adjustments, variable initialization, loop consistency, exception handling, const correctness, string handling, and struct initialization.

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b01f4eb and 1270015.

📒 Files selected for processing (1)
  • source/external_server_api.cpp (12 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/external_server_api.cpp

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 6f97f0f and 4d5572e.

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 of constexpr for constants is appropriate.

Switching from static const to static 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 with std::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, and validateAutonomyError are consistently used across the codebase with appropriate error handling using OK and NOT_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 to message_handler_lib is appropriate.

The new name reflects the expanded role of handling both protobuf and JSON.


87-87: Linkage update to message_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. Ensure bringauto_logger is necessary for logging functionality.

source/external_server_api.cpp (8)

20-20: Const correctness for KeyValueConfig 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 of std::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 in destroy function enhances safety.

This change prevents unintended modifications to the context.


331-336: Structured bindings in pop_command improve readability.

This change aligns with modern C++ practices and enhances code clarity.

include/bringauto/ba_json/JsonHelper.hpp Outdated Show resolved Hide resolved
source/external_server_api.cpp Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 4d5572e and 05cc21e.

Files selected for processing (1)
  • CMakeLists.txt (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • CMakeLists.txt

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 05cc21e and 7bf4394.

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. The validateAutonomyCommand function properly parses JSON strings into Protobuf messages, ensuring the command data is validated accurately.

  • The function validateAutonomyCommand is used in source/external_server_api.cpp and defined in source/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 the AutonomyDevice.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 the AutonomyDevice.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 the stops array, is correctly implemented. The bufferToJson and jsonToBuffer methods are used appropriately for JSON conversion, and no issues were found in their implementation or usage. The manipulation of the stops array is localized and should work as intended.

  • Methods bufferToJson and jsonToBuffer are correctly implemented in JsonHelper.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 cpp

Length of output: 2302

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 7bf4394 and 18b96e9.

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

Copy link

sonarcloud bot commented Aug 15, 2024

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 18b96e9 and db41bef.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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:

  1. Formatting has been improved for better readability.
  2. 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:

  1. Using BufferAsString and getStringView() is more idiomatic C++ and potentially more efficient.
  2. 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 of std::string if the validateAutonomyStatus 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:

  1. Using BufferAsString and getStringView() for error messages enhances code quality.
  2. 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 the validateAutonomyError 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 with auto.

The use of auto for received_device_id is generally a good practice:

  1. It can improve code maintainability, especially if the exact type is complex or might change in the future.
  2. 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 object

This 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:

  1. The new method of accessing the command payload (getPayload()->getData()->getJson().serialize()) suggests a more structured approach to data handling.
  2. 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 with auto for command object.

The use of auto for command_object is generally a good practice:

  1. It can improve code maintainability, especially if the exact type of the tuple element might change in the future.
  2. 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::string

This preserves the benefits of auto while improving code readability.


337-337: Consistent use of auto for device ID.

The use of auto for device_id is consistent with previous changes and offers similar benefits:

  1. Improved code maintainability if the type of the tuple element changes.
  2. 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 object

This maintains consistency with previous changes while improving code readability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between db41bef and f7b61a6.

📒 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 issue

Consider 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:

  1. All code that previously used protobuf for serialization/deserialization has been updated to use JSON.
  2. Any external systems or dependencies that expect protobuf messages have been updated or have appropriate conversion mechanisms in place.
  3. 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:

  1. Uniform initialization with curly braces helps prevent narrowing conversions and is more consistent.
  2. Using ++i instead of i++ 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 to const auto for context pointers is a positive improvement:

  1. It prevents accidental modification of the pointer itself.
  2. It clearly communicates the intent that the pointer should not be reassigned.
  3. 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:

  1. Using ++it instead of it++ in the for-loop is more efficient, especially when working with iterators.
  2. 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:

  1. It makes the code more explicit and self-documenting.
  2. It reduces the chance of errors when initializing structs with many fields.
  3. 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 in command_ack function.

The change to explicitly return OK in the command_ack function is a good improvement:

  1. It makes the function's behavior more explicit and self-documenting.
  2. It eliminates any potential ambiguity about the return value.

This minor change enhances code clarity and maintainability.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 Strategy

The 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:

  1. 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
  2. Impact on system performance with dual serialization libraries
  3. 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 and forward_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:

  1. Define and document JSON schemas for all message types
  2. Implement proper JSON validation using schema validation
  3. Consider implementing a JSONHelper class to replace ProtobufHelper
  4. Add JSON-specific error handling and logging
  5. Consider performance implications of JSON parsing vs protobuf
  6. 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

📥 Commits

Files that changed from the base of the PR and between c47cfd6 and b01f4eb.

📒 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:

  1. Are both serialization methods needed simultaneously?
  2. Is this a transitional phase where both are required?
  3. 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 to message_handler_lib better reflects its generic purpose, but:

  1. The comment still mentions both "Protobuf, JSON mission payload"
  2. The library links against both protobuf::libprotobuf and nlohmann_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:

  1. All dependent targets are aware of the serialization method changes
  2. 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 cpp

Also 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:

  1. The surrounding context of the command_ack function implementation
  2. 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:

  1. Understand if other command handlers follow a similar pattern of returning OK
  2. 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 the command_ack function is intentional and correct. This is evidenced by:

  1. The codebase follows a consistent pattern where OK is returned to indicate successful completion of operations
  2. Command processing is handled elsewhere in the system, and this acknowledgment is just a confirmation of receipt
  3. 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 cpp

Length 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 hpp

Length 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

CMakeLists.txt Show resolved Hide resolved
source/external_server_api.cpp Outdated Show resolved Hide resolved
source/external_server_api.cpp Show resolved Hide resolved
source/external_server_api.cpp Show resolved Hide resolved
Copy link

sonarcloud bot commented Oct 23, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant