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

fix: grpc dependency path resolution #1697

Closed
wants to merge 10 commits into from
Closed

fix: grpc dependency path resolution #1697

wants to merge 10 commits into from

Conversation

shashitnak
Copy link
Contributor

@shashitnak shashitnak commented Apr 11, 2024

Summary:
fixes #1686
Fixing the path resolution for imported files in the proto file

Build & Testing:

  • I ran cargo test successfully.
  • I have run ./lint.sh --mode=fix to fix all linting issues raised by ./lint.sh --mode=check.

Checklist:

  • I have added relevant unit & integration tests.
  • I have updated the documentation accordingly.
  • I have performed a self-review of my code.
  • PR follows the naming convention of <type>(<optional scope>): <title>

@github-actions github-actions bot added the type: fix Iterations on existing features or infrastructure. label Apr 11, 2024
Copy link
Contributor

coderabbitai bot commented Apr 11, 2024

Walkthrough

Walkthrough

The changes primarily involve updating the anyhow crate across various Cargo.toml files and significant modifications to Proto file handling in the codebase. The refactoring improves Proto file metadata retrieval and dependency resolution, aligning with modern practices by integrating Protox's file resolution capabilities.

Changes

File Path Change Summary
*Cargo.toml files (multiple locations) Updated anyhow dependency from "1.0.81" to "1.0.82".
src/config/reader.rs Removed proto_reader, refactored Proto file reading using ProtoReader::init.
src/generator/generator.rs Replaced proto_reader with runtime, adjusted file reading and metadata processing.
src/generator/proto/... Added new Proto files greetings.proto and greetings_message.proto.
src/proto_reader.rs Enhanced to use Protox for file path resolution, added new fields, and updated methods and test cases.

Assessment against linked issues

Objective (Issue Number) Addressed Explanation
Resolve proto file paths correctly (#1686)
Leverage Protox's file resolution capabilities (#1686)
Refactor hardcoded implementations to use Protox (#1686)

The changes effectively address the issues related to Proto file resolution and dependency management by incorporating Protox's capabilities, ensuring that Proto files are found and handled correctly.


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between c783913 and 58107e6.
Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (5)
  • src/config/reader.rs (2 hunks)
  • src/generator/generator.rs (2 hunks)
  • src/generator/proto/greetings.proto (1 hunks)
  • src/generator/proto/greetings_message.proto (1 hunks)
  • src/proto_reader.rs (6 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/config/reader.rs
  • src/generator/generator.rs
  • src/generator/proto/greetings.proto
  • src/generator/proto/greetings_message.proto
Additional Context Used
Path-based Instructions (1)
src/proto_reader.rs (1)

Pattern **/*.rs: Programming Style Guidelines

  • When calling functions that do not need to modify values, pass references of those values.
  • When calling functions that need to modify values, pass ownership of the values, and ensure they are returned from the function.

IMPORTANT: This programming style may not be suitable for performance-sensitive components or hot code paths. In such cases, prioritize efficiency and optimization strategies to enhance performance.

Testing

  1. Write Tests: For every new feature or bugfix, ensure that you write appropriate tests.
    Structure your tests in the following way:

    use pretty_assertions::assert_eq;
    fn test_something_important() {
       let value = setup_something_using_a_function();
    
       let actual = perform_some_operation_on_the_value(value);
       let expected = ExpectedValue {foo: 1, bar: 2};
    
       assert_eq!(actual, expected);
    }
    • Setup the value using helper methods in tests.
    • Create an actual and an expected value.
    • Assert the two values in a new line.
    • Ensure there are only one assertions per test.
Additional comments not posted (1)
src/proto_reader.rs (1)

14-16: Consider documenting the purpose of the new fields descriptors, files, and includes in the ProtoReader struct to enhance code maintainability and clarity.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

codecov bot commented Apr 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 87.21%. Comparing base (c783913) to head (58107e6).
Report is 14 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1697      +/-   ##
==========================================
+ Coverage   87.18%   87.21%   +0.03%     
==========================================
  Files         149      149              
  Lines       15275    15314      +39     
==========================================
+ Hits        13317    13356      +39     
  Misses       1958     1958              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

Comment on lines 25 to 39
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths
.iter()
.filter_map(|path| {
Path::new(path.as_ref())
.ancestors().nth(1)
.map(Path::to_path_buf)
})
.collect(),
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor the init method to improve clarity and maintainability. Consider using more descriptive variable names and possibly splitting complex logic into smaller functions.

-            includes: paths
-                .iter()
-                .filter_map(|path| {
-                    Path::new(path.as_ref())
-                        .ancestors().nth(1)
-                        .map(Path::to_path_buf)
-                })
-                .collect(),
+            includes: paths.iter().map(|path| get_parent_directory(path)).collect(),
+
+fn get_parent_directory<T: AsRef<str>>(path: &T) -> PathBuf {
+    Path::new(path.as_ref()).ancestors().nth(1).unwrap().to_path_buf()
+}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths
.iter()
.filter_map(|path| {
Path::new(path.as_ref())
.ancestors().nth(1)
.map(Path::to_path_buf)
})
.collect(),
}
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths.iter().map(|path| get_parent_directory(path)).collect(),
}
}
fn get_parent_directory<T: AsRef<str>>(path: &T) -> PathBuf {
Path::new(path.as_ref()).ancestors().nth(1).unwrap().to_path_buf()
}

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

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

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

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

Comment on lines +25 to +39
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths
.iter()
.filter_map(|path| {
Path::new(path.as_ref())
.ancestors()
.nth(1)
.map(Path::to_path_buf)
})
.collect(),
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor the includes computation in the init method for clarity. Consider using a helper function to encapsulate the logic of extracting the parent directory, which will make the init method cleaner and easier to understand.

-            includes: paths
-                .iter()
-                .filter_map(|path| {
-                    Path::new(path.as_ref())
-                        .ancestors().nth(1)
-                        .map(Path::to_path_buf)
-                })
-                .collect(),
+            includes: paths.iter().map(|path| get_parent_directory(path)).collect(),
+
+fn get_parent_directory<T: AsRef<str>>(path: &T) -> PathBuf {
+    Path::new(path.as_ref()).ancestors().nth(1).unwrap().to_path_buf()
+}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths
.iter()
.filter_map(|path| {
Path::new(path.as_ref())
.ancestors()
.nth(1)
.map(Path::to_path_buf)
})
.collect(),
}
pub fn init<T: AsRef<str>>(runtime: TargetRuntime, paths: &[T]) -> Self {
Self {
resource_reader: ResourceReader::init(runtime),
descriptors: HashMap::new(),
files: paths.iter().map(|path| path.as_ref().to_string()).collect(),
includes: paths.iter().map(|path| get_parent_directory(path)).collect(),
}
}
fn get_parent_directory<T: AsRef<str>>(path: &T) -> PathBuf {
Path::new(path.as_ref()).ancestors().nth(1).unwrap().to_path_buf()
}

Comment on lines +42 to +49
pub async fn load(&mut self) -> anyhow::Result<Vec<ProtoMetadata>> {
let mut metadata = Vec::new();

for file in self.files.clone().iter() {
metadata.push(self.read(file).await?);
}

Ok(metadata)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the load method by avoiding unnecessary cloning of the files vector. Use iter() directly since the vector does not need to be owned in this context.

-        for file in self.files.clone().iter() {
+        for file in self.files.iter() {
            metadata.push(self.read(file).await?);
        }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub async fn load(&mut self) -> anyhow::Result<Vec<ProtoMetadata>> {
let mut metadata = Vec::new();
for file in self.files.clone().iter() {
metadata.push(self.read(file).await?);
}
Ok(metadata)
pub async fn load(&mut self) -> anyhow::Result<Vec<ProtoMetadata>> {
let mut metadata = Vec::new();
for file in self.files.iter() {
metadata.push(self.read(file).await?);
}
Ok(metadata)

Comment on lines +67 to +112
async fn resolve_dependencies(
&mut self,
parent_proto: FileDescriptorProto,
parent_path: &str,
) -> anyhow::Result<Vec<FileDescriptorProto>> {
let mut descriptors: HashMap<String, FileDescriptorProto> = HashMap::new();
let mut queue = VecDeque::new();
let parent_path = Path::new(parent_path).ancestors().nth(1).unwrap();
println!("{}", parent_path.display());

queue.push_back(parent_proto.clone());

while let Some(file) = queue.pop_front() {
let futures: Vec<_> = file
.dependency
.iter()
.map(|import| self.read_proto(import))
.map(|import| async {
let import = import.clone();
let import = self
.includes
.iter()
.find_map(|include| {
let path = include.join(&import);
path.exists().then_some(path)
})
.unwrap_or_else(|| PathBuf::from(import));
self.read_proto(import.to_str().unwrap()).await
})
.collect();

let results = join_all(futures).await;

for result in results {
let proto = result?;
let descriptors = &mut self.descriptors;
if descriptors.get(proto.name()).is_none() {
queue.push_back(proto.clone());
descriptors.insert(proto.name().to_string(), proto);
}
}
}

let mut descriptors_vec = descriptors
.into_values()
let hash_map = &mut self.descriptors;

let mut descriptors_vec = hash_map
.values()
.cloned()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling in the resolve_dependencies method to prevent potential runtime panics. Specifically, handle cases where ancestors().nth(1) might return None, which currently leads to an unwrap() call that could panic.

-        let parent_path = Path::new(parent_path).ancestors().nth(1).unwrap();
+        let parent_path = Path::new(parent_path).ancestors().nth(1).ok_or_else(|| anyhow::Error::msg("Parent path not found"))?;

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
async fn resolve_dependencies(
&mut self,
parent_proto: FileDescriptorProto,
parent_path: &str,
) -> anyhow::Result<Vec<FileDescriptorProto>> {
let mut descriptors: HashMap<String, FileDescriptorProto> = HashMap::new();
let mut queue = VecDeque::new();
let parent_path = Path::new(parent_path).ancestors().nth(1).unwrap();
println!("{}", parent_path.display());
queue.push_back(parent_proto.clone());
while let Some(file) = queue.pop_front() {
let futures: Vec<_> = file
.dependency
.iter()
.map(|import| self.read_proto(import))
.map(|import| async {
let import = import.clone();
let import = self
.includes
.iter()
.find_map(|include| {
let path = include.join(&import);
path.exists().then_some(path)
})
.unwrap_or_else(|| PathBuf::from(import));
self.read_proto(import.to_str().unwrap()).await
})
.collect();
let results = join_all(futures).await;
for result in results {
let proto = result?;
let descriptors = &mut self.descriptors;
if descriptors.get(proto.name()).is_none() {
queue.push_back(proto.clone());
descriptors.insert(proto.name().to_string(), proto);
}
}
}
let mut descriptors_vec = descriptors
.into_values()
let hash_map = &mut self.descriptors;
let mut descriptors_vec = hash_map
.values()
.cloned()
async fn resolve_dependencies(
&mut self,
parent_proto: FileDescriptorProto,
parent_path: &str,
) -> anyhow::Result<Vec<FileDescriptorProto>> {
let mut queue = VecDeque::new();
let parent_path = Path::new(parent_path).ancestors().nth(1).ok_or_else(|| anyhow::Error::msg("Parent path not found"))?;
println!("{}", parent_path.display());
queue.push_back(parent_proto.clone());
while let Some(file) = queue.pop_front() {
let futures: Vec<_> = file
.dependency
.iter()
.map(|import| async {
let import = import.clone();
let import = self
.includes
.iter()
.find_map(|include| {
let path = include.join(&import);
path.exists().then_some(path)
})
.unwrap_or_else(|| PathBuf::from(import));
self.read_proto(import.to_str().unwrap()).await
})
.collect();
let results = join_all(futures).await;
for result in results {
let proto = result?;
let descriptors = &mut self.descriptors;
if descriptors.get(proto.name()).is_none() {
queue.push_back(proto.clone());
descriptors.insert(proto.name().to_string(), proto);
}
}
}
let hash_map = &mut self.descriptors;
let mut descriptors_vec = hash_map
.values()
.cloned()

Comment on lines +52 to +61
pub async fn read(&mut self, path: &str) -> anyhow::Result<ProtoMetadata> {
let proto = self.read_proto(path).await?;
if proto.package.is_none() {
anyhow::bail!("Package name is required");
}

let descriptors = self.resolve_descriptors(file_read).await?;
let descriptors = self.resolve_dependencies(proto, path).await?;
let metadata = ProtoMetadata {
descriptor_set: FileDescriptorSet { file: descriptors },
path: path.as_ref().to_string(),
path: path.to_string(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the error message in the read method is clear and actionable when the package name is missing from the proto file.

-            anyhow::bail!("Package name is required");
+            anyhow::bail!("Package name is required in the proto file: {}", path);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub async fn read(&mut self, path: &str) -> anyhow::Result<ProtoMetadata> {
let proto = self.read_proto(path).await?;
if proto.package.is_none() {
anyhow::bail!("Package name is required");
}
let descriptors = self.resolve_descriptors(file_read).await?;
let descriptors = self.resolve_dependencies(proto, path).await?;
let metadata = ProtoMetadata {
descriptor_set: FileDescriptorSet { file: descriptors },
path: path.as_ref().to_string(),
path: path.to_string(),
pub async fn read(&mut self, path: &str) -> anyhow::Result<ProtoMetadata> {
let proto = self.read_proto(path).await?;
if proto.package.is_none() {
anyhow::bail!("Package name is required in the proto file: {}", path);
}
let descriptors = self.resolve_dependencies(proto, path).await?;
let metadata = ProtoMetadata {
descriptor_set: FileDescriptorSet { file: descriptors },
path: path.to_string(),

Copy link

Action required: PR inactive for 2 days.
Status update or closure in 5 days.

@github-actions github-actions bot added the state: inactive No current action needed/possible; issue fixed, out of scope, or superseded. label Apr 13, 2024
@shashitnak shashitnak closed this Apr 18, 2024
@shashitnak
Copy link
Contributor Author

fixed in #1705

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
state: inactive No current action needed/possible; issue fixed, out of scope, or superseded. type: fix Iterations on existing features or infrastructure.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

bug(grpc): proto files are not found
3 participants