Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

Commit

Permalink
Feat: Add clear old txs cron
Browse files Browse the repository at this point in the history
  • Loading branch information
guscalonico committed Jul 28, 2022
1 parent 16bffa9 commit 48640e7
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/cron/clear_transactions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use crate::{database::{queries::{QueryContext, delete_txs}}};

use super::CronJobError;
use crate::cron::ValidatorCronError;

pub async fn clear_old_transactions<Context>(ctx: &Context) -> Result<(), CronJobError>
where
Context: QueryContext
{
let epoch = ctx.current_epoch();
delete_txs(ctx, epoch, 40).await
.map(|amount| print!( "Deleted {} transactions from epoch {} to {}", amount, epoch - 40, epoch))
.map_err(|err| CronJobError::ValidatorError(ValidatorCronError::from(err)))
}
6 changes: 6 additions & 0 deletions src/cron/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,9 @@ impl From<anyhow::Error> for ValidatorCronError {
ValidatorCronError::AddressNotFound
}
}

impl From<diesel::result::Error> for ValidatorCronError {
fn from(_err: diesel::result::Error) -> ValidatorCronError {
ValidatorCronError::TxNotFound
}
}
7 changes: 7 additions & 0 deletions src/cron/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod error;
mod slasher;
mod transactions;
mod validate;
mod clear_transactions;

use crate::{
context,
Expand Down Expand Up @@ -56,6 +57,12 @@ where
validate::validate_transactions,
30
),
create_cron(
&ctx,
"clear old transactions",
clear_transactions::clear_old_transactions,
180
)
);
}

Expand Down
14 changes: 14 additions & 0 deletions src/database/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use crate::database::schema::transactions::dsl::*;
use crate::database::schema::{bundle, transactions};
use crate::state::ValidatorStateAccess;

use super::models::Epoch;

pub trait QueryContext: ValidatorStateAccess {
fn get_db_connection(&self) -> PooledConnection<ConnectionManager<PgConnection>>;
fn current_epoch(&self) -> u128;
Expand Down Expand Up @@ -80,3 +82,15 @@ where
.filter(transactions::id.eq(tx_id))
.first::<Transaction>(&conn)
}

pub async fn delete_txs<Context>(ctx: &Context, current_epoch: u128, epoch_amount: u128) -> Result<usize, Error>
where
Context: QueryContext,
{
let epochs : Vec<Epoch> = (0..epoch_amount).map(|i| Epoch(current_epoch - i)).collect();
let conn = ctx.get_db_connection();
let txs = transactions
.filter(transactions::epoch.ne_all(epochs));
diesel::delete(txs)
.execute(&conn)
}

0 comments on commit 48640e7

Please sign in to comment.