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

Network specific storage paths #149

Merged
merged 4 commits into from
Jan 16, 2025
Merged

Network specific storage paths #149

merged 4 commits into from
Jan 16, 2025

Conversation

danielnordh
Copy link
Contributor

@danielnordh danielnordh commented Jan 16, 2025

This PR introduces network specific storage paths, to enable switching networks in the future.
It also uses a separate sub-directory for logs.
Broken out from #145

Summary by CodeRabbit

  • Improvements
    • Enhanced directory organization for Lightning node storage and logging
    • Improved error handling during node initialization

Copy link

coderabbitai bot commented Jan 16, 2025

Warning

Rate limit exceeded

@danielnordh has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 30 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 b45ebd6 and bd003d8.

📒 Files selected for processing (1)
  • LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (1 hunks)

Walkthrough

The changes in the LightningNodeService.swift file involve significant updates to the initialization process of the LightningNodeService class. The storageDirPath and logDirPath properties have been modified to utilize a new directory structure that incorporates the network description, improving file organization. Additionally, the error handling during the initialization of the ldkNode has been enhanced by replacing forced unwrapping with a safer error management approach.

Changes

File Change Summary
LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift - Updated storageDirPath and logDirPath to utilize network-specific directories
- Enhanced error handling during ldkNode initialization by replacing forced unwrapping with safer practices

Poem

🐰 A Lightning Node, neat and bright,
Paths now sorted with network's might
No more crashes, errors tamed
Directories carefully framed
Code hopping with safer delight! 🌩️


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

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

🔭 Outside diff range comments (2)
LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (2)

Line range hint 102-102: Remove forced unwrap in node initialization.

The forced unwrap (try!) in node initialization is dangerous and could crash the app. This is particularly risky as node initialization could fail for various reasons (e.g., file system issues, permission problems, network conflicts).

Replace with proper error handling:

-        let ldkNode = try! nodeBuilder.build()  // Handle error instead of "!"
+        do {
+            self.ldkNode = try nodeBuilder.build()
+        } catch {
+            logger.error("Failed to initialize Lightning node: \(error)")
+            // Consider implementing a recovery strategy or user notification
+            throw error
+        }
-        self.ldkNode = ldkNode

Also, consider adding a custom error type to handle specific initialization failures:

enum LightningNodeError: Error {
    case initializationFailed(underlying: Error)
    case directoryCreationFailed(path: String)
}

Network switching cleanup needs to be more targeted

The current implementation of deleteAllContentsInDocumentsDirectory() performs a complete wipe of the documents directory, which could unintentionally delete data from other networks. Consider implementing network-specific cleanup by:

  • Only deleting the specific network directory path: documents/<network>/
  • Adding a deleteNetworkDirectory(network: Network) method for targeted cleanup
🔗 Analysis chain

Line range hint 1-102: Verify network switching cleanup process.

While the network-specific paths provide good isolation, we should verify the cleanup process during network switching to prevent data leaks or corruption.

Let's check for potential issues:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for network-specific directory handling and potential cleanup issues

# Check for any hardcoded network paths that might bypass the new network-specific structure
rg -i "documents.*/(bitcoin|testnet|signet|regtest)" --type swift

# Look for any file operations that might not respect network isolation
ast-grep --pattern 'FileManager.default.$_($$$)' --lang swift

# Check for proper cleanup in deleteDocuments method
ast-grep --pattern 'func deleteDocuments() {
  $$$
}' --lang swift

Length of output: 661


Script:

#!/bin/bash
# Check the implementation of deleteAllContentsInDocumentsDirectory

# Look for the extension implementation
rg -A 10 "deleteAllContentsInDocumentsDirectory" --type swift

# Check for any other cleanup related methods
ast-grep --pattern 'extension FileManager {
  $$$
}' --lang swift

Length of output: 1816

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a75124a and 6167c87.

📒 Files selected for processing (1)
  • LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (1 hunks)

Comment on lines 33 to 38
config.storageDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
"/\(network.description)/"
)
config.logDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
"/\(network.description)/"
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure proper directory handling for network-specific paths.

While the network-specific paths align with the PR objective, there are a few improvements needed:

  1. The code should ensure directories exist before use
  2. Use URL path components instead of string concatenation for robust path handling
  3. Consider data migration strategy for network switching

Here's a safer implementation:

-        config.storageDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
-            "/\(network.description)/"
-        )
-        config.logDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
-            "/\(network.description)/"
-        )
+        let documentsPath = FileManager.default.getDocumentsDirectoryPath()
+        let networkPath = URL(fileURLWithPath: documentsPath)
+            .appendingPathComponent(network.description)
+            .path
+        
+        try? FileManager.default.createDirectory(
+            atPath: networkPath,
+            withIntermediateDirectories: true
+        )
+        
+        config.storageDirPath = networkPath
+        config.logDirPath = networkPath
📝 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
config.storageDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
"/\(network.description)/"
)
config.logDirPath = FileManager.default.getDocumentsDirectoryPath().appending(
"/\(network.description)/"
)
let documentsPath = FileManager.default.getDocumentsDirectoryPath()
let networkPath = URL(fileURLWithPath: documentsPath)
.appendingPathComponent(network.description)
.path
try? FileManager.default.createDirectory(
atPath: networkPath,
withIntermediateDirectories: true
)
config.storageDirPath = networkPath
config.logDirPath = networkPath

Copy link

@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

🧹 Nitpick comments (1)
LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (1)

31-44: Enhance error handling for directory creation.

While the implementation correctly uses URL path components and creates network-specific directories, the error handling could be improved:

  1. Silent error handling with try? could mask directory creation issues
  2. No validation that the directory exists before use
  3. Missing error logging for directory creation failures

Consider this safer implementation:

 let documentsPath = FileManager.default.getDocumentsDirectoryPath()
 let networkPath = URL(fileURLWithPath: documentsPath)
     .appendingPathComponent(network.description)
     .path

-try? FileManager.default.createDirectory(
-    atPath: networkPath,
-    withIntermediateDirectories: true
-)
+do {
+    try FileManager.default.createDirectory(
+        atPath: networkPath,
+        withIntermediateDirectories: true
+    )
+    
+    guard FileManager.default.fileExists(atPath: networkPath) else {
+        throw NSError(
+            domain: "LightningNodeService",
+            code: -1,
+            userInfo: [NSLocalizedDescriptionKey: "Failed to create network directory"]
+        )
+    }
+    
+    config.storageDirPath = networkPath
+    config.logDirPath = networkPath
+} catch {
+    os_log(
+        .error,
+        "Failed to create network directory: %{public}@",
+        error.localizedDescription
+    )
+    throw error
+}
-config.storageDirPath = networkPath
-config.logDirPath = networkPath
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6167c87 and b45ebd6.

📒 Files selected for processing (1)
  • LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (1 hunks)
🔇 Additional comments (1)
LDKNodeMonday/Service/Lightning Service/LightningNodeService.swift (1)

Line range hint 102-102: Consider improving error handling in node initialization in a future PR.

The current implementation uses forced unwrapping (try!) for node initialization which could lead to runtime crashes. While this is outside the scope of the current PR's network-specific storage paths objective, consider addressing this in a future PR.

Run this script to assess the impact of potential initialization failures:

@reez reez merged commit 84fd4f7 into reez:main Jan 16, 2025
1 check passed
@reez
Copy link
Owner

reez commented Jan 16, 2025

Great!

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