Skip to content

Feat: issue #427 avoid multiple pending orders#444

Merged
grunch merged 5 commits into
developfrom
feature-avoid-multiple-pending-orders
Feb 26, 2025
Merged

Feat: issue #427 avoid multiple pending orders#444
grunch merged 5 commits into
developfrom
feature-avoid-multiple-pending-orders

Conversation

@arkanoider

@arkanoider arkanoider commented Feb 18, 2025

Copy link
Copy Markdown
Collaborator

Implementation of #427 :
User should just have one waiting-payment or waiting-buyer-invoice order pending when taking orders ( sell or buy ), in case of other pending orders they receive a CantDo message ( maybe we can add a more meaningful one )

Summary by CodeRabbit

  • New Features
    • Implemented additional pending order validations for buy and sell actions to prevent duplicate processing.
    • Orders will now be halted with an immediate error notification when a pending order is detected, ensuring accurate order management.
    • Updated the mostro-core dependency to version 0.6.28, potentially enhancing library functionality.

…ayment or waiting-buyer-invoice order pending
@coderabbitai

coderabbitai Bot commented Feb 18, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce new checks for pending orders in both the buy and sell actions of the application. In the take_buy_action and take_sell_action functions, asynchronous helper functions from the database module are called to verify if there are any pending orders. If a pending order is detected, the functions return an error immediately. Additionally, two new functions, seller_has_pending_order and buyer_has_pending_order, have been added to the database module to perform these checks, incorporating improved error handling and key validation.

Changes

File(s) Change Summary
src/app/take_buy.rs, src/app/take_sell.rs Modified control flow in buy and sell actions by adding conditional checks (using seller_has_pending_order/buyer_has_pending_order) to halt processing if pending orders exist.
src/db.rs Added two asynchronous functions, seller_has_pending_order and buyer_has_pending_order, which perform database lookups for pending orders and include error handling.
Cargo.toml Updated the version of the mostro-core dependency from 0.6.26 to 0.6.28.

Possibly related PRs

  • Refactoring code removing unwraps() #449: The changes in this PR are related to the modifications in the take_sell_action function, as both involve adding checks for pending orders and modifying control flow based on those checks.
  • Code refactoring removing old actions #409: The changes in this PR relate to the modifications in the take_buy_action and take_sell_action functions, which both implement new error handling logic using send_cant_do_msg.
  • Refactoring #431: The changes in this PR are related to the modifications in the take_buy_action and take_sell_action functions, which both involve adding checks for pending orders and returning specific error types.

Suggested reviewers

  • grunch

Poem

I hopped through lines of code with glee,
Checking orders as busy as a bee.
If pending orders are found, I quickly retreat,
Leaving a trail of errors so neat.
In the garden of functions where logic is true,
I nibble on bugs and celebrate something new.
🐇 Happy hops and even happier code to you!


📜 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 2f545b1 and 291becb.

📒 Files selected for processing (2)
  • src/app/take_buy.rs (2 hunks)
  • src/app/take_sell.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/app/take_buy.rs
  • src/app/take_sell.rs

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.

@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

♻️ Duplicate comments (1)
src/app/take_sell.rs (1)

54-56: 🛠️ Refactor suggestion

Enhance error message to provide more meaningful feedback.

The current error message InvalidAction is too generic and doesn't help users understand why their action was rejected. Consider providing a more descriptive error message that explains the pending order restriction.

🧹 Nitpick comments (2)
src/app/take_sell.rs (1)

53-53: Fix incorrect comment.

The comment says "Check if the seller has a pending order" but the function name is buyer_has_pending_order. This is confusing and should be corrected.

Apply this diff to fix the comment:

-    // Check if the seller has a pending order
+    // Check if the buyer has a pending order
src/db.rs (1)

456-508: Reduce code duplication by extracting common logic.

The seller_has_pending_order and buyer_has_pending_order functions share identical structure and error handling. Consider refactoring to reduce duplication.

Apply this diff to extract common logic:

+/// Check if a user has a pending order in the database with status waiting-payment or waiting-buyer-invoice
+async fn has_pending_order(
+    pool: &SqlitePool,
+    pubkey: String,
+    column_name: &str,
+) -> anyhow::Result<bool, MostroError> {
+    // Validate public key format (32-bytes hex)
+    if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 {
+        return Err(MostroCantDo(CantDoReason::InvalidPubkey));
+    }
+
+    let mut conn = pool
+        .acquire()
+        .await
+        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
+    let rows_affected = sqlx::query(&format!(
+        r#"
+            SELECT EXISTS (SELECT 1 FROM orders WHERE {} = ?1 AND (status = 'waiting-payment' OR status = 'waiting-buyer-invoice'))
+        "#,
+        column_name
+    ))
+    .bind(pubkey)
+    .map(|row: SqliteRow| row.get(0))
+    .fetch_one(&mut conn)
+    .await.map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
+
+    Ok(rows_affected)
+}
+
 /// Check if the seller has a pending order in the database with status waiting-payment or waiting-buyer-invoice
 pub async fn seller_has_pending_order(
     pool: &SqlitePool,
     pubkey: String,
 ) -> anyhow::Result<bool, MostroError> {
-    // Validate public key format (32-bytes hex)
-    if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 {
-        return Err(MostroCantDo(CantDoReason::InvalidPubkey));
-    }
-
-    let mut conn = pool
-        .acquire()
-        .await
-        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
-    let rows_affected = sqlx::query(
-        r#"
-            SELECT EXISTS (SELECT 1 FROM orders WHERE master_seller_pubkey = ?1 AND (status = 'waiting-payment' OR status = 'waiting-buyer-invoice'))
-        "#,
-    )
-    .bind(pubkey)
-    .map(|row: SqliteRow| row.get(0))
-    .fetch_one(&mut conn)
-    .await.map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
-
-    Ok(rows_affected)
+    has_pending_order(pool, pubkey, "master_seller_pubkey").await
 }
 
 /// Check if the buyer has a pending order in the database with status waiting-payment or waiting-buyer-invoice
 pub async fn buyer_has_pending_order(
     pool: &SqlitePool,
     pubkey: String,
 ) -> anyhow::Result<bool, MostroError> {
-    // Validate public key format (32-bytes hex)
-    if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 {
-        return Err(MostroCantDo(CantDoReason::InvalidPubkey));
-    }
-
-    let mut conn = pool
-        .acquire()
-        .await
-        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
-    let rows_affected = sqlx::query(
-        r#"
-            SELECT EXISTS (SELECT 1 FROM orders WHERE master_buyer_pubkey = ?1 AND (status = 'waiting-payment' OR status = 'waiting-buyer-invoice'))
-        "#,
-    )
-    .bind(pubkey)
-    .map(|row: SqliteRow| row.get(0))
-    .fetch_one(&mut conn)
-    .await.map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
-
-    Ok(rows_affected)
+    has_pending_order(pool, pubkey, "master_buyer_pubkey").await
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 825ba61 and d98d23b.

📒 Files selected for processing (3)
  • src/app/take_buy.rs (2 hunks)
  • src/app/take_sell.rs (2 hunks)
  • src/db.rs (2 hunks)

Comment thread src/app/take_buy.rs

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

Hi @arkanoider Good job. However, I found 2 cases where it can be improved because it shouldn't work like this.

  • A creates an order
  • B takes A's order but doesn't respond
  • A tries to take C's order and Mostro doesn't let him (A doesn't know that his order was taken because the taker doesn't continue)

This could be used by a malicious user to block other users from taking orders

How it should work is that A could take an order even if it is in status waiting-buyer-invoice or waiting-payment if it is the taker's turn

  • A takes an order from B and does his part
  • B doesn't respond and leaves A waiting
  • A tries to take an order from C and Mostro doesn't let him

Mostro should allow A to take another order if he has already done his part

@arkanoider

Copy link
Copy Markdown
Collaborator Author

@Catrya need some more refinement, you're right. Have to check how to manage better all the possible cases.

@arkanoider

Copy link
Copy Markdown
Collaborator Author
  • A creates an order
  • B takes A's order but doesn't respond
  • A tries to take C's order and Mostro doesn't let him (A doesn't know that his order was taken because the taker doesn't continue showing that he doesn't let A know to do his part)

This could be used by a malicious user to block other users from taking orders

How it should work is that A could take an order even if it is in status waiting-buyer-invoice or waiting-payment if it is the taker's turn

So for case 1 @Catrya , just for my mental recap:

-- A creates a sell order
-- B Takes it and then he stops here ( order is waiting buyer invoice )
-- A now is blocked to take another order.

This is the sequence for case 1?

@Catrya

Catrya commented Feb 19, 2025

Copy link
Copy Markdown
Member
  • A creates an order
  • B takes A's order but doesn't respond
  • A tries to take C's order and Mostro doesn't let him (A doesn't know that his order was taken because the taker doesn't continue showing that he doesn't let A know to do his part)

This could be used by a malicious user to block other users from taking orders
How it should work is that A could take an order even if it is in status waiting-buyer-invoice or waiting-payment if it is the taker's turn

So for case 1 @Catrya , just for my mental recap:

-- A creates a sell order -- B Takes it and then he stops here ( order is waiting buyer invoice ) -- A now is blocked to take another order.

This is the sequence for case 1?

Yes, but Mostro should let A take another order

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Yes, but Mostro should let A take another order

I tested quickly and with a clean db with two sell orders from A and two from B and B was able to take a new order correctly after A took one. But I could be totally wrong @Catrya please do a round on your side again when you can.

@Catrya

Catrya commented Feb 19, 2025

Copy link
Copy Markdown
Member

Yes, but Mostro should let A take another order

I tested quickly and with a clean db with two sell orders from A and two from B and B was able to take a new order correctly after A took one. But I could be totally wrong @Catrya please do a round on your side again when you can.

You're right, I just checked again and it's possible.
I don't know what I did wrong yesterday. I'll try again more carefully tomorrow morning.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Yes, but Mostro should let A take another order

I tested quickly and with a clean db with two sell orders from A and two from B and B was able to take a new order correctly after A took one. But I could be totally wrong @Catrya please do a round on your side again when you can.

You're right, I just checked again and it's possible.
I don't know what I did wrong yesterday. I'll try again more carefully tomorrow morning.

maybe some edge cases depending on db situation, do your test meanwhile i will fix event ratings issue.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Will try to do another round of testing on this tonite or tomorrow morning @Catrya . Let me know if you found wrong behaviour of this PR.

@Catrya

Catrya commented Feb 21, 2025

Copy link
Copy Markdown
Member

Will try to do another round of testing on this tonite or tomorrow morning @Catrya . Let me know if you found wrong behaviour of this PR.

Hi @arkanoider this case have to be fixed:

  • A takes an order from B and does his part
  • B doesn't respond and leaves A waiting
  • A tries to take an order from C and Mostro doesn't let him
    Mostro should allow A to take another order if he has already done his part

I tested again and the first case that I mentioned worked fine as I told you later.
But the second one didn't, that one hasn't been fixed yet

@arkanoider

arkanoider commented Feb 21, 2025

Copy link
Copy Markdown
Collaborator Author

Will try to do another round of testing on this tonite or tomorrow morning @Catrya . Let me know if you found wrong behaviour of this PR.

Hi @arkanoider this case have to be fixed:

  • A takes an order from B and does his part
  • B doesn't respond and leaves A waiting
  • A tries to take an order from C and Mostro doesn't let him
    Mostro should allow A to take another order if he has already done his part

I tested again and the first case that I mentioned worked fine as I told you later.
But the second one didn't, that one hasn't been fixed yet

confirm i did not retest second case, will be on it tonight or tomorrow.

@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 (1)
src/db.rs (1)

456-508: Consider refactoring to reduce code duplication.

The seller_has_pending_order and buyer_has_pending_order functions are nearly identical, differing only in the column name and documentation. Consider extracting the common logic into a shared function.

Here's a suggested refactor:

async fn has_pending_order(
    pool: &SqlitePool,
    pubkey: String,
    role_column: &str,
) -> anyhow::Result<bool, MostroError> {
    // Validate public key format (32-bytes hex)
    if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 {
        return Err(MostroCantDo(CantDoReason::InvalidPubkey));
    }

    let mut conn = pool
        .acquire()
        .await
        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
    
    let query = format!(
        r#"
            SELECT EXISTS (
                SELECT 1 
                FROM orders 
                WHERE {} = ?1 
                AND (status = 'waiting-payment' OR status = 'waiting-buyer-invoice')
            )
        "#,
        role_column
    );
    
    let rows_affected = sqlx::query(&query)
        .bind(pubkey)
        .map(|row: SqliteRow| row.get(0))
        .fetch_one(&mut conn)
        .await
        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;

    Ok(rows_affected)
}

pub async fn seller_has_pending_order(
    pool: &SqlitePool,
    pubkey: String,
) -> anyhow::Result<bool, MostroError> {
    has_pending_order(pool, pubkey, "master_seller_pubkey").await
}

pub async fn buyer_has_pending_order(
    pool: &SqlitePool,
    pubkey: String,
) -> anyhow::Result<bool, MostroError> {
    has_pending_order(pool, pubkey, "master_buyer_pubkey").await
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d98d23b and bb57996.

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

3-7: LGTM! Error handling imports are well-organized.

The new imports from mostro_core::error are appropriately added to support the enhanced error handling in the new functions.


456-508:

Details

❓ Verification inconclusive

Consider edge cases in order status checks.

Based on the PR discussion, the current implementation might incorrectly block users who have completed their part of the transaction. For example, if User A creates an order and User B takes it but doesn't respond, User A would be blocked from taking new orders.

Consider adding additional checks to allow users to take new orders if they've completed their part of the transaction (e.g., seller has provided invoice, buyer has made payment).

Let's verify the current order status flow:


🏁 Script executed:

#!/bin/bash
# Description: Check the order status flow in the codebase
# Look for order status transitions to understand the complete flow

rg -A 5 "status = " --type rust

Length of output: 7937


Attention: Revisit Pending Order Status Conditions

The current implementation in src/db.rs relies solely on checking for orders with status 'waiting-payment' (for sellers) and 'waiting-buyer-invoice' (for buyers). However, the order status flow throughout the codebase (e.g., in src/flow.rs and src/scheduler.rs) suggests that there are additional transitions that mark an order as active or otherwise progressing toward completion. This raises the risk that a user might be incorrectly blocked—especially in edge cases where part of the transaction has already been completed (for example, when the seller has provided the invoice or the buyer has made the payment), but the order still briefly holds one of these statuses.

Recommendations:

  • Seller Check: Reassess whether the condition status = 'waiting-payment' fully represents a pending seller order. Consider incorporating a check for orders that have moved past the waiting stage.
  • Buyer Check: Similarly, confirm that matching on status = 'waiting-buyer-invoice' is sufficient. Evaluate if there are states (or additional fields) that indicate the buyer has already taken action.
  • Overall Status Flow: Verify that order status transitions (as seen in src/flow.rs and /src/scheduler.rs) align with the intended logic. Adjust these functions to allow new orders when an order has reached a completed or non-blocking state.

It would be beneficial to review the full order lifecycle to ensure this pending order logic correctly differentiates between truly active pending orders and those that can be considered completed or stale.

Comment thread src/db.rs Outdated
Comment thread src/db.rs Outdated
@arkanoider

arkanoider commented Feb 22, 2025

Copy link
Copy Markdown
Collaborator Author

Ok @Catrya @grunch

i did some tests and seems working with the right logic now, do a round on your side if you see still some edge cases.

Note:

left invalidAction as error until we merge new mostro-core with PendingOrdersExists new error.

@arkanoider arkanoider force-pushed the feature-avoid-multiple-pending-orders branch from 66f8e05 to 9aed9b7 Compare February 22, 2025 16:06
@grunch grunch changed the title Feat: issue #427 implementation Feat: issue #427 feature-avoid-multiple-pending-orders Feb 23, 2025
@grunch grunch changed the title Feat: issue #427 feature-avoid-multiple-pending-orders Feat: issue #427 avoid multiple pending orders Feb 23, 2025
@grunch

grunch commented Feb 23, 2025

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Feb 23, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Catrya

Catrya commented Feb 24, 2025

Copy link
Copy Markdown
Member
  • A takes an order from B and does his part
  • B doesn't respond and leaves A waiting
  • A tries to take an order from C and Mostro doesn't let him
    Mostro should allow A to take another order if he has already done his part

Hi @arkanoider I still find this error in my side

@Catrya

Catrya commented Feb 24, 2025

Copy link
Copy Markdown
Member

tACK @grunch @arkanoider

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Conflicts are due to latest mostro-core in toml. Let me know if I can resolve and merge @grunch ...

@grunch

grunch commented Feb 25, 2025

Copy link
Copy Markdown
Member

Conflicts are due to latest mostro-core in toml. Let me know if I can resolve and merge @grunch ...

please solve those conflicts, we can't merge like this

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Conflicts are due to latest mostro-core in toml. Let me know if I can resolve and merge @grunch ...

please solve those conflicts, we can't merge like this

Done

@Catrya

Catrya commented Feb 25, 2025

Copy link
Copy Markdown
Member

tACK again @arkanoider @grunch

@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 23d556d into develop Feb 26, 2025
@grunch grunch deleted the feature-avoid-multiple-pending-orders branch February 26, 2025 14:05
This was referenced Mar 2, 2025
@coderabbitai coderabbitai Bot mentioned this pull request May 6, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Jul 24, 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.

3 participants