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: handles cancel request for already cancelled order & removes redundant check #393

Closed

Conversation

bilthon
Copy link
Contributor

@bilthon bilthon commented Nov 13, 2024

When receiving a cancel request for an already cancelled order mostro just fails silently. This adds a check for that and makes mostro reply with a cant-do action response.

There's also a small redundant check that was removed.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for order cancellations to prevent processing of already canceled orders.
    • Improved logic for cooperative cancellations, ensuring funds are returned to the seller when applicable.
  • Bug Fixes

    • Simplified condition checking for sell orders to streamline cancellation processes.
  • Documentation

    • Updated messaging for buyers and sellers during the cancellation process to provide clearer communication.

Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request focus on enhancing the cancellation process within the application. The cancel_action, cancel_add_invoice, and cancel_pay_hold_invoice functions have been updated to include additional checks for the order's status, preventing unnecessary processing for already canceled orders. The logic for cooperative cancellations has been refined to ensure proper fund handling and messaging. Overall, these modifications improve error handling and control flow related to order cancellations.

Changes

File Change Summary
src/app/cancel.rs - Updated cancel_action, cancel_add_invoice, and cancel_pay_hold_invoice to add status checks for cancellations.
- Simplified condition checking for sell orders.
- Enhanced cooperative cancellation logic for fund return and messaging.

Possibly related PRs

Suggested reviewers

  • grunch

🐇 In the land where orders roam,
Cancellations find their home.
With checks and balances in place,
Errors vanish without a trace.
Funds returned with care and cheer,
A smoother process, oh so near!
🌼


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.

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

🧹 Outside diff range and nitpick comments (1)
src/app/cancel.rs (1)

Line range hint 208-324: Consider refactoring common patterns in cancellation functions

The cancel_add_invoice and cancel_pay_hold_invoice functions share similar patterns for:

  • Handling hold invoices
  • Checking pubkeys and permissions
  • Updating order status
  • Sending messages
  • Logging

Consider extracting these common operations into helper functions to improve maintainability and reduce duplication.

Here's a suggested approach:

// Helper for handling hold invoices
async fn handle_hold_invoice(ln_client: &mut LndConnector, order: &Order) -> Result<()> {
    if let Some(hash) = &order.hash {
        ln_client.cancel_hold_invoice(hash).await?;
        info!("Order Id {}: Funds returned to seller", &order.id);
    }
    Ok(())
}

// Helper for checking permissions
async fn check_cancellation_permission(
    order: &Order,
    user_pubkey: &str,
    expected_role_pubkey: &str,
    request_id: Option<u64>,
    event_sender: &PublicKey,
) -> Result<()> {
    if user_pubkey != expected_role_pubkey {
        send_cant_do_msg(request_id, Some(order.id), None, event_sender).await;
        return Err(Error::msg("Unauthorized cancellation attempt"));
    }
    Ok(())
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 22d3a30 and 416bc63.

📒 Files selected for processing (1)
  • src/app/cancel.rs (2 hunks)
🔇 Additional comments (2)
src/app/cancel.rs (2)

43-56: LGTM: Well-implemented early return for cancelled orders

The new check properly handles already cancelled orders by checking all possible cancellation states and returning a clear error message to the user. This aligns well with the PR objective of improving the user experience.


91-91: Verify the safety of removing the redundant check

The condition has been simplified, but let's verify that removing the check doesn't introduce any edge cases.

✅ Verification successful

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

The simplified condition check is safe and correctly implemented

The codebase analysis confirms that WaitingBuyerInvoice status is consistently used in the expected flow:

  • It's set during sell order flow (src/flow.rs)
  • It's properly checked in add_invoice handling (src/app/add_invoice.rs)
  • It's monitored by the scheduler for timeouts (src/scheduler.rs)
  • The simplified condition in cancel.rs aligns with these usages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other occurrences of WaitingBuyerInvoice status checks
# to ensure we're not missing any important conditions

# Look for WaitingBuyerInvoice status checks in the codebase
rg "WaitingBuyerInvoice" -B 2 -A 2

# Look for status transitions to/from WaitingBuyerInvoice
ast-grep --pattern 'Status::WaitingBuyerInvoice'

Length of output: 3356

send_cant_do_msg(
request_id,
Some(order_id),
Some("Order already canceled".to_string()),
Copy link
Collaborator

@Catrya Catrya Nov 25, 2024

Choose a reason for hiding this comment

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

I think the idea is to send messages with just the action, without a text string inside, so that clients can interpret that action and show a message to users with the text they want and in the language they want.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh, sorry, I somehow missed this.

Yes, the idea is to replace custom messages with static codes that clients can map to localized, human-readable messages. However, I don’t think we have those static codes implemented yet, so for now, I decided to stick with the legacy method of using hard-coded, human-readable error messages.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Actually there are, there are no longer any actions with text strings in the code, all the ones that had them were replaced by one of these: https://github.com/MostroP2P/mostro-core/blob/c0cd7bbd263a303e7aab46588362839e836f0ac0/src/message.rs#L37C1-L84C2

Perhaps in this case just send the cant do msg, but if is needit something more descriptive, create it as a new action
But if don't do it for now, at least keep it pending to don't forget later, because since there are no more actions with text string we could forget that was added one recently and not change it later. My 2 cents

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh I see. The thing is, we can have many many different reasons for errors like CantDo. Expanding this set for every new specific error we want to convey to clients would result in an unbounded number of actions, making CantDo itself too vague in the process.

Instead I'd suggest keeping the action list concise and grouping all specific error messages into a new enum, which we could call ErrorMessage. What do you say @grunch?

Copy link
Member

Choose a reason for hiding this comment

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

Sorry I missed this response, yes I think it makes sense @bilthon, if you want you want to do it please go first to mostro-core and then change it here

Copy link
Member

Choose a reason for hiding this comment

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

Here the proposal for CantDoReason error handling

MostroP2P/mostro-core#69

And here the merged PR

MostroP2P/mostro-core#70

It is already working on mostro-core 0.6.15

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.

3 participants