From 008f3fe6a4e984b5b9399103f06e8b6e0fbb4184 Mon Sep 17 00:00:00 2001 From: ok300 <106775972+ok300@users.noreply.github.com> Date: Tue, 30 Apr 2024 14:37:06 +0200 Subject: [PATCH] Fix yielding send_payment handling with timeout --- libs/sdk-core/src/breez_services.rs | 29 ++++++++++++++--------------- libs/sdk-core/src/error.rs | 7 +++++++ 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/libs/sdk-core/src/breez_services.rs b/libs/sdk-core/src/breez_services.rs index 5ab70f308..18fe471ef 100644 --- a/libs/sdk-core/src/breez_services.rs +++ b/libs/sdk-core/src/breez_services.rs @@ -328,32 +328,31 @@ impl BreezServices { self.notify_event_listeners(BreezEvent::payment_started(pending_payment.clone())) .await?; - let pending_timeout_sec = req.pending_timeout_sec.unwrap_or(u64::MAX); - let (tx, rx) = std::sync::mpsc::channel(); + let (tx, rx) = tokio::sync::oneshot::channel(); let cloned = self.clone(); tokio::spawn(async move { + let label = req.label; + let payee_pk = parsed_invoice.payee_pubkey.clone(); + let bolt11 = parsed_invoice.bolt11.clone(); + let payment_res = cloned .node_api - .send_payment( - parsed_invoice.bolt11.clone(), - req.amount_msat, - req.label.clone(), - ) + .send_payment(bolt11, req.amount_msat, label.clone()) .map_err(Into::into) .await; let result = cloned - .on_payment_completed( - parsed_invoice.payee_pubkey.clone(), - Some(parsed_invoice), - req.label, - payment_res, - ) + .on_payment_completed(payee_pk, Some(parsed_invoice), label, payment_res) .await; let _ = tx.send(result); }); - match rx.recv_timeout(Duration::from_secs(pending_timeout_sec)) { - Ok(result) => result.map(SendPaymentResponse::from_payment), + let pending_timeout_sec = req.pending_timeout_sec.unwrap_or(u64::MAX); + match tokio::time::timeout(Duration::from_secs(pending_timeout_sec), rx).await { + Ok(Ok(result)) => result.map(SendPaymentResponse::from_payment), + Ok(Err(_)) => { + error!("The send_payment sender (tx) dropped without sending a message"); + Err(SendPaymentError::payment_failed("Payment call interrupted")) + } Err(_) => Ok(SendPaymentResponse::from_payment(pending_payment)), } } diff --git a/libs/sdk-core/src/error.rs b/libs/sdk-core/src/error.rs index 2c662df1a..f26642cf4 100644 --- a/libs/sdk-core/src/error.rs +++ b/libs/sdk-core/src/error.rs @@ -765,6 +765,13 @@ pub enum SendPaymentError { #[error("Service connectivity: {err}")] ServiceConnectivity { err: String }, } +impl SendPaymentError { + pub(crate) fn payment_failed(err: &str) -> Self { + Self::PaymentFailed { + err: err.to_string(), + } + } +} impl From for SendPaymentError { fn from(err: anyhow::Error) -> Self {