Skip to content

Prelude.rs#103

Merged
grunch merged 3 commits into
mainfrom
prelude
May 5, 2025
Merged

Prelude.rs#103
grunch merged 3 commits into
mainfrom
prelude

Conversation

@arkanoider

@arkanoider arkanoider commented May 3, 2025

Copy link
Copy Markdown
Collaborator

@grunch ,

this is mostro-core with prelude.rs so now all symbols in prelude are re-exported and we can remove some bloat import in many files in mostrod, I have yet a branch of mostrod with the clean done. Will push it.

Summary by CodeRabbit

  • New Features

    • Introduced a new prelude module to simplify importing commonly used types and traits.
  • Refactor

    • Centralized and reorganized constants and type exports for easier access.
    • Removed certain public constants from the main library and redefined them where needed.
    • Improved error handling by replacing generic errors with domain-specific error types in order and rating processing.
  • Chores

    • Added homepage and repository metadata to the package configuration.

@coderabbitai

coderabbitai Bot commented May 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes update the "mostro-core" package metadata by adding homepage and repository fields in Cargo.toml. Two public constants, NOSTR_REPLACEABLE_EVENT_KIND and PROTOCOL_VER, are removed from the crate root and defined locally within the message module with added documentation. A new public prelude module is introduced, re-exporting commonly used types and constants from multiple modules to simplify imports. Error handling in order.rs and rating.rs is changed from using anyhow::Result to a custom Result type with ServiceError, providing explicit domain-specific error mapping. Minor import reordering occurs in message.rs tests.

Changes

File(s) Change Summary
Cargo.toml Added homepage and repository metadata fields; no other changes.
src/lib.rs Removed public constants NOSTR_REPLACEABLE_EVENT_KIND and PROTOCOL_VER; added public prelude module.
src/message.rs Defined NOSTR_REPLACEABLE_EVENT_KIND and PROTOCOL_VER locally with documentation; reordered test imports.
src/prelude.rs Added new module re-exporting commonly used types and constants from multiple modules.
src/order.rs Changed SmallOrder JSON serialization methods to return Result with ServiceError instead of anyhow::Result.
src/rating.rs Changed from_tags method to return Result with ServiceError instead of anyhow::Result; updated error mapping and imports.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant prelude
    participant message
    participant order
    participant error
    participant dispute
    participant rating
    participant usermod

    User->>App: Import prelude
    App->>prelude: Access types/constants (e.g., Message, MostroError)
    prelude->>message: Re-export message-related items
    prelude->>order: Re-export order-related items
    prelude->>error: Re-export error types
    prelude->>dispute: Re-export dispute types
    prelude->>rating: Re-export Rating
    prelude->>usermod: Re-export User, UserInfo
Loading

Possibly related PRs

  • Better error handling #65: Also modifies error handling in src/rating.rs, improving robustness and changing error types in the from_tags method of the Rating struct.

Suggested reviewers

  • grunch

Poem

A homepage set, a repo found,
Constants moved, no longer bound.
Prelude calls with open arms,
Types and traits with all their charms.
Errors mapped with care and grace,
A cleaner code, a brighter place.
🐇🌿✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/prelude.rs (1)

15-15: Consider qualifying MostroError variant exports.

The line pub use MostroError::*; re-exports all variants of the MostroError enum directly into the prelude namespace. This could potentially cause name collisions if any variant names overlap with other items.

Consider either:

  1. Re-exporting just the enum: pub use crate::error::MostroError;
  2. Or if direct variant access is desired, use a qualified re-export pattern to avoid potential collisions.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1f27fd and 26e4276.

📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • src/lib.rs (1 hunks)
  • src/message.rs (2 hunks)
  • src/prelude.rs (1 hunks)
🔇 Additional comments (5)
Cargo.toml (1)

3-3: Version bump is appropriate for the introduction of a prelude module.

The version increment from 0.6.38 to 0.6.39 aligns with the scope of changes, which are non-breaking structural improvements.

src/lib.rs (1)

5-5: LGTM: Clear and appropriate module addition.

Adding the prelude module to the public exports follows the Rust convention for creating a centralized import point, which will help simplify imports in downstream code.

src/message.rs (2)

20-23: Moving constants to their semantically appropriate module.

Relocating NOSTR_REPLACEABLE_EVENT_KIND and PROTOCOL_VER to the message module where they are primarily used improves code organization. The documentation also clearly explains the purpose of these constants.


437-437: Minor import reordering.

The reordering of the UserInfo import is a minor stylistic change that doesn't affect functionality.

src/prelude.rs (1)

1-15: Well-structured prelude module with comprehensive exports.

The prelude module is well-organized and includes exports from all relevant modules, making it easier for consumers to import commonly used types and traits.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 comments (1)
src/rating.rs (1)

34-41: 🛠️ Refactor suggestion

Consider updating other methods for consistent error handling

While from_tags has been updated to use the ServiceError type, the from_json and as_json methods (lines 34-36 and 39-41) are still using a generic Result type. For consistency, consider updating these methods to also return Result<_, ServiceError> with appropriate error mapping.

-pub fn from_json(json: &str) -> Result<Self> {
-    Ok(serde_json::from_str(json)?)
+pub fn from_json(json: &str) -> Result<Self, ServiceError> {
+    serde_json::from_str(json).map_err(|_| ServiceError::MessageSerializationError)
}

-pub fn as_json(&self) -> Result<String> {
-    Ok(serde_json::to_string(&self)?)
+pub fn as_json(&self) -> Result<String, ServiceError> {
+    serde_json::to_string(&self).map_err(|_| ServiceError::MessageSerializationError)
}
🧹 Nitpick comments (1)
src/order.rs (1)

34-41: Consider updating error handling in Order.as_new_order method

The method as_new_order on line 193 calls unwrap() on the result of Kind::from_str and Status::from_str. Consider using error handling with map_err to convert these potential errors to ServiceError for consistency with the updated error handling approach.

pub fn as_new_order(&self) -> SmallOrder {
    SmallOrder::new(
        Some(self.id),
-       Some(Kind::from_str(&self.kind).unwrap()),
-       Some(Status::from_str(&self.status).unwrap()),
+       Some(Kind::from_str(&self.kind).unwrap_or(Kind::Buy)), // Or handle with proper error
+       Some(Status::from_str(&self.status).unwrap_or(Status::Active)), // Or handle with proper error
        self.amount,
        self.fiat_code.clone(),
        self.min_amount,
        self.max_amount,
        self.fiat_amount,
        self.payment_method.clone(),
        self.premium,
        None,
        None,
        self.buyer_invoice.clone(),
        Some(self.created_at),
        Some(self.expires_at),
        None,
        None,
    )
}

Alternatively, you could change this method to return a Result<SmallOrder, ServiceError> for more robust error handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26e4276 and 85e2b86.

📒 Files selected for processing (5)
  • Cargo.toml (1 hunks)
  • src/message.rs (2 hunks)
  • src/order.rs (1 hunks)
  • src/prelude.rs (1 hunks)
  • src/rating.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • Cargo.toml
  • src/message.rs
  • src/prelude.rs
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/order.rs (2)
src/rating.rs (2)
  • from_json (34-36)
  • as_json (39-41)
src/message.rs (6)
  • from_json (36-38)
  • from_json (154-156)
  • from_json (287-289)
  • as_json (40-42)
  • as_json (159-161)
  • as_json (291-293)
🔇 Additional comments (7)
src/rating.rs (4)

4-4: Good improvement to error handling structure!

Adding the import for ServiceError is a positive change that supports the transition from generic anyhow errors to domain-specific error types. This aligns well with the PR's goal of cleaning up imports and making code more maintainable.


78-78: Appropriate method signature update

Changing the return type from generic Result<Self> to specific Result<Self, ServiceError> improves type safety and makes error handling expectations clearer. This is a good step toward more robust error handling.


89-92: Better error creation with domain-specific error types

Replacing generic error creation with ServiceError::NostrError makes the error handling more structured and specific, which will help with debugging and error handling throughout the application.


94-118: Improved number parsing error handling

The explicit mapping of parsing errors to ServiceError::ParsingNumberError is more maintainable than propagating generic errors. This approach provides clearer error context and improves error handling consistency.

src/order.rs (3)

464-466: Good error handling improvement

Converting from anyhow::Result to a domain-specific Result<Self, ServiceError> improves error clarity and type safety. The explicit mapping to ServiceError::MessageSerializationError makes the error handling more structured and predictable.


469-471: Consistent error handling approach

Using the same pattern as from_json for the as_json method maintains consistency in the error handling approach throughout the codebase. This is a positive change that aligns with the PR's goal of standardizing error handling.


1-557: The prelude pattern will simplify imports

The new prelude module introduced in this PR will significantly reduce import boilerplate across the codebase. Converting these domain-specific error types (Result<Self, ServiceError>) is an excellent pairing with the prelude pattern, as it will make it easier to consistently use these error types throughout the codebase.

@grunch grunch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@grunch grunch merged commit 7be3a23 into main May 5, 2025
2 checks passed
@grunch grunch deleted the prelude branch May 5, 2025 22:41
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.

2 participants