Skip to content

Commit

Permalink
Apply changes to bindings & generate them
Browse files Browse the repository at this point in the history
- Create LevelFilter struct that's usable from bindings.
- Add optional filter_level param to binding logger init & setters
- Map models:LevelFilter to log::LevelFilter.
  - Set LevelFilter::TRACE as default filter level
  • Loading branch information
erdemyerebasmaz committed Mar 22, 2024
1 parent d8fa8eb commit 8cdbad4
Show file tree
Hide file tree
Showing 12 changed files with 290 additions and 56 deletions.
11 changes: 10 additions & 1 deletion libs/sdk-bindings/src/breez_sdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,15 @@ dictionary RefundResponse {
string refund_tx_id;
};

enum LevelFilter {
"Off",
"Error",
"Warn",
"Info",
"Debug",
"Trace",
};

interface BlockingBreezServices {

[Throws=SdkError]
Expand Down Expand Up @@ -956,7 +965,7 @@ namespace breez_sdk {
BlockingBreezServices connect(ConnectRequest req, EventListener listener);

[Throws=SdkError]
void set_log_stream(LogStream log_stream);
void set_log_stream(LogStream log_stream, LevelFilter? filter_level);

[Throws=SdkError]
LNInvoice parse_invoice(string invoice);
Expand Down
43 changes: 23 additions & 20 deletions libs/sdk-bindings/src/uniffi_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@ use breez_sdk_core::{
CheckMessageResponse, ClosedChannelPaymentDetails, Config, ConfigureNodeRequest,
ConnectRequest, CurrencyInfo, EnvironmentType, EventListener, FeeratePreset, FiatCurrency,
GreenlightCredentials, GreenlightNodeConfig, HealthCheckStatus, InputType, InvoicePaidDetails,
LNInvoice, ListPaymentsRequest, LnPaymentDetails, LnUrlAuthRequestData, LnUrlCallbackStatus,
LnUrlErrorData, LnUrlPayErrorData, LnUrlPayRequest, LnUrlPayRequestData, LnUrlPayResult,
LnUrlPaySuccessData, LnUrlWithdrawRequest, LnUrlWithdrawRequestData, LnUrlWithdrawResult,
LnUrlWithdrawSuccessData, LocaleOverrides, LocalizedName, LogEntry, LogStream, LspInformation,
MaxReverseSwapAmountResponse, MessageSuccessActionData, MetadataFilter, MetadataItem, Network,
NodeConfig, NodeCredentials, NodeState, OnchainPaymentLimitsResponse, OpenChannelFeeRequest,
OpenChannelFeeResponse, OpeningFeeParams, OpeningFeeParamsMenu, PayOnchainRequest,
PayOnchainResponse, Payment, PaymentDetails, PaymentFailedData, PaymentStatus, PaymentType,
PaymentTypeFilter, PrepareOnchainPaymentRequest, PrepareOnchainPaymentResponse,
PrepareRedeemOnchainFundsRequest, PrepareRedeemOnchainFundsResponse, PrepareRefundRequest,
PrepareRefundResponse, Rate, ReceiveOnchainRequest, ReceivePaymentRequest,
ReceivePaymentResponse, RecommendedFees, RedeemOnchainFundsRequest, RedeemOnchainFundsResponse,
RefundRequest, RefundResponse, ReportIssueRequest, ReportPaymentFailureDetails,
ReverseSwapFeesRequest, ReverseSwapInfo, ReverseSwapPairInfo, ReverseSwapStatus, RouteHint,
RouteHintHop, SendOnchainRequest, SendOnchainResponse, SendPaymentRequest, SendPaymentResponse,
SendSpontaneousPaymentRequest, ServiceHealthCheckResponse, SignMessageRequest,
SignMessageResponse, StaticBackupRequest, StaticBackupResponse, SuccessActionProcessed,
SwapAmountType, SwapInfo, SwapStatus, Symbol, TlvEntry, UnspentTransactionOutput,
UrlSuccessActionData,
LNInvoice, LevelFilter, ListPaymentsRequest, LnPaymentDetails, LnUrlAuthRequestData,
LnUrlCallbackStatus, LnUrlErrorData, LnUrlPayErrorData, LnUrlPayRequest, LnUrlPayRequestData,
LnUrlPayResult, LnUrlPaySuccessData, LnUrlWithdrawRequest, LnUrlWithdrawRequestData,
LnUrlWithdrawResult, LnUrlWithdrawSuccessData, LocaleOverrides, LocalizedName, LogEntry,
LogStream, LspInformation, MaxReverseSwapAmountResponse, MessageSuccessActionData,
MetadataFilter, MetadataItem, Network, NodeConfig, NodeCredentials, NodeState,
OnchainPaymentLimitsResponse, OpenChannelFeeRequest, OpenChannelFeeResponse, OpeningFeeParams,
OpeningFeeParamsMenu, PayOnchainRequest, PayOnchainResponse, Payment, PaymentDetails,
PaymentFailedData, PaymentStatus, PaymentType, PaymentTypeFilter, PrepareOnchainPaymentRequest,
PrepareOnchainPaymentResponse, PrepareRedeemOnchainFundsRequest,
PrepareRedeemOnchainFundsResponse, PrepareRefundRequest, PrepareRefundResponse, Rate,
ReceiveOnchainRequest, ReceivePaymentRequest, ReceivePaymentResponse, RecommendedFees,
RedeemOnchainFundsRequest, RedeemOnchainFundsResponse, RefundRequest, RefundResponse,
ReportIssueRequest, ReportPaymentFailureDetails, ReverseSwapFeesRequest, ReverseSwapInfo,
ReverseSwapPairInfo, ReverseSwapStatus, RouteHint, RouteHintHop, SendOnchainRequest,
SendOnchainResponse, SendPaymentRequest, SendPaymentResponse, SendSpontaneousPaymentRequest,
ServiceHealthCheckResponse, SignMessageRequest, SignMessageResponse, StaticBackupRequest,
StaticBackupResponse, SuccessActionProcessed, SwapAmountType, SwapInfo, SwapStatus, Symbol,
TlvEntry, UnspentTransactionOutput, UrlSuccessActionData,
};
use once_cell::sync::Lazy;
use std::sync::Arc;
Expand Down Expand Up @@ -78,7 +78,10 @@ pub fn connect(
}

/// If used, this must be called before `connect`
pub fn set_log_stream(log_stream: Box<dyn LogStream>, filter_level: Option<LevelFilter>) -> SdkResult<()> {
pub fn set_log_stream(
log_stream: Box<dyn LogStream>,
filter_level: Option<LevelFilter>,
) -> SdkResult<()> {
init_uniffi_logger(log_stream, filter_level);
Ok(())
}
Expand Down
3 changes: 1 addition & 2 deletions libs/sdk-core/src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::sync::Arc;

use anyhow::{anyhow, Result};
use flutter_rust_bridge::StreamSink;
use log::LevelFilter;
use once_cell::sync::{Lazy, OnceCell};
use tokio::sync::Mutex;

Expand All @@ -34,7 +33,7 @@ use crate::lsp::LspInformation;
use crate::models::{Config, LogEntry, NodeState, Payment, SwapInfo};
use crate::{
BackupStatus, BuyBitcoinRequest, BuyBitcoinResponse, CheckMessageRequest, CheckMessageResponse,
ConfigureNodeRequest, ConnectRequest, EnvironmentType, ListPaymentsRequest,
ConfigureNodeRequest, ConnectRequest, EnvironmentType, LevelFilter, ListPaymentsRequest,
LnUrlCallbackStatus, LnUrlPayRequest, LnUrlWithdrawRequest, LnUrlWithdrawResult,
MaxReverseSwapAmountResponse, NodeConfig, NodeCredentials, OnchainPaymentLimitsResponse,
OpenChannelFeeRequest, OpenChannelFeeResponse, PayOnchainRequest, PayOnchainResponse,
Expand Down
15 changes: 13 additions & 2 deletions libs/sdk-core/src/bridge_generated.io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ pub extern "C" fn wire_breez_events_stream(port_: i64) {
}

#[no_mangle]
pub extern "C" fn wire_breez_log_stream(port_: i64) {
wire_breez_log_stream_impl(port_)
pub extern "C" fn wire_breez_log_stream(port_: i64, filter_level: *mut i32) {
wire_breez_log_stream_impl(port_, filter_level)
}

#[no_mangle]
Expand Down Expand Up @@ -356,6 +356,11 @@ pub extern "C" fn new_box_autoadd_i64_0(value: i64) -> *mut i64 {
support::new_leak_box_ptr(value)
}

#[no_mangle]
pub extern "C" fn new_box_autoadd_level_filter_0(value: i32) -> *mut i32 {
support::new_leak_box_ptr(value)
}

#[no_mangle]
pub extern "C" fn new_box_autoadd_list_payments_request_0() -> *mut wire_ListPaymentsRequest {
support::new_leak_box_ptr(wire_ListPaymentsRequest::new_with_null_ptr())
Expand Down Expand Up @@ -580,6 +585,12 @@ impl Wire2Api<i64> for *mut i64 {
unsafe { *support::box_from_leak_ptr(self) }
}
}
impl Wire2Api<LevelFilter> for *mut i32 {
fn wire2api(self) -> LevelFilter {
let wrap = unsafe { support::box_from_leak_ptr(self) };
Wire2Api::<LevelFilter>::wire2api(*wrap).into()
}
}
impl Wire2Api<ListPaymentsRequest> for *mut wire_ListPaymentsRequest {
fn wire2api(self) -> ListPaymentsRequest {
let wrap = unsafe { support::box_from_leak_ptr(self) };
Expand Down
26 changes: 24 additions & 2 deletions libs/sdk-core/src/bridge_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ use crate::models::EnvironmentType;
use crate::models::GreenlightCredentials;
use crate::models::GreenlightNodeConfig;
use crate::models::HealthCheckStatus;
use crate::models::LevelFilter;
use crate::models::ListPaymentsRequest;
use crate::models::LnPaymentDetails;
use crate::models::LnUrlCallbackStatus;
Expand Down Expand Up @@ -311,14 +312,22 @@ fn wire_breez_events_stream_impl(port_: MessagePort) {
},
)
}
fn wire_breez_log_stream_impl(port_: MessagePort) {
fn wire_breez_log_stream_impl(
port_: MessagePort,
filter_level: impl Wire2Api<Option<LevelFilter>> + UnwindSafe,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, (), _>(
WrapInfo {
debug_name: "breez_log_stream",
port: Some(port_),
mode: FfiCallMode::Stream,
},
move || move |task_callback| breez_log_stream(task_callback.stream_sink::<_, LogEntry>()),
move || {
let api_filter_level = filter_level.wire2api();
move |task_callback| {
breez_log_stream(task_callback.stream_sink::<_, LogEntry>(), api_filter_level)
}
},
)
}
fn wire_list_lsps_impl(port_: MessagePort) {
Expand Down Expand Up @@ -949,6 +958,19 @@ impl Wire2Api<i64> for i64 {
self
}
}
impl Wire2Api<LevelFilter> for i32 {
fn wire2api(self) -> LevelFilter {
match self {
0 => LevelFilter::Off,
1 => LevelFilter::Error,
2 => LevelFilter::Warn,
3 => LevelFilter::Info,
4 => LevelFilter::Debug,
5 => LevelFilter::Trace,
_ => unreachable!("Invalid variant for LevelFilter: {}", self),
}
}
}

impl Wire2Api<Network> for i32 {
fn wire2api(self) -> Network {
Expand Down
42 changes: 23 additions & 19 deletions libs/sdk-core/src/logger.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::models::LevelFilter as BindingLevelFilter;
use crate::{LogEntry, LogStream};
use anyhow::{anyhow, Result};
use chrono::Local;
Expand Down Expand Up @@ -83,13 +84,9 @@ fn init_env_logger(target: Option<Target>, filter_level: Option<LevelFilter>) ->

static INIT_DART_LOGGER: Once = Once::new();

pub fn init_dart_logger(filter_level: Option<LevelFilter>) {
pub fn init_dart_logger(filter_level: Option<BindingLevelFilter>) {
INIT_DART_LOGGER.call_once(|| {
let filter_level = if filter_level.is_some() {
filter_level.unwrap()
} else {
LevelFilter::Trace
};
let filter_level = get_filter_level(filter_level);

assert!(
filter_level <= STATIC_MAX_LEVEL,
Expand Down Expand Up @@ -157,7 +154,10 @@ impl Log for DartLogger {

static INIT_UNIFFI_LOGGER: Once = Once::new();

pub fn init_uniffi_logger(log_stream: Box<dyn LogStream>, filter_level: Option<LevelFilter>) {
pub fn init_uniffi_logger(
log_stream: Box<dyn LogStream>,
filter_level: Option<BindingLevelFilter>,
) {
INIT_UNIFFI_LOGGER.call_once(|| {
UniFFILogger::set_log_stream(log_stream, filter_level);
});
Expand All @@ -169,13 +169,8 @@ pub struct UniFFILogger {
}

impl UniFFILogger {
fn set_log_stream(log_stream: Box<dyn LogStream>, filter_level: Option<LevelFilter>) {
let filter_level = if filter_level.is_some() {
filter_level.unwrap()
} else {
LevelFilter::Trace
};

fn set_log_stream(log_stream: Box<dyn LogStream>, filter_level: Option<BindingLevelFilter>) {
let filter_level = get_filter_level(filter_level);
assert!(
filter_level <= STATIC_MAX_LEVEL,
"Should respect STATIC_MAX_LEVEL={:?}, which is done in compile time. level{:?}",
Expand Down Expand Up @@ -254,11 +249,7 @@ pub fn init_sdk_logger(
app_logger: Option<Box<dyn Log>>,
filter_level: Option<LevelFilter>,
) -> Result<()> {
let filter_level = if filter_level.is_some() {
filter_level.unwrap()
} else {
LevelFilter::Trace
};
let filter_level = filter_level.unwrap_or(LevelFilter::Trace);

assert!(
filter_level <= STATIC_MAX_LEVEL,
Expand Down Expand Up @@ -315,3 +306,16 @@ impl Log for GlobalSdkLogger {

fn flush(&self) {}
}

/* Binding LevelFilter */

fn get_filter_level(filter_level: Option<BindingLevelFilter>) -> LevelFilter {
match filter_level.unwrap_or(BindingLevelFilter::Trace) {
BindingLevelFilter::Off => LevelFilter::Off,
BindingLevelFilter::Error => LevelFilter::Error,
BindingLevelFilter::Warn => LevelFilter::Warn,
BindingLevelFilter::Info => LevelFilter::Info,
BindingLevelFilter::Debug => LevelFilter::Debug,
BindingLevelFilter::Trace => LevelFilter::Trace,
}
}
30 changes: 30 additions & 0 deletions libs/sdk-core/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1653,6 +1653,36 @@ impl PaymentPathEdge {
}
}

/// An enum representing the available verbosity level filters of the logger.
#[repr(usize)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub enum LevelFilter {
// The "off" level.
///
/// A level lower than all log levels.
Off,
/// The "error" level.
///
/// Designates very serious errors.
Error,
/// The "warn" level.
///
/// Designates hazardous situations.
Warn,
/// The "info" level.
///
/// Designates useful information.
Info,
/// The "debug" level.
///
/// Designates lower priority information.
Debug,
/// The "trace" level.
///
/// Designates very low priority, often extremely verbose, information.
Trace,
}

#[cfg(test)]
mod tests {
use anyhow::Result;
Expand Down
5 changes: 4 additions & 1 deletion libs/sdk-flutter/ios/Classes/bridge_generated.h
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ void wire_service_health_check(int64_t port_, struct wire_uint_8_list *api_key);

void wire_breez_events_stream(int64_t port_);

void wire_breez_log_stream(int64_t port_);
void wire_breez_log_stream(int64_t port_, int32_t *filter_level);

void wire_list_lsps(int64_t port_);

Expand Down Expand Up @@ -424,6 +424,8 @@ struct wire_GreenlightNodeConfig *new_box_autoadd_greenlight_node_config_0(void)

int64_t *new_box_autoadd_i64_0(int64_t value);

int32_t *new_box_autoadd_level_filter_0(int32_t value);

struct wire_ListPaymentsRequest *new_box_autoadd_list_payments_request_0(void);

struct wire_LnUrlAuthRequestData *new_box_autoadd_ln_url_auth_request_data_0(void);
Expand Down Expand Up @@ -557,6 +559,7 @@ static int64_t dummy_method_to_enforce_bundling(void) {
dummy_var ^= ((int64_t) (void*) new_box_autoadd_greenlight_credentials_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_greenlight_node_config_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_i64_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_level_filter_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_list_payments_request_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_ln_url_auth_request_data_0);
dummy_var ^= ((int64_t) (void*) new_box_autoadd_ln_url_pay_request_0);
Expand Down
Loading

0 comments on commit 8cdbad4

Please sign in to comment.