forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
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(zcoin): impl balance event streaming #2076
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
ee857e5
save initial dev state — z_balance_streaming.rs
borngraced 12356fd
trigger z_balance_streaming impl
borngraced 517215a
finish working impl
borngraced c89f940
update doc comment
borngraced ae9986b
move z_params to storage and add send_status_on_err macro for ZCOin::…
borngraced 9f48b04
move types definitions to z_balance_streaming.rs mod
borngraced 2590fb2
include NetworkUpgrade::ZFuture in match arms
borngraced a233311
fix WASM build
borngraced fb98ce7
Merge remote-tracking branch 'origin/dev' into z_event_streaming
borngraced 19f6752
improve code organisation
borngraced 9d60dc8
remove unused
borngraced 498880d
don't clone consensus_params
borngraced b05ac4c
fix merge conflicts
borngraced File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
use crate::common::Future01CompatExt; | ||
use crate::hd_wallet::AsyncMutex; | ||
use crate::z_coin::ZCoin; | ||
use crate::{MarketCoinOps, MmCoin}; | ||
|
||
use async_trait::async_trait; | ||
use common::executor::{AbortSettings, SpawnAbortable}; | ||
use common::log::{error, info}; | ||
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender}; | ||
use futures::channel::oneshot; | ||
use futures::channel::oneshot::{Receiver, Sender}; | ||
use futures_util::StreamExt; | ||
use mm2_core::mm_ctx::MmArc; | ||
use mm2_event_stream::behaviour::{EventBehaviour, EventInitStatus}; | ||
use mm2_event_stream::{Event, EventStreamConfiguration}; | ||
use std::sync::Arc; | ||
|
||
pub type ZBalanceEventSender = UnboundedSender<()>; | ||
pub type ZBalanceEventHandler = Arc<AsyncMutex<UnboundedReceiver<()>>>; | ||
|
||
#[async_trait] | ||
impl EventBehaviour for ZCoin { | ||
const EVENT_NAME: &'static str = "COIN_BALANCE"; | ||
const ERROR_EVENT_NAME: &'static str = "COIN_BALANCE_ERROR"; | ||
Comment on lines
+23
to
+24
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note for the future development: We may need to maintain all the available event names from a single source without needing to type them manually for each implementation. |
||
|
||
async fn handle(self, _interval: f64, tx: Sender<EventInitStatus>) { | ||
const RECEIVER_DROPPED_MSG: &str = "Receiver is dropped, which should never happen."; | ||
|
||
macro_rules! send_status_on_err { | ||
($match: expr, $sender: tt, $msg: literal) => { | ||
match $match { | ||
Some(t) => t, | ||
None => { | ||
$sender | ||
.send(EventInitStatus::Failed($msg.to_owned())) | ||
.expect(RECEIVER_DROPPED_MSG); | ||
panic!("{}", $msg); | ||
}, | ||
} | ||
}; | ||
} | ||
|
||
let ctx = send_status_on_err!( | ||
MmArc::from_weak(&self.as_ref().ctx), | ||
tx, | ||
"MM context must have been initialized already." | ||
); | ||
let z_balance_change_handler = send_status_on_err!( | ||
self.z_fields.z_balance_event_handler.as_ref(), | ||
tx, | ||
"Z balance change receiver can not be empty." | ||
); | ||
|
||
tx.send(EventInitStatus::Success).expect(RECEIVER_DROPPED_MSG); | ||
|
||
// Locks the balance change handler, iterates through received events, and updates balance changes accordingly. | ||
let mut bal = z_balance_change_handler.lock().await; | ||
while (bal.next().await).is_some() { | ||
match self.my_balance().compat().await { | ||
Ok(balance) => { | ||
let payload = json!({ | ||
"ticker": self.ticker(), | ||
"address": self.my_z_address_encoded(), | ||
"balance": { "spendable": balance.spendable, "unspendable": balance.unspendable } | ||
}); | ||
|
||
ctx.stream_channel_controller | ||
.broadcast(Event::new(Self::EVENT_NAME.to_string(), payload.to_string())) | ||
.await; | ||
}, | ||
Err(err) => { | ||
let ticker = self.ticker(); | ||
error!("Failed getting balance for '{ticker}'. Error: {err}"); | ||
let e = serde_json::to_value(err).expect("Serialization should't fail."); | ||
return ctx | ||
.stream_channel_controller | ||
.broadcast(Event::new( | ||
format!("{}:{}", Self::ERROR_EVENT_NAME, ticker), | ||
e.to_string(), | ||
)) | ||
.await; | ||
}, | ||
}; | ||
} | ||
} | ||
|
||
async fn spawn_if_active(self, config: &EventStreamConfiguration) -> EventInitStatus { | ||
if let Some(event) = config.get_event(Self::EVENT_NAME) { | ||
info!( | ||
"{} event is activated for {} address {}. `stream_interval_seconds`({}) has no effect on this.", | ||
Self::EVENT_NAME, | ||
self.ticker(), | ||
self.my_z_address_encoded(), | ||
event.stream_interval_seconds | ||
); | ||
|
||
let (tx, rx): (Sender<EventInitStatus>, Receiver<EventInitStatus>) = oneshot::channel(); | ||
let fut = self.clone().handle(event.stream_interval_seconds, tx); | ||
let settings = | ||
AbortSettings::info_on_abort(format!("{} event is stopped for {}.", Self::EVENT_NAME, self.ticker())); | ||
self.spawner().spawn_with_settings(fut, settings); | ||
|
||
rx.await.unwrap_or_else(|e| { | ||
EventInitStatus::Failed(format!("Event initialization status must be received: {}", e)) | ||
}) | ||
} else { | ||
EventInitStatus::Inactive | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this clone is redundant? no?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good catch, thanks.