Refactor stuff to indeed release resources

This commit is contained in:
Alex 2022-07-13 16:14:10 +02:00
parent 3b256de3dc
commit 2a0aa0d42c
Signed by: lx
GPG key ID: 0E496D15096376BE

View file

@ -471,31 +471,29 @@ impl K2vWatch {
let watch = Arc::new(K2vWatch { pk, sk, rx, notify }); let watch = Arc::new(K2vWatch { pk, sk, rx, notify });
tokio::spawn(Self::watcher_task( tokio::spawn(Self::background_task(
Arc::downgrade(&watch), Arc::downgrade(&watch),
creds.k2v_client()?, creds.k2v_client()?,
tx, tx,
)); ));
tokio::spawn(Self::updater_task(
Arc::downgrade(&watch),
creds.k2v_client()?,
));
Ok(watch) Ok(watch)
} }
async fn watcher_task( async fn background_task(
self_weak: Weak<Self>, self_weak: Weak<Self>,
k2v: K2vClient, k2v: K2vClient,
tx: watch::Sender<Option<CausalityToken>>, tx: watch::Sender<Option<CausalityToken>>,
) { ) {
let mut ct = None; let mut ct = None;
while let Some(this) = Weak::upgrade(&self_weak) { while let Some(this) = Weak::upgrade(&self_weak) {
info!("bayou k2v watch loop iter: ct = {:?}", ct); debug!(
let update = tokio::select!( "bayou k2v watch bg loop iter ({}, {}): ct = {:?}",
_ = tokio::time::sleep(Duration::from_secs(60)) => continue, this.pk, this.sk, ct
r = k2v_wait_value_changed(&k2v, &this.pk, &this.sk, &ct) => r,
); );
tokio::select!(
_ = tokio::time::sleep(Duration::from_secs(60)) => continue,
update = k2v_wait_value_changed(&k2v, &this.pk, &this.sk, &ct) => {
match update { match update {
Err(e) => { Err(e) => {
error!("Error in bayou k2v wait value changed: {}", e); error!("Error in bayou k2v wait value changed: {}", e);
@ -509,23 +507,14 @@ impl K2vWatch {
} }
} }
} }
info!("bayou k2v watch loop exiting");
}
async fn updater_task(self_weak: Weak<Self>, k2v: K2vClient) {
while let Some(this) = Weak::upgrade(&self_weak) {
let ct: Option<CausalityToken> = this.rx.borrow().clone();
let rand = u128::to_be_bytes(thread_rng().gen()).to_vec();
tokio::select!(
_ = tokio::time::sleep(Duration::from_secs(60)) => (),
_ = this.notify.notified() => { _ = this.notify.notified() => {
let rand = u128::to_be_bytes(thread_rng().gen()).to_vec();
if let Err(e) = k2v if let Err(e) = k2v
.insert_item( .insert_item(
&this.pk, &this.pk,
&this.sk, &this.sk,
rand, rand,
ct, ct.clone(),
) )
.await .await
{ {
@ -533,9 +522,9 @@ impl K2vWatch {
tokio::time::sleep(Duration::from_secs(30)).await; tokio::time::sleep(Duration::from_secs(30)).await;
} }
} }
) );
} }
info!("bayou k2v watch updater loop exiting"); info!("bayou k2v watch bg loop exiting");
} }
} }