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

Return rules evaluation from the api response on rule valuation #37

Merged
merged 3 commits into from
Apr 19, 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
56 changes: 52 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use crate::config::Config;
use crate::controller::{ControllerCommands, ControllerInterface, DBQuery};
use crate::rules::Results;
use crate::storage;
use crate::types::PremintTypes;
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Serialize;
use sqlx::SqlitePool;
use tokio::net::TcpListener;

Expand Down Expand Up @@ -64,13 +66,59 @@ async fn health() -> &'static str {
async fn submit_premint(
State(state): State<AppState>,
Json(premint): Json<PremintTypes>,
) -> (StatusCode, String) {
) -> (StatusCode, Json<APIResponse>) {
let (snd, recv) = tokio::sync::oneshot::channel();
match state
.controller
.send_command(ControllerCommands::Broadcast { message: premint })
.send_command(ControllerCommands::Broadcast {
message: premint,
channel: snd,
})
.await
{
Ok(()) => (StatusCode::OK, "Premint submitted".to_string()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
Ok(()) => match recv.await {
Ok(Ok(_)) => (
StatusCode::OK,
Json(APIResponse::Success {
message: "Premint submitted".to_string(),
}),
),
Ok(Err(e)) => match e.downcast_ref::<Results>() {
Some(res) => (
StatusCode::BAD_REQUEST,
Json(APIResponse::RulesError {
evaluation: res.clone(),
}),
),
None => (
StatusCode::BAD_REQUEST,
Json(APIResponse::Error {
message: e.to_string(),
}),
),
},
Err(e) => {
tracing::warn!("Failed to submit premint: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(APIResponse::Error {
message: e.to_string(),
}),
)
}
},
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(APIResponse::Error {
message: e.to_string(),
}),
),
}
}

#[derive(Serialize)]
pub enum APIResponse {
RulesError { evaluation: Results },
Error { message: String },
Success { message: String },
}
27 changes: 20 additions & 7 deletions src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ pub enum ControllerCommands {
AnnounceSelf,
Broadcast {
message: PremintTypes,
channel: oneshot::Sender<eyre::Result<()>>,
},
ReturnNodeInfo {
channel: oneshot::Sender<MintpoolNodeInfo>,
Expand Down Expand Up @@ -125,16 +126,28 @@ impl Controller {
.send(SwarmCommand::AnnounceSelf)
.await?;
}
ControllerCommands::Broadcast { message } => {
ControllerCommands::Broadcast { message, channel } => {
match self.validate_and_insert(message.clone()).await {
Ok(_) => {
self.swarm_command_sender
Ok(_result) => {
if let Err(err) = self
.swarm_command_sender
.send(SwarmCommand::Broadcast { message })
.await?;
}
Err(err) => {
tracing::warn!("Invalid premint, not broadcasting: {:?}", err);
.await
{
channel
.send(Err(eyre::eyre!("Error broadcasing premint: {:?}", err)))
.map_err(|err| {
eyre::eyre!("error broadcasting via channel: {:?}", err)
})?;
} else {
channel.send(Ok(())).map_err(|err| {
eyre::eyre!("error broadcasting via channel: {:?}", err)
})?;
}
}
Err(err) => channel
.send(Err(err))
.map_err(|err| eyre::eyre!("error broadcasting via channel: {:?}", err))?,
}
}
ControllerCommands::ReturnNodeInfo { channel } => {
Expand Down
2 changes: 2 additions & 0 deletions src/p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,8 @@ impl SwarmController {
} else {
match serde_json::from_str::<PremintTypes>(&msg) {
Ok(premint) => {
let id = premint.metadata().id;
tracing::info!(id = id, "Received new premint");
self.event_sender
.send(P2PEvent::PremintReceived(premint.clone()))
.await
Expand Down
18 changes: 15 additions & 3 deletions src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::config::Config;
use crate::storage::{PremintStorage, Reader};
use crate::types::PremintTypes;

#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Evaluation {
Accept,
Ignore(String),
Expand Down Expand Up @@ -67,6 +67,18 @@ pub struct RuleResult {
pub result: eyre::Result<Evaluation>,
}

impl Clone for RuleResult {
fn clone(&self) -> Self {
Self {
rule_name: self.rule_name,
result: match &self.result {
Ok(e) => Ok(e.clone()),
Err(e) => Err(eyre::eyre!(e.to_string())),
},
}
}
}

impl Serialize for RuleResult {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand All @@ -91,7 +103,7 @@ impl Serialize for RuleResult {
}
}

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

impl Results {
Expand Down Expand Up @@ -437,7 +449,7 @@ mod test {
use crate::premints::zora_premint_v2::types::ZoraPremintV2;
use crate::rules::general::existing_token_uri;
use crate::rules::Evaluation::{Accept, Reject};
use crate::storage::Writer;
use crate::storage::{PremintStorage, Writer};
use crate::types::{Premint, SimplePremint};

use super::*;
Expand Down
17 changes: 16 additions & 1 deletion src/stdin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,27 @@ async fn process_stdin_line(ctl: ControllerInterface, line: String) {
} else {
match PremintTypes::from_json(line) {
Ok(premint) => {
let (snd, recv) = tokio::sync::oneshot::channel();
if let Err(err) = ctl
.send_command(ControllerCommands::Broadcast { message: premint })
.send_command(ControllerCommands::Broadcast {
message: premint,
channel: snd,
})
.await
{
tracing::error!(error = err.to_string(), "Error sending broadcast command");
};
match recv.await {
Ok(Ok(())) => {
tracing::info!("Premint broadcasted successfully");
}
Ok(Err(e)) => {
tracing::warn!("Error broadcasting premint: {:?}", e);
}
Err(e) => {
tracing::error!("Error broadcasting premint: {:?}", e);
}
}
}

Err(e) => {
Expand Down
2 changes: 2 additions & 0 deletions tests/e2e_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ async fn test_zora_premint_v2_e2e() {
// Push a message to the mintpool
let premint: ZoraPremintV2 = serde_json::from_str(PREMINT_JSON).unwrap();

let (send, _recv) = tokio::sync::oneshot::channel();
ctl.send_command(ControllerCommands::Broadcast {
message: PremintTypes::ZoraV2(premint),
channel: send,
})
.await
.unwrap();
Expand Down
5 changes: 4 additions & 1 deletion tests/p2p_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,20 @@ async fn test_list_all_premints() {

let nodes = mintpool_build::gen_fully_connected_swarm(2310, num_nodes).await;
let (first, nodes) = mintpool_build::split_first_rest(nodes).await;

let (snd, rcv) = tokio::sync::oneshot::channel();
first
.send_command(Broadcast {
message: PremintTypes::ZoraV2(Default::default()),
channel: snd,
})
.await
.unwrap();
let (snd, rcv) = tokio::sync::oneshot::channel();

first
.send_command(Broadcast {
message: PremintTypes::Simple(SimplePremint::build_default()),
channel: snd,
})
.await
.unwrap();
Expand Down
Loading