Skip to content

Settings refactor#481

Merged
grunch merged 14 commits into
mainfrom
settings-refactor
May 14, 2025
Merged

Settings refactor#481
grunch merged 14 commits into
mainfrom
settings-refactor

Conversation

@arkanoider

@arkanoider arkanoider commented May 2, 2025

Copy link
Copy Markdown
Collaborator

@grunch ,

refactored Settings module in a more readable way (imo) . I called the module Config
This goes in the sense of having Mostrod always more readable and without long files.

Let me know your opinion.

Summary by CodeRabbit

  • Refactor
    • Reorganized configuration management into a dedicated module, improving structure and maintainability.
    • Updated import paths throughout the application to use the new configuration module.
    • Removed the old configuration file and split logic into separate files for settings, types, and utilities.
    • Simplified CLI settings initialization and updated function signatures for better error handling.
  • Documentation
    • Added and updated module-level documentation for configuration-related code.
  • Chores
    • Cleaned up unused module declarations and improved code organization.
  • Dependencies
    • Added the "toml" and "dirs" crates; removed the "config" crate from dependencies.

@coderabbitai

coderabbitai Bot commented May 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes reorganize the application's configuration management by moving all settings-related logic from src/cli/settings.rs to a new src/config module, which is subdivided into settings, types, and util submodules. This restructuring involves updating all import paths referencing the Settings struct and related configuration types to use the new module structure. The init_default_dir function and configuration data structures are now located in the new config module. The old src/cli/settings.rs file is deleted, and public re-exports are provided in src/config/mod.rs for easier access throughout the codebase.

Changes

File(s) Change Summary
src/cli/settings.rs Deleted; all configuration logic and types moved to the new src/config module.
src/config/mod.rs, src/config/settings.rs, New config module introduced with submodules for settings, types, and utilities; re-exports key items.
src/config/types.rs, src/config/util.rs New files defining configuration structs, trait implementations, and utility functions for config management.
src/cli.rs Removed pub mod settings;, updated imports to use new config module, changed settings_init signature and logic.
src/app.rs, src/app/order.rs, src/app/release.rs Updated import paths for Settings to use crate::config::settings::Settings.
src/db.rs, src/lightning/invoice.rs, src/lightning/mod.rs Updated import paths for Settings to use new config module; minor clone adjustments for owned values.
src/main.rs Added pub mod config;, updated imports for settings initialization; removed explicit global init call.
src/nip33.rs, src/scheduler.rs, src/util.rs Updated import paths for Settings to new config module.
Cargo.toml Added dependencies: toml and dirs; removed config crate.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant ConfigUtil
    participant ConfigSettings
    participant GlobalConfig

    Main->>ConfigUtil: init_configuration_file(config_path)
    ConfigUtil->>ConfigUtil: Create config dir if missing
    ConfigUtil-->>Main: Return or create config path and settings file

    Main->>ConfigSettings: Settings::new(config_path)
    ConfigSettings->>ConfigSettings: Load and merge config file & env vars
    ConfigSettings->>GlobalConfig: init_mostro_settings(settings)
    GlobalConfig-->>ConfigSettings: Store settings globally
    ConfigSettings-->>Main: Return Settings instance

    Main->>GlobalConfig: Access config via getters (e.g., get_ln, get_db)
    GlobalConfig-->>Main: Return requested config section
Loading

Suggested reviewers

  • grunch

Poem

In burrows deep, a rabbit found
Configs scattered all around.
With nimble paws and tidy flair,
It moved them to a proper lair.
Now settings live where they belong—
In config/, neat and strong!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6491ae5 and b84963e.

📒 Files selected for processing (1)
  • src/config/util.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/config/util.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests
✨ 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: 4

🧹 Nitpick comments (5)
src/config/settings.rs (1)

52-67: Consider safer accessor methods to avoid potential panics

The getter methods use unwrap() which could panic if the global config hasn't been initialized. Consider using Result or Option return types or documenting that these should only be called after initialization.

impl Settings {
    // ...
-    pub fn get_ln() -> Lightning {
-        MOSTRO_CONFIG.get().unwrap().lightning.clone()
+    pub fn get_ln() -> Option<Lightning> {
+        MOSTRO_CONFIG.get().map(|config| config.lightning.clone())
    }

-    pub fn get_mostro() -> Mostro {
-        MOSTRO_CONFIG.get().unwrap().mostro.clone()
+    pub fn get_mostro() -> Option<Mostro> {
+        MOSTRO_CONFIG.get().map(|config| config.mostro.clone())
    }

-    pub fn get_db() -> Database {
-        MOSTRO_CONFIG.get().unwrap().database.clone()
+    pub fn get_db() -> Option<Database> {
+        MOSTRO_CONFIG.get().map(|config| config.database.clone())
    }

-    pub fn get_nostr() -> Nostr {
-        MOSTRO_CONFIG.get().unwrap().nostr.clone()
+    pub fn get_nostr() -> Option<Nostr> {
+        MOSTRO_CONFIG.get().map(|config| config.nostr.clone())
    }
}

Alternatively, you could keep the current implementation but add a documentation comment explaining that these methods should only be called after init_global_settings has been called.

src/config/types.rs (4)

1-3: Fix redundant comments.

The file starts with two nearly identical comments. Consider consolidating them into a single comprehensive documentation comment to better describe the purpose and content of this file.

-// File with the types for the configuration settings
-// Initialize the types for the configuration settings
+/// This file defines the configuration data structures used throughout the application
+/// and implements conversions between them and the main Settings type.

6-7: Fix incorrect doc comment syntax.

The current format // / is not valid Rust documentation syntax. Use /// for documentation comments.

-// / Implement the TryFrom trait for each of the structs in Settings
-// / This allows you to convert from Settings to each of the structs directly.
+/// Implement the TryFrom trait for each of the structs in Settings
+/// This allows you to convert from Settings to each of the structs directly.

4-5: Consider adding more specific imports.

The code only imports Deserialize from serde, but in the future you might need other traits like Serialize. Consider using more explicit imports or a wildcard import if more serde traits might be needed.

-use serde::Deserialize;
+use serde::{Deserialize, Serialize};

Or alternatively:

-use serde::Deserialize;
+use serde::*;

45-58: Consider grouping related configuration fields.

The Mostro struct contains many fields with different purposes. Consider grouping related fields into nested structs for better organization and readability.

Example:

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Fees {
    pub fee: f64,
    pub max_routing_fee: f64,
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Limits {
    pub max_order_amount: u32,
    pub min_payment_amount: u32,
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct Mostro {
    pub fees: Fees,
    pub limits: Limits,
    pub expiration_hours: u32,
    // other fields...
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3684988 and f6990fc.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (16)
  • src/app.rs (1 hunks)
  • src/app/order.rs (1 hunks)
  • src/app/release.rs (1 hunks)
  • src/cli.rs (1 hunks)
  • src/cli/settings.rs (0 hunks)
  • src/config/mod.rs (1 hunks)
  • src/config/settings.rs (1 hunks)
  • src/config/types.rs (1 hunks)
  • src/config/util.rs (1 hunks)
  • src/db.rs (1 hunks)
  • src/lightning/invoice.rs (1 hunks)
  • src/lightning/mod.rs (1 hunks)
  • src/main.rs (2 hunks)
  • src/nip33.rs (1 hunks)
  • src/scheduler.rs (1 hunks)
  • src/util.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • src/cli/settings.rs
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/cli.rs (1)
src/config/util.rs (1)
  • init_default_dir (51-76)
src/main.rs (1)
src/config/settings.rs (1)
  • init_global_settings (18-20)
src/config/util.rs (3)
src/config/settings.rs (1)
  • new (23-50)
src/lightning/mod.rs (1)
  • new (41-55)
src/app.rs (1)
  • e (355-355)
src/config/mod.rs (2)
src/config/settings.rs (1)
  • init_global_settings (18-20)
src/config/util.rs (1)
  • init_default_dir (51-76)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests
🔇 Additional comments (22)
src/app/order.rs (1)

1-1: Import path updated to the new config module
The Settings struct is now correctly imported from crate::config::settings::Settings, matching the refactored configuration layout.

src/app/release.rs (1)

1-1: Import path updated to the new config module
The Settings struct import has been updated from cli::settings to config::settings, aligning with the modularized configuration system.

src/scheduler.rs (1)

3-3: Import path updated to the new config module
The import use crate::config::settings::Settings; correctly reflects the relocation of configuration logic into src/config.

src/lightning/invoice.rs (1)

1-1: Import path updated to the new config module
Switching the Settings import to crate::config::settings::Settings maintains consistency with the refactored settings organization.

src/db.rs (1)

21-21: Import path updated to the new config module
The Settings struct is now being imported from crate::config::settings::Settings, which matches the updated config module structure.

src/lightning/mod.rs (1)

3-3: Update import path for Settings
The import path for the Settings struct was correctly updated to point to the new config::settings module, aligning with the refactor of the Settings module into src/config.

src/main.rs (2)

4-4: Expose new config module at crate root
Adding pub mod config; makes the reorganized configuration submodules (settings, types, util) available at the crate root, which is the intended entry point for configuration management.


17-17: Update import path for init_global_settings and Settings
The imports have been updated to reflect the move of Settings and its initializer into config::settings. This maintains correct linkage and ensures configuration is initialized from the new module.

src/util.rs (1)

2-2: Update import path for Settings
The Settings struct import now references crate::config::settings::Settings, matching the new module hierarchy after refactoring.

src/app.rs (1)

36-36: Update import path for Settings
The import of Settings has been updated to crate::config::settings::Settings, aligning with the relocated configuration code.

src/nip33.rs (1)

1-1: Update import path for Settings
Correctly updated to import Settings from the new config::settings module, keeping configuration access consistent.

src/cli.rs (2)

1-5: Good refactoring of import paths

The import path has been correctly updated to use the new config::util module instead of the old cli::settings module, which aligns with the refactoring goal. The header comments are also useful for documenting the CLI's purpose.


34-42: Implementation looks correct after refactoring

The settings_init() function correctly uses the refactored init_default_dir function from the new location. The function's implementation remains unchanged which is good for maintaining compatibility.

src/config/mod.rs (2)

1-7: Well-structured module organization

The new module structure is clean and follows good separation of concerns by dividing configuration into logical components: settings, types, and utilities. The doc comments clearly explain the module's purpose.


8-11: Good use of re-exports for API simplicity

Re-exporting the key types and functions from submodules creates a clean public API. This approach makes the module easier to use while maintaining internal organization.

src/config/util.rs (3)

1-17: Well-documented utility module with clear imports

The module documentation clearly explains its purpose, and the imports are well-organized with appropriate platform-specific conditional compilation.


18-26: Platform-specific implementations for path handling

Good use of conditional compilation to handle platform differences in path separators. The code correctly handles Windows and Unix path conventions.


28-46: Path manipulation logic is well-implemented

The implementation correctly appends platform-specific trailing slashes to paths, with proper capacity allocation for the new string and fallback handling when the path has no filename component.

src/config/settings.rs (3)

1-15: Well-structured Settings implementation

The Settings struct is well-organized with clear domain separation into database, nostr, mostro, and lightning components. The imports correctly reference the types from the new module structure.


17-20: Simple global settings initialization

The global settings initialization function is concise and appropriately unwraps the result since this is a critical operation that should fail if unsuccessful.


22-50: Config loading implementation looks good

The new method correctly handles different run modes and properly uses the utility functions has_trailing_slash and add_trailing_slash. The configuration loading leverages the config crate with appropriate environment variable overrides.

src/config/types.rs (1)

60-66: LGTM: Clear macro usage.

The macro invocation is clear and correctly implements the TryFrom trait for all configuration structs.

Comment thread src/config/util.rs
Comment thread src/config/types.rs
Comment thread src/config/types.rs
Comment thread src/config/types.rs

@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: 2

🧹 Nitpick comments (4)
src/config/util.rs (3)

1-5: Prefer Rust-doc comments over free-form // / comments

The file-header comments start with a peculiar // / prefix, which is not picked up by rustdoc.
Switching to idiomatic //! (module-level) or /// (item-level) comments will allow the documentation to be rendered by cargo doc and IDEs.

-// / Utility functions for the config module
-// / This module provides utility functions for the config module.
-// / It includes functions to initialize the default settings directory and create a settings file from the template if it doesn't exist.
-// / It also includes functions to add a trailing slash to a path if it doesn't already have one.
+//! Utility helpers for the `config` module.
+//!
+//!  * `init_default_dir` – creates `~/.mostro` (or a user-supplied path) on first run.
+//!  * `has_trailing_slash` / `add_trailing_slash` – path helpers that behave
+//!    consistently on Unix and Windows.

18-26: Avoid hard-coding separators; lean on MAIN_SEPARATOR

b'\\' and b'/' work, but the intent is clearer (and one branch can be removed) if we compare against the platform’s canonical separator supplied by std lib.

-#[cfg(windows)]
-pub fn has_trailing_slash(p: &Path) -> bool {
-    let last = p.as_os_str().encode_wide().last();
-    last == Some(b'\\' as u16) || last == Some(b'/' as u16)
-}
+#[cfg(windows)]
+pub fn has_trailing_slash(p: &Path) -> bool {
+    use std::path::MAIN_SEPARATOR;
+    let last = p.as_os_str().encode_wide().last();
+    last == Some(MAIN_SEPARATOR as u16)
+}

If you still want to treat / as valid on Windows, add a comment explaining why.
This keeps the function short, removes the magic numbers and improves readability.


68-72: Use structured logging instead of println!

Elsewhere in the codebase you already employ tracing::info!.
Uniform logging makes it easier to redirect output and to keep stdout clean for TUI/CLI interactions.

-        println!(
+        tracing::info!(
             "Created settings file from template at {} for mostro - Edit it to configure your Mostro instance",
             config_path.display()
-        );
+        );
src/config/settings.rs (1)

64-82: Getter methods clone the entire sub-config each time

Cloning small structs is cheap, but if these grow (e.g., include TLS certs or big strings) it becomes wasteful.
Two options:

  1. Return &'static references (&'static Lightning) using MOSTRO_CONFIG.get().unwrap().
  2. Expose the entire Settings once and let callers borrow what they need.

Not urgent, but worth considering for larger deployments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 764750e and 4ffd769.

📒 Files selected for processing (2)
  • src/config/settings.rs (1 hunks)
  • src/config/util.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/config/util.rs (1)
Learnt from: arkanoider
PR: MostroP2P/mostro#481
File: src/config/util.rs:48-76
Timestamp: 2025-05-02T14:21:39.391Z
Learning: The `init_default_dir` function in Mostro intentionally exits the process (std::process::exit(0)) after creating a new configuration file so users can edit the configuration before restarting the application.
🧬 Code Graph Analysis (1)
src/config/util.rs (1)
src/config/settings.rs (1)
  • new (23-62)
🔇 Additional comments (3)
src/config/util.rs (1)

55-58: HOME is Unix-specific – fall back to a cross-platform solution

Windows often lacks the HOME env var; the canonical variables are USERPROFILE or HOMEDRIVE + HOMEPATH. Consider the dirs/home crate or manual fallback:

-        let home = std::env::var("HOME")
-            .map_err(|e| MostroInternalErr(ServiceError::EnvVarError(e.to_string())))?;
+        let home = std::env::var("HOME")
+            .or_else(|_| std::env::var("USERPROFILE"))
+            .map_err(|e| MostroInternalErr(ServiceError::EnvVarError(e.to_string())))?;

Failing to locate a home directory on Windows will currently crash the application even when a custom path is later supplied.
[ suggest_essential_refactor ]

src/config/settings.rs (2)

17-20: init_global_settings will panic if called twice

OnceCell::set (behind MOSTRO_CONFIG) panics on the second call.
If multiple integration tests (or a reload command) call init_global_settings, the process will abort. Consider returning a Result<(), ()> or simply ignoring subsequent calls:

-pub fn init_global_settings(s: Settings) {
-    MOSTRO_CONFIG.set(s).unwrap()
+pub fn init_global_settings(s: Settings) -> Result<(), Settings> {
+    MOSTRO_CONFIG.set(s)
 }

49-58: Database URL points to a directory, not a file

sqlite://{path}/ is not a valid Diesel/sqlx URL – it expects a file, e.g. sqlite://{path}/mostro.db.
Either append the DB filename here or document that downstream code appends it later.

-    .set_override(
-        "database.url",
-        format!("sqlite://{}", config_path.display()),
-    )?
+    .set_override(
+        "database.url",
+        format!("sqlite://{}/mostro.db", config_path.display()),
+    )?

Comment thread src/config/util.rs Outdated
Comment thread src/config/settings.rs Outdated
arkanoider added 3 commits May 9, 2025 21:25
- removed config dep and added more basic serde toml deserializer

- removing cloning of Mostro Settings params

- improve readability
- added some unit testing to config module to verify different parts of mostro settings struct

- improved readability and removed cloning in getter functions of Mostro settings.

@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: 5

🧹 Nitpick comments (3)
src/config/util.rs (3)

19-27: Use consistent logging approach

The create_template_file function uses println! for logging, while init_default_dir uses a mix of println! and structured logging (as suggested by the previous review comments). Consider using the same logging approach throughout the codebase for consistency.

-        println!("Settings file not found - creating default settings file");
+        tracing::info!("Settings file not found - creating default settings file");
         std::fs::write(file_name, include_bytes!("../../settings.tpl.toml"))
             .expect("Failed to write template file");
         // Print a message to the user
-        println!(
+        tracing::info!(
             "Created settings file from template at {} for Mostro",
             config_path.display()
         );
-        println!("Please edit the settings file with  your settings and run Mostro again");
+        tracing::info!("Please edit the settings file with your settings and run Mostro again");

27-27: Fix typo in message

There's an extra space in "with your settings".

-        println!("Please edit the settings file with  your settings and run Mostro again");
+        println!("Please edit the settings file with your settings and run Mostro again");

68-71: Inconsistent use of "mostro" vs "Mostro" in log messages

The message uses both lowercase "mostro" and uppercase "Mostro". Consider standardizing on one capitalization style for consistency.

-            "Created settings file from template at {} for mostro - Edit it to configure your Mostro instance",
+            "Created settings file from template at {} for Mostro - Edit it to configure your Mostro instance",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d82ae4a and ff4d350.

📒 Files selected for processing (4)
  • src/config/mod.rs (1 hunks)
  • src/config/settings.rs (1 hunks)
  • src/config/util.rs (1 hunks)
  • src/lightning/invoice.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/lightning/invoice.rs
  • src/config/mod.rs
  • src/config/settings.rs
🔇 Additional comments (1)
src/config/util.rs (1)

72-72: Process exit in library function is intentional

In accordance with the previous discussion in PR comments, the process exit is intentional as part of the application's configuration workflow. This is a valid pattern for CLI applications where users need to edit the config and restart.

Comment thread src/config/util.rs Outdated
Comment thread src/config/util.rs Outdated
Comment thread src/config/util.rs Outdated
Comment thread src/config/util.rs Outdated
Comment thread src/config/util.rs Outdated
arkanoider and others added 2 commits May 12, 2025 17:28
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
- removed some parts of init functions: now just a single init is called from main.

- added dirs crate to manage multiOs home folder
@arkanoider

Copy link
Copy Markdown
Collaborator Author

@coderabbitai please review

@coderabbitai

coderabbitai Bot commented May 12, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@arkanoider I've reviewed your "Settings refactor" PR and I'm impressed with the improvements you've made to the codebase organization. Here's my assessment:

What I like

  • Better organization: Breaking up the monolithic settings.rs into separate modules (settings.rs, types.rs, and util.rs) creates a much cleaner structure
  • Separation of concerns: Clear distinction between settings types, global state management, and utility functions
  • Module re-exports: The public re-exports in mod.rs make the API easier to use while maintaining internal organization
  • Testing improvements: The updated test approach using embedded TOML is cleaner

Suggestions

  • Consider adding more documentation to the new module structure, particularly explaining the relationship between the different components
  • The impl_try_from_settings! macro in types.rs is a nice touch for reducing boilerplate

Overall, this is a solid refactoring that improves code maintainability without changing core functionality. The code is now more modular, easier to navigate, and follows better Rust practices by separating different concerns into appropriate modules.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Tip

For best results, initiate chat on the files or code changes.

@arkanoider I've reviewed your "Settings refactor" PR and I'm impressed with the improvements you've made to the codebase organization. Here's my assessment:

What I like

* **Better organization**: Breaking up the monolithic `settings.rs` into separate modules (`settings.rs`, `types.rs`, and `util.rs`) creates a much cleaner structure

* **Separation of concerns**: Clear distinction between settings types, global state management, and utility functions

* **Module re-exports**: The public re-exports in `mod.rs` make the API easier to use while maintaining internal organization

* **Testing improvements**: The updated test approach using embedded TOML is cleaner

Suggestions

* Consider adding more documentation to the new module structure, particularly explaining the relationship between the different components

* The `impl_try_from_settings!` macro in `types.rs` is a nice touch for reducing boilerplate

Overall, this is a solid refactoring that improves code maintainability without changing core functionality. The code is now more modular, easier to navigate, and follows better Rust practices by separating different concerns into appropriate modules.

Let me know if you see something to improve!

@arkanoider arkanoider requested a review from grunch May 12, 2025 19:20

@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: 1

🧹 Nitpick comments (3)
src/config/util.rs (3)

34-38: Consider using tracing instead of println for consistency

You're using tracing::info! for the success message at the end of the function, but println! for the configuration template creation message. For consistency, consider using the tracing framework throughout.

-        println!(
-            "Created settings file from template at {} for Mostro - Edit it to configure your Mostro instance",
-            config_file_path.display()
-        );
+        tracing::info!(
+            "Created settings file from template at {} for Mostro - Edit it to configure your Mostro instance",
+            config_file_path.display()
+        );

45-46: Consider using a more specific error type for TOML parsing

The current implementation wraps the TOML parsing error as an IOError, which isn't technically accurate. Consider using a more specific error type for parsing errors to provide better diagnostics.

-    let mut settings: Settings = toml::from_str(&contents)
-        .map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?;
+    let mut settings: Settings = toml::from_str(&contents)
+        .map_err(|e| MostroInternalErr(ServiceError::ParseError(e.to_string())))?;

This assumes you have a ParseError variant in your ServiceError enum. If not, you might want to consider adding one.


49-49: Consider making the database filename configurable

The database filename "mostro.db" is hardcoded. Consider either:

  1. Making it configurable through the settings file
  2. Using a constant at the module level for better maintainability
+const DB_FILENAME: &str = "mostro.db";
+
// Later in the code:
-    settings.database.url = format!("sqlite://{}", settings_dir.join("mostro.db").display());
+    settings.database.url = format!("sqlite://{}", settings_dir.join(DB_FILENAME).display());
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9cdc560 and 70ae411.

📒 Files selected for processing (1)
  • src/config/util.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/config/util.rs (1)
Learnt from: arkanoider
PR: MostroP2P/mostro#481
File: src/config/util.rs:48-76
Timestamp: 2025-05-02T14:21:39.391Z
Learning: The `init_default_dir` function in Mostro intentionally exits the process (std::process::exit(0)) after creating a new configuration file so users can edit the configuration before restarting the application.
🧬 Code Graph Analysis (1)
src/config/util.rs (1)
src/config/settings.rs (1)
  • init_mostro_settings (15-19)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests
🔇 Additional comments (2)
src/config/util.rs (2)

38-38: Process exit is correctly implemented as intended

The intentional process exit after creating the configuration template is a deliberate design decision to allow users to edit the configuration before restarting the application, as noted in the retrieved learnings.


1-57: Good overall implementation of configuration management

This utility function correctly implements the configuration initialization workflow with proper error handling, cross-platform compatibility through the dirs crate, and appropriate process management. The code is well-documented and follows the intended design patterns for the application.

Comment thread src/config/util.rs Outdated
arkanoider and others added 2 commits May 12, 2025 21:49
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@arkanoider

Copy link
Copy Markdown
Collaborator Author

@grunch if you like this and we could merge i 'd like to do another improvement having the DB_POOL as an OnceLock too, removing many passage as parameter and using Arc to avoid cloning all pool in scheduler.
To avoid more confusional pr it would be nice to work on top of this when merged.

@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.

tACK

great job @arkanoider and @coderabbitai 🐰 😃

@grunch grunch merged commit 91328e7 into main May 14, 2025
2 checks passed
@grunch grunch deleted the settings-refactor branch May 14, 2025 12:44
This was referenced May 15, 2025
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