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

feat: provide genes/transcripts endpoint with openapi (#605) #610

Conversation

holtgrewe
Copy link
Contributor

@holtgrewe holtgrewe commented Nov 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration file for Codecov to enhance coverage reporting.
    • Added a new service endpoint for gene transcript handling in the web server.
    • Enhanced type conversion capabilities for the Assembly enum and its interaction with genome builds.
  • Bug Fixes

    • Improved error handling for gene transcript queries and responses.
  • Documentation

    • Updated comments for API endpoint paths for clarity.

@holtgrewe holtgrewe linked an issue Nov 11, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Warning

Rate limit exceeded

@holtgrewe has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b612ae3 and 80902db.

Walkthrough

The changes introduce a new configuration file, codecov.yml, for coverage reporting settings, including coverage range and ignored paths. Additionally, significant modifications are made to the gene_txs.rs file, refactoring endpoint handling functions, enhancing error management, and adding new structures for query and response handling. The mod.rs file sees the addition of a new service endpoint, while the versions.rs file enhances type conversion capabilities between Assembly and pbs::txs::GenomeBuild, along with updates to documentation.

Changes

File Path Change Summary
codecov.yml New configuration file added for Codecov, specifying coverage settings, patch coverage disabled, coverage range from 70 to 90, rounding method, precision, and ignored paths.
src/server/run/actix_server/gene_txs.rs Refactored function handle to genes_tx_impl, added new async function handle_with_openapi, updated error handling, and introduced new structures and enums for query and response handling.
src/server/run/actix_server/mod.rs Added new service endpoint gene_txs::handle_with_openapi to the Actix web server configuration.
src/server/run/actix_server/versions.rs Added implementations of From and TryFrom traits for converting between Assembly and pbs::txs::GenomeBuild, and updated documentation for VersionsInfoResponse struct regarding API endpoint path.

Poem

In the code where rabbits play,
New paths and structures come to stay.
With coverage set and queries bright,
We hop along, coding with delight!
Each function gleams, each enum sings,
In our burrow, joyfully, we bring! 🐇✨


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.

@holtgrewe holtgrewe force-pushed the 605-provide-endpoint-alternative-with-openapi-schema-for-genestxs branch from dd2f61a to b612ae3 Compare November 11, 2024 06:23
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

🧹 Outside diff range and nitpick comments (6)
src/server/run/actix_server/mod.rs (1)

62-62: LGTM! Consider API versioning strategy.

The addition of handle_with_openapi alongside the existing handle endpoint is logically placed. However, having two endpoints for potentially the same functionality suggests a transition period.

Consider:

  1. Documenting the deprecation timeline for the non-OpenAPI endpoint
  2. Adding OpenAPI support to all endpoints consistently
  3. Implementing API versioning through content negotiation or accept headers instead of parallel endpoints
src/server/run/actix_server/versions.rs (1)

44-63: Enhance error message in TryFrom implementation.

The type conversion implementations are well-structured and handle all cases appropriately. However, the error message in the catch-all arm could be more descriptive.

Consider enhancing the error message to include the actual value:

-            _ => Err(anyhow::anyhow!("Unsupported assembly")),
+            other => Err(anyhow::anyhow!("Unsupported assembly: {:?}", other)),
src/server/run/actix_server/gene_txs.rs (4)

35-36: Use safer default conversion for genome_build

The expression GenomeBuild::Grch37 as i32 relies on the underlying representation of the enum, which can be prone to errors if the enum's definition changes. It's safer to use the into() method for conversions.

Apply this diff to improve the safety of the default value conversion:

-    let genome_build = GenomeBuild::try_from(genome_build.unwrap_or(GenomeBuild::Grch37 as i32))
+    let genome_build = GenomeBuild::try_from(genome_build.unwrap_or_else(|| GenomeBuild::Grch37.into()))

89-93: Align field optionality between query structs

In GenesTranscriptsListQuery, hgnc_id and genome_build are required fields, whereas in GeneTranscriptsQuery, they are optional (Option<String> and Option<i32> respectively). This inconsistency may lead to confusion and potential errors during conversions.

Consider making hgnc_id and genome_build optional in GenesTranscriptsListQuery to align with GeneTranscriptsQuery, or adjust the conversion logic to account for the differences in field optionality.


284-314: Simplify nested conversions in Transcript implementation

The nested try_from calls within the TryFrom implementation for Transcript can make the code harder to read and maintain.

Consider refactoring the nested conversions using helper functions or intermediary variables to enhance readability. For example:

let biotype = pbs::txs::TranscriptBiotype::try_from(value.biotype)
    .map_err(|e| anyhow::anyhow!("Invalid biotype: {}", e))
    .and_then(TranscriptBiotype::try_from)?;

let tags = value
    .tags
    .into_iter()
    .map(pbs::txs::TranscriptTag::try_from)
    .map(|res| res.and_then(TranscriptTag::try_from))
    .collect::<Result<Vec<_>, _>>()?;

356-359: Provide more context in conversion error messages

The error message "Conversion error: {}" may not give sufficient context when a conversion fails in handle_with_openapi.

Enhance the error message to include more details, which can aid in debugging:

-    CustomError::new(anyhow::anyhow!("Conversion error: {}", e))
+    CustomError::new(anyhow::anyhow!("Failed to convert GeneTranscriptsResponse: {}", e))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ba15439 and b612ae3.

📒 Files selected for processing (4)
  • codecov.yml (1 hunks)
  • src/server/run/actix_server/gene_txs.rs (4 hunks)
  • src/server/run/actix_server/mod.rs (1 hunks)
  • src/server/run/actix_server/versions.rs (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • codecov.yml
🔇 Additional comments (3)
src/server/run/actix_server/mod.rs (1)

Line range hint 62-67: Verify OpenAPI documentation generation.

The new endpoint should be properly documented in the OpenAPI schema that's being served at /api-docs/openapi.json.

✅ Verification successful

Let me gather more information about the OpenAPI documentation.


Let me check for the schema definition and API documentation structure.


Let me check the OpenAPI configuration in more detail.


Based on the gathered information, I can now provide the final response:

OpenAPI documentation is properly implemented for the endpoint

The endpoint is correctly documented with:

  • Path operation decorator with #[utoipa::path]
  • Proper response schema definition using GenesTranscriptsListResponse
  • Integration with Swagger UI at /swagger-ui and OpenAPI JSON at /api-docs/openapi.json
  • Complete response documentation including success (200) and error (500) cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the new endpoint is documented in OpenAPI schema

# Test: Search for OpenAPI/Swagger documentation related to the genes/transcripts endpoint
rg -l "genes/transcripts" --type rust

Length of output: 97


Script:

#!/bin/bash
# Check for OpenAPI documentation in gene_txs.rs
rg "#\[utoipa" -A 5 src/server/run/actix_server/gene_txs.rs

# Check for any OpenAPI path definitions
ast-grep --pattern 'OpenApi::new().path($$$)'

Length of output: 388


Script:

#!/bin/bash
# Check for OpenAPI schema definitions in gene_txs.rs
rg "impl Schema" -A 5 src/server/run/actix_server/gene_txs.rs

# Check for the OpenAPI configuration
rg "ApiDoc" --type rust -A 5

Length of output: 1615


Script:

#!/bin/bash
# Check the OpenAPI configuration implementation
rg "impl ApiDoc" -A 10 src/server/run/mod.rs

# Check for schema components and responses
rg "GenesTranscriptsListResponse" --type rust

Length of output: 645

src/server/run/actix_server/versions.rs (2)

6-6: LGTM: Import addition is appropriate.

The new import for pbs is necessary for the type conversions and follows Rust's import conventions.


44-63: Verify usage of the new type conversions.

Let's ensure these conversions are being used consistently across the codebase.

✅ Verification successful

Based on the search results, I can now generate the final response:

Type conversions are used correctly and consistently

The new type conversions between Assembly and GenomeBuild in versions.rs are part of a well-structured type conversion chain in the codebase:

  • Used in gene_txs.rs for handling genome build parameters in API requests
  • Integrates with existing conversions in common/mod.rs between GenomeRelease, Assembly, and GenomeBuild
  • Maintains consistency with the biocommons ecosystem through biocommons_bioutils::assemblies::Assembly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of Assembly and GenomeBuild conversions

# Test: Find direct usage of the conversion methods
echo "=== Direct conversion usage ==="
rg "\.into\(\)" -A 2 -B 2 | grep -C 2 "Assembly.*GenomeBuild\|GenomeBuild.*Assembly"

# Test: Find potential places where conversion might be needed
echo "=== Potential conversion locations ==="
rg "GenomeBuild|Assembly" --type rust

Length of output: 10071

@@ -87,7 +108,7 @@ impl DataVersionEntry {
}
}

/// Response of the `/v1/version` endpoint.
/// Response of the `/api/v1/version` endpoint.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix documentation inconsistency.

The documentation comment mentions /api/v1/version but the actual endpoint path is /api/v1/versionsInfo.

Update the documentation to match the actual endpoint path:

-/// Response of the `/api/v1/version` endpoint.
+/// Response of the `/api/v1/versionsInfo` endpoint.
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Response of the `/api/v1/version` endpoint.
/// Response of the `/api/v1/versionsInfo` endpoint.

Comment on lines +242 to +255
impl TryFrom<pbs::txs::GenomeAlignment> for GenomeAlignment {
type Error = anyhow::Error;

fn try_from(value: pbs::txs::GenomeAlignment) -> Result<Self, Self::Error> {
Ok(GenomeAlignment {
genome_build: Assembly::try_from(pbs::txs::GenomeBuild::try_from(value.genome_build)?)?,
contig: value.contig.clone(),
cds_start: value.cds_start,
cds_end: value.cds_end,
strand: Strand::from(pbs::txs::Strand::try_from(value.strand)?),
exons: value.exons.into_iter().map(Into::into).collect(),
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential errors in GenomeAlignment conversion

In the TryFrom implementation for GenomeAlignment, the conversion of pbs::txs::GenomeAlignment to GenomeAlignment does not handle errors that may occur during the conversion of exons.

Update the exons mapping to handle possible errors:

-            exons: value.exons.into_iter().map(Into::into).collect(),
+            exons: value
+                .exons
+                .into_iter()
+                .map(TryInto::try_into)
+                .collect::<Result<_, _>>()?,

Also, adjust the function to return a Result<Self, Self::Error> that appropriately handles these potential conversion errors.

📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
impl TryFrom<pbs::txs::GenomeAlignment> for GenomeAlignment {
type Error = anyhow::Error;
fn try_from(value: pbs::txs::GenomeAlignment) -> Result<Self, Self::Error> {
Ok(GenomeAlignment {
genome_build: Assembly::try_from(pbs::txs::GenomeBuild::try_from(value.genome_build)?)?,
contig: value.contig.clone(),
cds_start: value.cds_start,
cds_end: value.cds_end,
strand: Strand::from(pbs::txs::Strand::try_from(value.strand)?),
exons: value.exons.into_iter().map(Into::into).collect(),
})
}
}
impl TryFrom<pbs::txs::GenomeAlignment> for GenomeAlignment {
type Error = anyhow::Error;
fn try_from(value: pbs::txs::GenomeAlignment) -> Result<Self, Self::Error> {
Ok(GenomeAlignment {
genome_build: Assembly::try_from(pbs::txs::GenomeBuild::try_from(value.genome_build)?)?,
contig: value.contig.clone(),
cds_start: value.cds_start,
cds_end: value.cds_end,
strand: Strand::from(pbs::txs::Strand::try_from(value.strand)?),
exons: value
.exons
.into_iter()
.map(TryInto::try_into)
.collect::<Result<_, _>>()?,
})
}
}

@holtgrewe holtgrewe merged commit 9132312 into main Nov 11, 2024
9 checks passed
@holtgrewe holtgrewe deleted the 605-provide-endpoint-alternative-with-openapi-schema-for-genestxs branch November 11, 2024 06:56
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.

Provide endpoint alternative with OpenAPI schema for /genes/txs
1 participant