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

Improve rule evaluation errors #36

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 11 additions & 9 deletions src/controller.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use eyre::WrapErr;
use sqlx::SqlitePool;
use tokio::select;
use tokio::sync::{mpsc, oneshot};

use crate::p2p::NetworkState;
use crate::rules::{RuleContext, RulesEngine};
use crate::rules::{Evaluation, Results, RuleContext, RulesEngine};
use crate::storage::{PremintStorage, Reader, Writer};
use crate::types::{InclusionClaim, MintpoolNodeInfo, PremintTypes};

Expand Down Expand Up @@ -171,18 +172,19 @@ impl Controller {
Ok(())
}

async fn validate_and_insert(&self, premint: PremintTypes) -> eyre::Result<()> {
async fn validate_and_insert(&self, premint: PremintTypes) -> eyre::Result<Results> {
let evaluation = self.rules.evaluate(&premint, self.store.clone()).await?;

if evaluation.is_accept() {
self.store.store(premint).await
self.store
.store(premint)
.await
.map(|_r| evaluation)
.wrap_err("Failed to store premint")
} else {
tracing::warn!(
"Premint failed validation: {:?}, evaluation: {:?}",
premint,
evaluation.summary()
);
Err(eyre::eyre!(evaluation.summary()))
tracing::info!("Premint failed validation: {:?}", premint);

Err(evaluation).wrap_err("Premint failed validation")
}
}
}
Expand Down
90 changes: 73 additions & 17 deletions src/rules.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::sync::Arc;

use alloy::network::Ethereum;
use async_trait::async_trait;
use futures::future::join_all;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};

use crate::chain_list::{ChainListProvider, CHAINS};
use crate::config::Config;
Expand All @@ -16,6 +20,33 @@ pub enum Evaluation {
Reject(String),
}

impl Display for Evaluation {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Evaluation::Accept => f.write_str("Accept"),
Evaluation::Ignore(reason) => write!(f, "Ignore ({})", reason),
Evaluation::Reject(reason) => write!(f, "Reject ({})", reason),
}
}
}

impl Evaluation {
fn variant(&self) -> &'static str {
match self {
Evaluation::Accept => "accept",
Evaluation::Ignore(_) => "ignore",
Evaluation::Reject(_) => "reject",
}
}

fn reason(&self) -> Option<&str> {
match self {
Evaluation::Ignore(reason) | Evaluation::Reject(reason) => Some(reason),
_ => None,
}
}
}

#[macro_export]
macro_rules! reject {
($($arg:tt)*) => {{
Expand All @@ -36,7 +67,31 @@ pub struct RuleResult {
pub result: eyre::Result<Evaluation>,
}

#[derive(Debug)]
impl Serialize for RuleResult {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer
.serialize_struct("RuleResult", 3)
.and_then(|mut s| {
match self.result {
Ok(ref result) => {
s.serialize_field("result", result.variant())?;
s.serialize_field("reason", &result.reason())?;
}
Err(ref e) => {
s.serialize_field("result", "error")?;
s.serialize_field("reason", &e.to_string())?;
}
}
s.serialize_field("rule_name", &self.rule_name)?;
s.end()
})
}
}

#[derive(Debug, Serialize)]
pub struct Results(Vec<RuleResult>);

impl Results {
Expand All @@ -55,22 +110,23 @@ impl Results {
pub fn is_err(&self) -> bool {
self.0.iter().any(|r| r.result.is_err())
}
}

pub fn summary(&self) -> String {
self.0
.iter()
.map(|r| match r.result {
Ok(Evaluation::Accept) => format!("{}: Accept", r.rule_name),
Ok(Evaluation::Ignore(ref reason)) => {
format!("{}: Ignore ({})", r.rule_name, reason)
}
Ok(Evaluation::Reject(ref reason)) => {
format!("{}: Reject ({})", r.rule_name, reason)
}
Err(ref e) => format!("{}: Error ({})", r.rule_name, e),
})
.collect::<Vec<_>>()
.join("\n")
impl Error for Results {}

impl Display for Results {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(
self.0
.iter()
.map(|r| match r.result {
Ok(ref e) => format!("{}: {}", r.rule_name, e),
Err(ref e) => format!("{}: Error ({})", r.rule_name, e),
})
.collect::<Vec<_>>()
.join("\n")
.as_str(),
)
}
}

Expand Down Expand Up @@ -276,7 +332,7 @@ impl<T: Reader> RulesEngine<T> {
}

mod general {
use crate::rules::Evaluation::{Accept, Ignore, Reject};
use crate::rules::Evaluation::Accept;
use crate::rules::{Evaluation, Rule, RuleContext};
use crate::storage::Reader;
use crate::types::PremintMetadata;
Expand Down
Loading