Skip to content

Sends an updated order status as a reply to the add-invoice action#464

Merged
grunch merged 1 commit into
MostroP2P:developfrom
bilthon:fix_sends_updated_order_status
Mar 25, 2025
Merged

Sends an updated order status as a reply to the add-invoice action#464
grunch merged 1 commit into
MostroP2P:developfrom
bilthon:fix_sends_updated_order_status

Conversation

@bilthon

@bilthon bilthon commented Mar 11, 2025

Copy link
Copy Markdown
Contributor

In the buyer-as-maker scenario, when the buyer sends an add-invoice message, the order transitions to the active state. However, we were cloning the order before updating the database, causing the reply to contain an outdated order state.

Since the client may rely on the reply to update the order’s state, it’s crucial to ensure the information is up to date. This PR ensures that the database is updated before responding, so the client always receives the most current order state.

Summary by CodeRabbit

  • Refactor
    • Revised invoice processing to improve error handling and implement fallback logic.
  • Bug Fixes
    • Updated confirmation notifications so that sellers and buyers reliably receive the correct order status.

@coderabbitai

coderabbitai Bot commented Mar 11, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes restructure the add_invoice_action function by replacing direct update logic with a match-based error handling mechanism. The updated flow now matches the result of update_order_event to either process a successful update—by cloning the order, updating the database, and sending confirmation messages using the SmallOrder representation—or fall back to the original order upon failure. No modifications were made to exported or public entities.

Changes

File Change Summary
src/app/add_invoice.rs Refactored add_invoice_action: switched from direct updates to a match-based error handling mechanism, cloned and updated the order in the DB, and revised messaging to use active_order with a SmallOrder payload representation.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant A as add_invoice_action
    participant O as OrderEventUpdater
    participant D as Database
    participant M as MessagingService

    C->>A: Invoke add_invoice_action
    A->>O: update_order_event(order)
    alt Update Successful
        O-->>A: Return updated order event
        A->>D: Clone order & update database
        A->>M: Send confirmation messages using active_order (SmallOrder)
    else Update Fails
        O-->>A: Return error result
        A->>M: Use fallback original order for confirmation
    end
Loading

Possibly related PRs

Suggested reviewers

  • arkanoider
  • grunch

Poem

Hopping through the code with delight,
I fixed the bugs both day and night.
Match and clone, the logic's tight—
Order updates now shine so bright!
A rabbit's cheer in every byte!
🐰✨

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 78e1dcc and 3eb2e48.

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

87-89: Good job switching to active_order.
Using active_order ensures that the client receives the most up-to-date and correct order state after the database update. This aligns with the PR objective of preventing outdated status replies.


97-99: Verify fallback scenario for unsuccessful updates.
If update_order_event fails, this code still sends success messages (Action::HoldInvoicePaymentAccepted) based on the original order (order.clone()). Please confirm if this behavior is intentional, as it might mislead clients into believing the update to Status::Active was successful.

Comment thread src/app/add_invoice.rs
Comment on lines +73 to +82
let active_order = match update_order_event(my_keys, Status::Active, &order).await {
Ok(updated_order) => {
// Update in database
updated_order.clone().update(pool).await.map_err(|cause| {
MostroInternalErr(ServiceError::DbAccessError(cause.to_string()))
})?;
updated_order
},
Err(_) => order.clone(), // Fallback to original order if update fails
};

@coderabbitai coderabbitai Bot Mar 11, 2025

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.

🛠️ Refactor suggestion

Resolve partial update concerns.
If update_order_event succeeds but the subsequent .update(pool) call fails, your system ends up in a partially updated state. Consider wrapping these operations in a database transaction to ensure that both the event update and the database update happen atomically. This prevents inconsistencies when one operation succeeds and the other fails.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The suggestion of wrapping these operations in a database transaction seems to suggest rabbit thinks these are both database operations. But from what I can gather update_order_event does not perform a database operation, it just updates the order in memory. So I'm not sure how relevant this suggestion is.

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Let's find the implementation of update_order_event
rg -A 10 -B 5 "fn update_order_event" --type rust

Length of output: 738


🏁 Script executed:

#!/bin/bash
# Let's see the full implementation of update_order_event
rg -A 30 -B 5 "fn update_order_event" --type rust

Length of output: 1638


@bilthon You're absolutely right. After examining the implementation of update_order_event, I see that it only performs in-memory updates to the order object and sends a Nostr event - it doesn't actually perform any database operations. The database update happens afterward with the .update(pool) call.

My suggestion about using a transaction wasn't appropriate here since we're dealing with a network operation followed by a database operation, not two database operations. Thank you for pointing this out!


✏️ Learnings added
Learnt from: bilthon
PR: MostroP2P/mostro#464
File: src/app/add_invoice.rs:73-82
Timestamp: 2025-03-11T23:26:33.652Z
Learning: In the Mostro codebase, the `update_order_event` function does not perform database operations - it only updates an order in memory and sends a Nostr event. The actual database update happens separately when calling `.update(pool)` afterward.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good pick @bilthon I think you're right! I just would make a small cosmetics doing this...

I would just make use of oneliner with ? since update_order_event is returning the Result we need just with question mark operator. In case update_order_event fails for internal reason we are just logging to mostrod the issue.

...

if order.preimage.is_some() {
        // We publish a new replaceable kind nostr event with the status updated
        // and update on local database the status and new event id
        let active_order = update_order_event(my_keys, Status::Active, &order).await?;
        active_order
            .clone()
            .update(pool)
            .await
            .map_err(|cause| MostroInternalErr(ServiceError::DbAccessError(cause.to_string())))?;

        // We send a confirmation message to seller
        enqueue_order_msg(
            None,
            Some(order.clone().id),
            Action::BuyerTookOrder,
            Some(Payload::Order(SmallOrder::from(active_order.clone()))),
            seller_pubkey,
            None,
        )
        .await;
        // We send a message to buyer saying seller paid
        enqueue_order_msg(
            msg.get_inner_message_kind().request_id,
            Some(order.clone().id),
            Action::HoldInvoicePaymentAccepted,
            Some(Payload::Order(SmallOrder::from(active_order.clone()))),
            buyer_pubkey,
            None,
        )
        .await;
    } else if let Err(cause) = show_hold_invoice(
        my_keys,
        None,
        &buyer_pubkey,
        &seller_pubkey,
        order,
        msg.get_inner_message_kind().request_id,
    )
    .await
    {
        return Err(MostroInternalErr(ServiceError::HoldInvoiceError(
            cause.to_string(),
        )));
    }
    Ok(())
}

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@arkanoider arkanoider requested a review from grunch March 24, 2025 08:51
@grunch grunch requested a review from Catrya March 24, 2025 17:19

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

I tested it and it works fine, for me could be merge.
However review @arkanoider's recommendations @grunch

@arkanoider

Copy link
Copy Markdown
Collaborator

I tested it and it works fine, for me could be merge.
However review @arkanoider's recommendations @grunch

I tested it too, it works and it makes sense 8n my opinion. Let's wait @grunch opinion.

@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 6972138 into MostroP2P:develop Mar 25, 2025
arkanoider added a commit that referenced this pull request Apr 30, 2025
* 📝 Add docstrings to `feature-full-privacy-mode-checks` (#455)

* add feature to check correctly if order is full privacy or normal

* 📝 Add docstrings to `feature-full-privacy-mode-checks`

Docstrings generation was requested by @arkanoider.

* #454 (comment)

The following files were modified:

* `src/app/order.rs`
* `src/util.rs`

---------

Co-authored-by: arkanoider <github.913zc@simplelogin.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: arkanoider <113362043+arkanoider@users.noreply.github.com>

* Fix network in order event (#452)

Now in orers event 38383 the network that comes out is the correct one

* Feature anyhow removal (#459)

* remove of anyhow dependency start

* removed anyhow dependecy

* remove patch from cargo.toml

* Update mostro-core version

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* Feature disputes (#463)

* Feature: dispute fix for new logic

* fix for coop cancel case

* Add logic for info message about dispute for solver

* first working dispute info message for admin after taking disputes

* added fields to dispute info message for solver

* removed some probably useless and refactored a bit admin-take-dispute function

* clippy suggestion

* other cosmetics to admin take file

* some other cosmetics on admin-take-dispute file

* fix on admin-take

* Update admin_take_dispute.rs

* fixed a wrong search of order id in admin take file@

* Fix: added correct check to add solver from admin cli

* fix: wrong check on admin cancel

* Fix initiator pubkey: now is the trade key of initiator not identity

* quick fix for full privacy orders

* new logic with mixed full privacy - regular reputation mode

* Update cargo toml to compile with version 0.6.32 of mostro-core - this is in preparation for migrating to nostr-sdk 0.40

* rollback sdk to 0.38 version to merge disputes - we will come back to 0.40 when we will fix signature issue

* Update mostro-core dependency

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* added correction for the case of buyer adding back a new invoice after payment failure (#462)

* Fix for nostr sdk 40 issue on incoming message (#465)

* testing sdk 40

* fix for sdk 40

* cleaned cargo.toml

* Bump mostro core version

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* fix: sends order with an updated 'status' field as the reply to add-invoice when there is a preimage (#464)

* Feature-nip69-order-status (#467)

* feature: align to nip69 order status in nostr event

* Improved in progress nip69 logic

* refined event states of the order with nip69 request

* add another check to avoid multiple events with in-progress state

* Privacy range order fix (#468)

* add optional field for users in full privacy inside solver message

* To be tested - privacy range child order fix

* fix cargo.toml

* bumped mostro-core version to 6.35

* New user or privacy order send same user info with zeros (#471)

* new user or privacy order send same user info with zeros

* fix days field and removed some println! macro with nicer tracing messages

* bumped mostro-core version to 6.36 and added requested fix to compile

* Add previous order state in database for solver message (#472)

* add previous state in database for solver message

* bumped mostro-core version to 6.36

* Taker info message to maker.

I think that could be modifies in a more generic UserInfo.
 (#473)

* added logic to send infos to maker when an order is taken

* Add takers info message for maker

* fix cargo.toml

* set peer pubkey to empty string when notifying taker reputation to maker

* moved user info message to the right point of the order flow

* fix cargo.toml

* changed message struct from UserDisputeInfo to UserInfo

* fix: get master keys for user infos

* Bumped mostro-core to version 6.38

* fix for buy order flow with message to maker (#479)

* Rabbit fixes

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Catrya <140891948+Catrya@users.noreply.github.com>
Co-authored-by: Bilthon <bilthon@gmail.com>
@coderabbitai coderabbitai Bot mentioned this pull request Oct 29, 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.

4 participants