Skip to content
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

pipe function for watcher.rs and replaced usage #459

Merged
merged 6 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion common/src/watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ use std::{future::Future, time::Duration};

use tokio::{
select,
sync::watch,
sync::watch::{self, Ref},
task::JoinHandle,
time::{self, sleep},
};
use tracing::warn;
Expand Down Expand Up @@ -84,3 +85,31 @@ where
});
rx
}

// Replacement for pipe_async function in eventuals
// Listen to the changes in a receiver and runs parametric function
pub fn watch_pipe<T, F, Fut>(rx: watch::Receiver<T>, function: F) -> JoinHandle<()>
where
T: Clone + Send + Sync + 'static,
F: Fn(Ref<'_, T>) -> Fut + Send + Sync + 'static,
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
Fut: Future<Output = ()> + Send + 'static,
{
tokio::spawn(async move {
let mut rx = rx;
let value = rx.borrow();
function(value).await;
loop {
let res = rx.changed().await;
match res {
Ok(_) => {
let value = rx.borrow();
function(value).await;
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
}
Err(err) => {
warn!("{err}");
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
break;
}
};
}
})
}
26 changes: 12 additions & 14 deletions tap-agent/src/agent/sender_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use bigdecimal::ToPrimitive;

use futures::{stream, StreamExt};
use graphql_client::GraphQLQuery;
use indexer_common::watcher::watch_pipe;
use jsonrpsee::http_client::HttpClientBuilder;
use prometheus::{register_gauge_vec, register_int_gauge_vec, GaugeVec, IntGaugeVec};
use reqwest::Url;
Expand Down Expand Up @@ -496,30 +497,27 @@ impl Actor for SenderAccount {
}: Self::Arguments,
) -> std::result::Result<Self::State, ActorProcessingErr> {
let myself_clone = myself.clone();
let _indexer_allocations_handle = tokio::spawn(async move {
let mut indexer_allocations = indexer_allocations.clone();
loop {
let allocation_ids = indexer_allocations.borrow().clone();
let _indexer_allocations_handle = watch_pipe(indexer_allocations, move |allocation_ids| {
let myself = myself_clone.clone();
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
let allocation_ids = allocation_ids.clone();
async move {
// Update the allocation_ids
myself_clone
myself
.cast(SenderAccountMessage::UpdateAllocationIds(allocation_ids))
.unwrap_or_else(|e| {
error!("Error while updating allocation_ids: {:?}", e);
});
if indexer_allocations.changed().await.is_err() {
break;
}
}
});

let myself_clone = myself.clone();
let pgpool_clone = pgpool.clone();
let mut accounts_clone = escrow_accounts.clone();
let _escrow_account_monitor = tokio::spawn(async move {
while accounts_clone.changed().await.is_ok() {
let escrow_account = accounts_clone.borrow().clone();
let myself = myself_clone.clone();
let pgpool = pgpool_clone.clone();
let accounts_clone = escrow_accounts.clone();
let _escrow_account_monitor = watch_pipe(accounts_clone, move |escrow_account| {
let myself = myself_clone.clone();
let pgpool = pgpool_clone.clone();
let escrow_account = escrow_account.clone();
async move {
// Get balance or default value for sender
// this balance already takes into account thawing
let balance = escrow_account
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
51 changes: 23 additions & 28 deletions tap-agent/src/agent/sender_accounts_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use std::collections::HashSet;
use std::time::Duration;
use std::{collections::HashMap, str::FromStr};

use super::sender_account::{
SenderAccount, SenderAccountArgs, SenderAccountConfig, SenderAccountMessage,
};
use crate::agent::sender_allocation::SenderAllocationMessage;
use crate::lazy_static;
use alloy::dyn_abi::Eip712Domain;
Expand All @@ -14,6 +17,8 @@ use anyhow::{anyhow, bail};
use futures::{stream, StreamExt};
use indexer_common::escrow_accounts::EscrowAccounts;
use indexer_common::prelude::{Allocation, SubgraphClient};
use indexer_common::watcher::watch_pipe;
use prometheus::{register_counter_vec, CounterVec};
use ractor::concurrency::JoinHandle;
use ractor::{Actor, ActorCell, ActorProcessingErr, ActorRef, SupervisionEvent};
use reqwest::Url;
Expand All @@ -23,12 +28,6 @@ use tokio::select;
use tokio::sync::watch::{self, Receiver};
use tracing::{error, warn};

use prometheus::{register_counter_vec, CounterVec};

use super::sender_account::{
SenderAccount, SenderAccountArgs, SenderAccountConfig, SenderAccountMessage,
};

lazy_static! {
static ref RECEIPTS_CREATED: CounterVec = register_counter_vec!(
"tap_receipts_received_total",
Expand Down Expand Up @@ -106,17 +105,12 @@ impl Actor for SenderAccountsManager {
}: Self::Arguments,
) -> std::result::Result<Self::State, ActorProcessingErr> {
let (allocations_tx, allocations_rx) = watch::channel(HashSet::<Address>::new());
tokio::spawn(async move {
let mut indexer_allocations = indexer_allocations.clone();
while indexer_allocations.changed().await.is_ok() {
watch_pipe(indexer_allocations.clone(), move |allocation_id| {
let allocations_tx = allocations_tx.clone();
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
let allocation_set = allocation_id.keys().cloned().collect::<HashSet<Address>>();
async move {
allocations_tx
.send(
indexer_allocations
.borrow()
.keys()
.cloned()
.collect::<HashSet<Address>>(),
)
.send(allocation_set)
.expect("Failed to update indexer_allocations_set channel");
}
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
});
Expand All @@ -129,18 +123,19 @@ impl Actor for SenderAccountsManager {
'scalar_tap_receipt_notification'",
);
let myself_clone = myself.clone();
let mut accounts_clone = escrow_accounts.clone();
let _eligible_allocations_senders_handle = tokio::spawn(async move {
while accounts_clone.changed().await.is_ok() {
myself_clone
.cast(SenderAccountsManagerMessage::UpdateSenderAccounts(
accounts_clone.borrow().get_senders(),
))
.unwrap_or_else(|e| {
error!("Error while updating sender_accounts: {:?}", e);
});
}
});
let accounts_clone = escrow_accounts.clone();
let _eligible_allocations_senders_handle =
watch_pipe(accounts_clone, move |escrow_accounts| {
let myself = myself_clone.clone();
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
let senders = escrow_accounts.get_senders();
async move {
myself
.cast(SenderAccountsManagerMessage::UpdateSenderAccounts(senders))
.unwrap_or_else(|e| {
error!("Error while updating sender_accounts: {:?}", e);
});
}
gusinacio marked this conversation as resolved.
Show resolved Hide resolved
});

let mut state = State {
config,
Expand Down
Loading