diff --git a/catalyst-gateway/Cargo.lock b/catalyst-gateway/Cargo.lock index 60f46f49848..193189bbb12 100644 --- a/catalyst-gateway/Cargo.lock +++ b/catalyst-gateway/Cargo.lock @@ -198,55 +198,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" -[[package]] -name = "axum" -version = "0.6.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" -dependencies = [ - "async-trait", - "axum-core", - "bitflags 1.3.2", - "bytes", - "futures-util", - "http", - "http-body", - "hyper", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "rustversion", - "serde", - "serde_json", - "serde_path_to_error", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "axum-core" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" -dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http", - "http-body", - "mime", - "rustversion", - "tower-layer", - "tower-service", -] - [[package]] name = "backtrace" version = "0.3.69" @@ -437,10 +388,8 @@ name = "cat-gateway" version = "0.0.1" dependencies = [ "async-trait", - "axum", "bb8", "bb8-postgres", - "bytes", "chrono", "clap", "cpu-time", @@ -460,8 +409,6 @@ dependencies = [ "thiserror", "tokio", "tokio-postgres", - "tower", - "tower-http", "tracing", "tracing-subscriber", "ulid", @@ -1033,12 +980,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" - [[package]] name = "httparse" version = "1.8.0" @@ -1192,12 +1133,6 @@ version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" -[[package]] -name = "matchit" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" - [[package]] name = "md-5" version = "0.10.6" @@ -1446,26 +1381,6 @@ dependencies = [ "siphasher", ] -[[package]] -name = "pin-project" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.38", -] - [[package]] name = "pin-project-lite" version = "0.2.13" @@ -1971,12 +1886,6 @@ dependencies = [ "windows-sys", ] -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - [[package]] name = "ryu" version = "1.0.15" @@ -2041,16 +1950,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_path_to_error" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" -dependencies = [ - "itoa", - "serde", -] - [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2205,12 +2104,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "tap" version = "1.0.1" @@ -2410,46 +2303,6 @@ dependencies = [ "winnow", ] -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "pin-project", - "pin-project-lite", - "tokio", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-http" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" -dependencies = [ - "bitflags 2.4.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-range-header", - "pin-project-lite", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" - [[package]] name = "tower-service" version = "0.3.2" diff --git a/catalyst-gateway/Cargo.toml b/catalyst-gateway/Cargo.toml index 96566a3c7d6..1609965b3f9 100644 --- a/catalyst-gateway/Cargo.toml +++ b/catalyst-gateway/Cargo.toml @@ -26,8 +26,6 @@ tracing-subscriber = "0.3.16" serde = "1.0" serde_json = "1.0" -axum = "0.6.9" - poem = "1.3.58" poem-openapi = "3.0.4" poem-extensions = "0.7.2" @@ -37,13 +35,10 @@ cryptoxide = "0.4.4" uuid = "1" lazy_static = "1.4" panic-message = "0.3" -bytes = "1.4" cpu-time = "1.0" ulid = "1.0.1" rust-embed = "8" -tower-http = "0.4" -tower = "0.4" hyper = "0.14" url = "2.4.1" diff --git a/catalyst-gateway/bin/Cargo.toml b/catalyst-gateway/bin/Cargo.toml index e7dd156d1f1..1f2aa80104b 100644 --- a/catalyst-gateway/bin/Cargo.toml +++ b/catalyst-gateway/bin/Cargo.toml @@ -30,7 +30,7 @@ tokio-postgres = { workspace = true, features = [ ] } clap = { workspace = true, features = ["derive", "env"] } -tracing = { workspace = true } +tracing = { workspace = true, features = ["log"] } tracing-subscriber = { workspace = true, features = ["fmt", "json", "time"] } serde = { workspace = true, features = ["derive"] } @@ -38,9 +38,6 @@ serde_json = { workspace = true } tokio = { workspace = true, features = ["rt", "macros", "rt-multi-thread"] } thiserror = { workspace = true } -axum = { workspace = true } - -tower-http = { workspace = true, features = ["cors"] } rust_decimal = { workspace = true, features = [ "serde-with-float", @@ -73,9 +70,7 @@ lazy_static = { workspace = true } url = { workspace = true } dotenvy = { workspace = true } panic-message = { workspace = true } -tower = { workspace = true, features = ["util"] } hyper = { workspace = true } -bytes = { workspace = true } cpu-time = { workspace = true } ulid = { workspace = true, features = ["serde", "uuid"] } rust-embed = { workspace = true } diff --git a/catalyst-gateway/bin/src/event_db/types/registration.rs b/catalyst-gateway/bin/src/event_db/types/registration.rs index a46d6c9e5e7..e38c254c976 100644 --- a/catalyst-gateway/bin/src/event_db/types/registration.rs +++ b/catalyst-gateway/bin/src/event_db/types/registration.rs @@ -75,16 +75,6 @@ impl RewardAddress { reward_address, } } - - /// Get the reward address - pub(crate) fn reward_address(&self) -> &str { - &self.reward_address - } - - /// Get the reward payable - pub(crate) fn reward_payable(&self) -> bool { - self.reward_payable - } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/catalyst-gateway/bin/src/event_db/types/search.rs b/catalyst-gateway/bin/src/event_db/types/search.rs index be1fb02ec20..bd28c888e66 100644 --- a/catalyst-gateway/bin/src/event_db/types/search.rs +++ b/catalyst-gateway/bin/src/event_db/types/search.rs @@ -6,10 +6,13 @@ use super::{event::EventSummary, objective::ObjectiveSummary, proposal::Proposal /// The Table to search pub(crate) enum SearchTable { /// Search for events + #[allow(dead_code)] Events, /// Search for objectives + #[allow(dead_code)] Objectives, /// Search for proposals + #[allow(dead_code)] Proposals, } @@ -18,14 +21,19 @@ pub(crate) enum SearchTable { /// The column to search pub(crate) enum SearchColumn { /// Search for the Title + #[allow(dead_code)] Title, /// Search for the Type + #[allow(dead_code)] Type, /// Search for the Description + #[allow(dead_code)] Description, /// Search for the Author + #[allow(dead_code)] Author, /// Search for the Funds + #[allow(dead_code)] Funds, } diff --git a/catalyst-gateway/bin/src/legacy_service/health.rs b/catalyst-gateway/bin/src/legacy_service/health.rs deleted file mode 100644 index 95fa93d3b60..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/health.rs +++ /dev/null @@ -1,93 +0,0 @@ -use axum::{routing::get, Router}; - -use super::handle_result; -use crate::service::Error; - -pub(crate) fn health() -> Router { - Router::new() - .route( - "/health/ready", - get(|| async { handle_result(ready_exec()) }), - ) - .route("/health/live", get(|| async { handle_result(live_exec()) })) -} - -#[allow(clippy::unnecessary_wraps)] -fn ready_exec() -> Result { - tracing::debug!("health ready exec"); - - Ok(true) -} - -#[allow(clippy::unnecessary_wraps)] -fn live_exec() -> Result { - tracing::debug!("health live exec"); - - Ok(true) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use std::sync::Arc; -// -// use axum::{ -// body::{Body, HttpBody}, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use crate::{legacy_service::app, state::State}; -// -// #[tokio::test] -// async fn health_ready_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri("/health/ready".to_string()) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// String::from_utf8(response.into_body().data().await.unwrap().unwrap().to_vec()) -// .unwrap() -// .as_str(), -// r#"true"# -// ); -// } -// -// #[tokio::test] -// async fn health_live_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri("/health/live".to_string()) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// String::from_utf8(response.into_body().data().await.unwrap().unwrap().to_vec()) -// .unwrap() -// .as_str(), -// r#"true"# -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/mod.rs b/catalyst-gateway/bin/src/legacy_service/mod.rs deleted file mode 100644 index 2de610d95d5..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/mod.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Main entrypoint to the Legacy AXUM version of the service -//! This whole module is deprecated, so don't worry if its not documented how we would -//! like. -#![allow(clippy::missing_docs_in_private_items)] -use std::{net::SocketAddr, sync::Arc}; - -use axum::{ - http::{Method, StatusCode}, - response::{IntoResponse, Response}, - Json, Router, -}; -use serde::Serialize; -use tower_http::cors::{Any, CorsLayer}; - -use crate::{ - service::{Error, ErrorMessage}, - state::State, -}; - -mod health; -pub(crate) mod types; -mod v0; -mod v1; - -pub(crate) fn app(state: Arc) -> Router { - // build our application with a route - let v0 = v0::v0(state.clone()); - let v1 = v1::v1(state); - let health = health::health(); - Router::new().nest("/api", v1.merge(v0)).merge(health) -} - -fn cors_layer() -> CorsLayer { - CorsLayer::new() - .allow_methods([Method::GET, Method::POST]) - .allow_origin(Any) - .allow_headers(Any) -} - -async fn run_service(app: Router, addr: &SocketAddr, name: &str) -> Result<(), Error> { - tracing::info!("Starting {name}..."); - tracing::info!("Listening on {addr}"); - - axum::Server::bind(addr) - .serve(app.into_make_service()) - .await - .map_err(|e| Error::CannotRunService(e.to_string()))?; - Ok(()) -} - -/// # Make the Axum web service. -/// -/// ## Arguments -/// -/// `service_addr`: &`SocketAddr` - the address to listen on -/// `metrics_addr`: &`Option` - the address to listen on for metrics -/// `state`: `Arc` - the state -/// -/// ## Errors -/// -/// `Error::CannotRunService` - cannot run the service -/// `Error::EventDbError` - cannot connect to the event db -/// `Error::IoError` - An IO error has occurred. -pub(crate) async fn run(service_addr: &SocketAddr, state: Arc) -> Result<(), Error> { - let cors = cors_layer(); - - let service_app = app(state).layer(cors); - - run_service(service_app, service_addr, "service").await?; - Ok(()) -} - -fn handle_result(res: Result) -> Response { - match res { - Ok(res) => (StatusCode::OK, Json(res)).into_response(), - Err(Error::EventDb(crate::event_db::error::Error::NotFound(error))) => { - (StatusCode::NOT_FOUND, Json(ErrorMessage::new(error))).into_response() - }, - Err(error) => { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(ErrorMessage::new(error.to_string())), - ) - .into_response() - }, - } -} - -// #[cfg(test)] -// pub(crate) mod tests { -// use std::str::FromStr; -// -// use axum::body::HttpBody; -// -// pub(crate) async fn response_body_to_json< -// T: HttpBody>, Error = axum::Error> + Unpin, -// >( -// response: axum::response::Response, -// ) -> Result { -// let data: Vec = response -// .into_body() -// .data() -// .await -// .ok_or("response should have data in a body".to_string())? -// .map_err(|e| e.to_string())? -// .into(); -// -// serde_json::Value::from_str(String::from_utf8(data).map_err(|e| -// e.to_string())?.as_str()) .map_err(|e| e.to_string()) -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/types/ballot.rs b/catalyst-gateway/bin/src/legacy_service/types/ballot.rs deleted file mode 100644 index 7c5de2a229d..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/ballot.rs +++ /dev/null @@ -1,280 +0,0 @@ -use serde::{ser::Serializer, Serialize}; - -use super::SerdeType; -use crate::event_db::types::{ - ballot::{ - Ballot, BallotType, GroupVotePlans, ObjectiveBallots, ObjectiveChoices, ProposalBallot, - VotePlan, - }, - objective::ObjectiveId, - proposal::ProposalId, - registration::VoterGroupId, -}; - -impl Serialize for SerdeType<&ObjectiveChoices> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&BallotType> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&VotePlan> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VotePlanSerde<'a> { - chain_proposal_index: i64, - #[serde(skip_serializing_if = "Option::is_none")] - group: Option>, - ballot_type: SerdeType<&'a BallotType>, - chain_voteplan_id: &'a String, - #[serde(skip_serializing_if = "Option::is_none")] - encryption_key: &'a Option, - } - VotePlanSerde { - chain_proposal_index: self.chain_proposal_index, - group: self.group.as_ref().map(SerdeType), - ballot_type: SerdeType(&self.ballot_type), - chain_voteplan_id: &self.chain_voteplan_id, - encryption_key: &self.encryption_key, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&GroupVotePlans> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 - .0 - .iter() - .map(SerdeType) - .collect::>() - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Ballot> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct BallotSerde<'a> { - choices: SerdeType<&'a ObjectiveChoices>, - voteplans: SerdeType<&'a GroupVotePlans>, - } - BallotSerde { - choices: SerdeType(&self.choices), - voteplans: SerdeType(&self.voteplans), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ProposalBallot> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ProposalBallotSerde<'a> { - proposal_id: SerdeType<&'a ProposalId>, - ballot: SerdeType<&'a Ballot>, - } - ProposalBallotSerde { - proposal_id: SerdeType(&self.proposal_id), - ballot: SerdeType(&self.ballot), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ObjectiveBallots> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ObjectiveBallotsSerde<'a> { - objective_id: SerdeType<&'a ObjectiveId>, - ballots: Vec>, - } - ObjectiveBallotsSerde { - objective_id: SerdeType(&self.objective_id), - ballots: self.ballots.iter().map(SerdeType).collect(), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - use crate::event_db::types::{ - ballot::{BallotType, GroupVotePlans, ObjectiveChoices}, - objective::ObjectiveId, - proposal::ProposalId, - registration::VoterGroupId, - }; - - #[test] - fn vote_plan_json_test() { - let vote_plan = SerdeType(VotePlan { - chain_proposal_index: 1, - group: Some(VoterGroupId("rep".to_string())), - ballot_type: BallotType("public".to_string()), - chain_voteplan_id: "chain_voteplan_id 1".to_string(), - encryption_key: Some("encryption_key 1".to_string()), - }); - - let json = serde_json::to_value(vote_plan).unwrap(); - assert_eq!( - json, - json!( - { - "chain_proposal_index": 1, - "group": "rep", - "ballot_type": "public", - "chain_voteplan_id": "chain_voteplan_id 1", - "encryption_key": "encryption_key 1" - } - ) - ); - - let vote_plan = SerdeType(VotePlan { - chain_proposal_index: 1, - group: None, - ballot_type: BallotType("public".to_string()), - chain_voteplan_id: "chain_voteplan_id 1".to_string(), - encryption_key: None, - }); - - let json = serde_json::to_value(vote_plan).unwrap(); - assert_eq!( - json, - json!( - { - "chain_proposal_index": 1, - "ballot_type": "public", - "chain_voteplan_id": "chain_voteplan_id 1", - } - ) - ); - } - - #[test] - fn ballot_json_test() { - let ballot = SerdeType(Ballot { - choices: ObjectiveChoices(vec![]), - voteplans: GroupVotePlans(vec![]), - }); - - let json = serde_json::to_value(ballot).unwrap(); - assert_eq!( - json, - json!( - { - "choices": [], - "voteplans": [] - } - ) - ); - } - - #[test] - fn proposal_ballot_json_test() { - let ballot = SerdeType(ProposalBallot { - proposal_id: ProposalId(1), - ballot: Ballot { - choices: ObjectiveChoices(vec![]), - voteplans: GroupVotePlans(vec![]), - }, - }); - - let json = serde_json::to_value(ballot).unwrap(); - assert_eq!( - json, - json!( - { - "proposal_id": 1, - "ballot": { - "choices": [], - "voteplans": [] - } - } - ) - ); - } - - #[test] - fn objective_ballots_json_test() { - let ballot = SerdeType(ObjectiveBallots { - objective_id: ObjectiveId(1), - ballots: vec![], - }); - - let json = serde_json::to_value(ballot).unwrap(); - assert_eq!( - json, - json!( - { - "objective_id": 1, - "ballots": [] - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/event.rs b/catalyst-gateway/bin/src/legacy_service/types/event.rs deleted file mode 100644 index b9a09c52d58..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/event.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(deprecated)] -use chrono::{DateTime, Utc}; -use rust_decimal::prelude::ToPrimitive; -use serde::{ - de::Deserializer, - ser::{Error as _, Serializer}, - Deserialize, Serialize, -}; - -use super::{serialize_option_datetime_as_rfc3339, SerdeType}; -use crate::event_db::types::event::{ - Event, EventDetails, EventGoal, EventId, EventRegistration, EventSchedule, EventSummary, - VotingPowerAlgorithm, VotingPowerSettings, -}; - -impl Serialize for SerdeType<&EventId> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - Ok(EventId(i32::deserialize(deserializer)?).into()) - } -} - -impl Serialize for SerdeType<&EventSummary> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct EventSummarySerde<'a> { - id: SerdeType<&'a EventId>, - name: &'a String, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - starts: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - ends: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - reg_checked: &'a Option>, - #[serde(rename = "final")] - is_final: bool, - } - EventSummarySerde { - id: SerdeType(&self.id), - name: &self.name, - starts: &self.starts, - ends: &self.ends, - reg_checked: &self.reg_checked, - is_final: self.is_final, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&VotingPowerAlgorithm> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - match self.0 { - VotingPowerAlgorithm::ThresholdStakedADA => { - "threshold_staked_ADA".serialize(serializer) - }, - } - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&VotingPowerSettings> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VotingPowerSettingsSerde<'a> { - alg: SerdeType<&'a VotingPowerAlgorithm>, - #[serde(skip_serializing_if = "Option::is_none")] - min_ada: Option, - #[serde(skip_serializing_if = "Option::is_none")] - max_pct: Option, - } - VotingPowerSettingsSerde { - alg: SerdeType(&self.alg), - min_ada: self.min_ada, - max_pct: if let Some(max_pct) = &self.max_pct { - Some( - max_pct - .to_f64() - .ok_or_else(|| S::Error::custom("cannot decimal convert to f64"))?, - ) - } else { - None - }, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&EventRegistration> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct EventRegistrationSerde<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - purpose: Option, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - deadline: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - taken: &'a Option>, - } - EventRegistrationSerde { - purpose: self.purpose, - deadline: &self.deadline, - taken: &self.taken, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&EventGoal> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct EventGoalSerde<'a> { - idx: i32, - name: &'a String, - } - EventGoalSerde { - idx: self.idx, - name: &self.name, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&EventSchedule> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct EventScheduleSerde<'a> { - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - insight_sharing: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - proposal_submission: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - refine_proposals: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - finalize_proposals: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - proposal_assessment: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - assessment_qa_start: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - voting: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - tallying: &'a Option>, - #[serde( - skip_serializing_if = "Option::is_none", - serialize_with = "serialize_option_datetime_as_rfc3339" - )] - tallying_end: &'a Option>, - } - EventScheduleSerde { - insight_sharing: &self.insight_sharing, - proposal_submission: &self.proposal_submission, - refine_proposals: &self.refine_proposals, - finalize_proposals: &self.finalize_proposals, - proposal_assessment: &self.proposal_assessment, - assessment_qa_start: &self.assessment_qa_start, - voting: &self.voting, - tallying: &self.tallying, - tallying_end: &self.tallying_end, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&EventDetails> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct EventDetailsSerde<'a> { - voting_power: SerdeType<&'a VotingPowerSettings>, - registration: SerdeType<&'a EventRegistration>, - schedule: SerdeType<&'a EventSchedule>, - goals: Vec>, - } - EventDetailsSerde { - voting_power: SerdeType(&self.voting_power), - registration: SerdeType(&self.registration), - schedule: SerdeType(&self.schedule), - goals: self.goals.iter().map(SerdeType).collect(), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Event> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - pub(crate) struct EventSerde<'a> { - #[serde(flatten)] - summary: SerdeType<&'a EventSummary>, - #[serde(flatten)] - details: SerdeType<&'a EventDetails>, - } - - let val = EventSerde { - summary: SerdeType(&self.summary), - details: SerdeType(&self.details), - }; - val.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use chrono::{DateTime, NaiveDateTime, Utc}; - use rust_decimal::Decimal; - use serde_json::json; - - use super::*; - - #[test] - fn event_id_json_test() { - let event_id = SerdeType(EventId(1)); - - let json = serde_json::to_value(&event_id).unwrap(); - assert_eq!(json, json!(1)); - - let expected: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(expected, event_id); - } - - #[test] - fn event_summary_json_test() { - let event_summary = SerdeType(EventSummary { - id: EventId(1), - name: "Fund 10".to_string(), - starts: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - ends: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - reg_checked: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - is_final: true, - }); - - let json = serde_json::to_value(event_summary).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "name": "Fund 10", - "starts": "1970-01-01T00:00:00+00:00", - "ends": "1970-01-01T00:00:00+00:00", - "final": true, - "reg_checked": "1970-01-01T00:00:00+00:00", - } - ) - ); - - let event_summary = SerdeType(EventSummary { - id: EventId(1), - name: "Fund 10".to_string(), - starts: None, - ends: None, - reg_checked: None, - is_final: true, - }); - - let json = serde_json::to_value(event_summary).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "name": "Fund 10", - "final": true, - } - ) - ); - } - - #[test] - fn voting_power_algorithm_json_test() { - let voting_power_algorithm = SerdeType(VotingPowerAlgorithm::ThresholdStakedADA); - - let json = serde_json::to_value(voting_power_algorithm).unwrap(); - assert_eq!(json, json!("threshold_staked_ADA")); - } - - #[test] - fn voting_power_settings_json_test() { - let voting_power_settings = SerdeType(VotingPowerSettings { - alg: VotingPowerAlgorithm::ThresholdStakedADA, - min_ada: Some(500), - max_pct: Some(Decimal::new(123, 2)), - }); - - let json = serde_json::to_value(voting_power_settings).unwrap(); - assert_eq!( - json, - json!( - { - "alg": "threshold_staked_ADA", - "min_ada": 500, - "max_pct": 1.23 - } - ) - ); - - let voting_power_settings = SerdeType(VotingPowerSettings { - alg: VotingPowerAlgorithm::ThresholdStakedADA, - min_ada: None, - max_pct: None, - }); - - let json = serde_json::to_value(voting_power_settings).unwrap(); - assert_eq!( - json, - json!( - { - "alg": "threshold_staked_ADA", - } - ) - ); - } - - #[test] - fn event_registration_json_test() { - let event_registration = SerdeType(EventRegistration { - purpose: Some(1), - deadline: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - taken: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }); - - let json = serde_json::to_value(event_registration).unwrap(); - assert_eq!( - json, - json!( - { - "purpose": 1, - "deadline": "1970-01-01T00:00:00+00:00", - "taken": "1970-01-01T00:00:00+00:00", - } - ) - ); - - let event_registration = SerdeType(EventRegistration { - purpose: None, - deadline: None, - taken: None, - }); - - let json = serde_json::to_value(event_registration).unwrap(); - assert_eq!(json, json!({})); - } - - #[test] - fn event_goal_json_test() { - let event_goal = SerdeType(EventGoal { - idx: 1, - name: "Fund 10".to_string(), - }); - - let json = serde_json::to_value(event_goal).unwrap(); - assert_eq!( - json, - json!( - { - "idx": 1, - "name": "Fund 10", - } - ) - ); - } - - #[test] - fn event_schedule_json_test() { - let event_schedule = SerdeType(EventSchedule { - insight_sharing: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_submission: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - refine_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - finalize_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_assessment: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - assessment_qa_start: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - voting: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying_end: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }); - - let json = serde_json::to_value(event_schedule).unwrap(); - assert_eq!( - json, - json!( - { - "insight_sharing": "1970-01-01T00:00:00+00:00", - "proposal_submission": "1970-01-01T00:00:00+00:00", - "refine_proposals": "1970-01-01T00:00:00+00:00", - "finalize_proposals": "1970-01-01T00:00:00+00:00", - "proposal_assessment": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "voting": "1970-01-01T00:00:00+00:00", - "tallying": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - } - ) - ); - - let event_schedule = SerdeType(EventSchedule { - insight_sharing: None, - proposal_submission: None, - refine_proposals: None, - finalize_proposals: None, - proposal_assessment: None, - assessment_qa_start: None, - voting: None, - tallying: None, - tallying_end: None, - }); - - let json = serde_json::to_value(event_schedule).unwrap(); - assert_eq!(json, json!({})); - } - - #[test] - fn event_details_json_test() { - let event_details = SerdeType(EventDetails { - voting_power: VotingPowerSettings { - alg: VotingPowerAlgorithm::ThresholdStakedADA, - min_ada: Some(500), - max_pct: Some(Decimal::new(123, 2)), - }, - registration: EventRegistration { - purpose: Some(1), - deadline: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - taken: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }, - schedule: EventSchedule { - insight_sharing: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_submission: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - refine_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - finalize_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_assessment: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - assessment_qa_start: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - voting: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying_end: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }, - goals: vec![], - }); - - let json = serde_json::to_value(event_details).unwrap(); - assert_eq!( - json, - json!( - { - "voting_power": { - "alg": "threshold_staked_ADA", - "min_ada": 500, - "max_pct": 1.23 - }, - "registration": { - "purpose": 1, - "deadline": "1970-01-01T00:00:00+00:00", - "taken": "1970-01-01T00:00:00+00:00", - }, - "schedule": { - "insight_sharing": "1970-01-01T00:00:00+00:00", - "proposal_submission": "1970-01-01T00:00:00+00:00", - "refine_proposals": "1970-01-01T00:00:00+00:00", - "finalize_proposals": "1970-01-01T00:00:00+00:00", - "proposal_assessment": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "voting": "1970-01-01T00:00:00+00:00", - "tallying": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - }, - "goals": [], - } - ) - ); - } - - #[test] - fn event_json_test() { - let event = SerdeType(Event { - summary: EventSummary { - id: EventId(1), - name: "Fund 10".to_string(), - starts: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - ends: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - reg_checked: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - is_final: true, - }, - details: EventDetails { - voting_power: VotingPowerSettings { - alg: VotingPowerAlgorithm::ThresholdStakedADA, - min_ada: Some(500), - max_pct: Some(Decimal::new(123, 2)), - }, - registration: EventRegistration { - purpose: Some(1), - deadline: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - taken: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }, - schedule: EventSchedule { - insight_sharing: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_submission: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - refine_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - finalize_proposals: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - proposal_assessment: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - assessment_qa_start: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - voting: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - tallying_end: Some(DateTime::from_utc(NaiveDateTime::default(), Utc)), - }, - goals: vec![], - }, - }); - - let json = serde_json::to_value(event).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "name": "Fund 10", - "starts": "1970-01-01T00:00:00+00:00", - "ends": "1970-01-01T00:00:00+00:00", - "final": true, - "reg_checked": "1970-01-01T00:00:00+00:00", - "voting_power": { - "alg": "threshold_staked_ADA", - "min_ada": 500, - "max_pct": 1.23 - }, - "registration": { - "purpose": 1, - "deadline": "1970-01-01T00:00:00+00:00", - "taken": "1970-01-01T00:00:00+00:00", - }, - "schedule": { - "insight_sharing": "1970-01-01T00:00:00+00:00", - "proposal_submission": "1970-01-01T00:00:00+00:00", - "refine_proposals": "1970-01-01T00:00:00+00:00", - "finalize_proposals": "1970-01-01T00:00:00+00:00", - "proposal_assessment": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "voting": "1970-01-01T00:00:00+00:00", - "tallying": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - }, - "goals": [], - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/mod.rs b/catalyst-gateway/bin/src/legacy_service/types/mod.rs deleted file mode 100644 index ed33d58b39f..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/mod.rs +++ /dev/null @@ -1,48 +0,0 @@ -use std::ops::Deref; - -use chrono::{DateTime, Utc}; -use serde::Serializer; - -pub(crate) mod ballot; -pub(crate) mod event; -pub(crate) mod objective; -pub(crate) mod proposal; -pub(crate) mod registration; -pub(crate) mod review; -pub(crate) mod search; -pub(crate) mod voting_status; -// DEPRECATED, added as a backward compatibility with the VIT-SS -pub(crate) mod vit_ss; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct SerdeType(pub(crate) T); - -impl From for SerdeType { - fn from(val: T) -> Self { - Self(val) - } -} - -impl Deref for SerdeType { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -pub(crate) fn serialize_datetime_as_rfc3339( - time: &DateTime, serializer: S, -) -> Result { - serializer.serialize_str(&time.to_rfc3339()) -} - -pub(crate) fn serialize_option_datetime_as_rfc3339( - time: &Option>, serializer: S, -) -> Result { - if let Some(time) = time { - serializer.serialize_str(&time.to_rfc3339()) - } else { - serializer.serialize_none() - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/objective.rs b/catalyst-gateway/bin/src/legacy_service/types/objective.rs deleted file mode 100644 index 6a2c43e8a97..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/objective.rs +++ /dev/null @@ -1,383 +0,0 @@ -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use serde_json::Value; - -use super::SerdeType; -use crate::event_db::types::{ - objective::{ - Objective, ObjectiveDetails, ObjectiveId, ObjectiveSummary, ObjectiveType, - RewardDefinition, VoterGroup, - }, - registration::VoterGroupId, -}; - -impl Serialize for SerdeType<&ObjectiveId> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - Ok(ObjectiveId(i32::deserialize(deserializer)?).into()) - } -} - -impl Serialize for SerdeType<&ObjectiveType> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ObjectiveTypeSerde<'a> { - id: &'a String, - description: &'a String, - } - ObjectiveTypeSerde { - id: &self.id, - description: &self.description, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ObjectiveSummary> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ObjectiveSummarySerde<'a> { - id: SerdeType<&'a ObjectiveId>, - #[serde(rename = "type")] - objective_type: SerdeType<&'a ObjectiveType>, - title: &'a String, - description: &'a String, - deleted: bool, - } - ObjectiveSummarySerde { - id: SerdeType(&self.id), - objective_type: SerdeType(&self.objective_type), - title: &self.title, - description: &self.description, - deleted: self.deleted, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&RewardDefinition> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct RewardDefinitionSerde<'a> { - currency: &'a String, - value: i64, - } - RewardDefinitionSerde { - currency: &self.currency, - value: self.value, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&VoterGroup> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VoterGroupSerde<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - group: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - voting_token: &'a Option, - } - VoterGroupSerde { - group: self.group.as_ref().map(SerdeType), - voting_token: &self.voting_token, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ObjectiveDetails> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ObjectiveDetailsSerde<'a> { - groups: Vec>, - #[serde(skip_serializing_if = "Option::is_none")] - reward: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - supplemental: &'a Option, - } - ObjectiveDetailsSerde { - groups: self.groups.iter().map(SerdeType).collect(), - reward: self.reward.as_ref().map(SerdeType), - supplemental: &self.supplemental, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Objective> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - pub(crate) struct ObjectiveSerde<'a> { - #[serde(flatten)] - summary: SerdeType<&'a ObjectiveSummary>, - #[serde(flatten)] - details: SerdeType<&'a ObjectiveDetails>, - } - - let val = ObjectiveSerde { - summary: SerdeType(&self.summary), - details: SerdeType(&self.details), - }; - val.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - use crate::event_db::types::registration::VoterGroupId; - - #[test] - fn objective_id_json_test() { - let objective_id = SerdeType(ObjectiveId(1)); - - let json = serde_json::to_value(&objective_id).unwrap(); - assert_eq!(json, json!(1)); - - let expected: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(expected, objective_id); - } - - #[test] - fn objective_type_json_test() { - let objective_type = SerdeType(ObjectiveType { - id: "catalyst-native".to_string(), - description: "catalyst native type".to_string(), - }); - - let json = serde_json::to_value(objective_type).unwrap(); - assert_eq!( - json, - json!( - { - "id": "catalyst-native", - "description": "catalyst native type", - } - ) - ); - } - - #[test] - fn objective_summary_json_test() { - let objective_summary = SerdeType(ObjectiveSummary { - id: ObjectiveId(1), - - objective_type: ObjectiveType { - id: "catalyst-native".to_string(), - description: "catalyst native type".to_string(), - }, - title: "objective 1".to_string(), - description: "description 1".to_string(), - deleted: false, - }); - - let json = serde_json::to_value(objective_summary).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "type": { - "id": "catalyst-native", - "description": "catalyst native type", - }, - "title": "objective 1", - "description": "description 1", - "deleted": false, - } - ) - ); - } - - #[test] - fn reward_definition_json_test() { - let reward_definition = SerdeType(RewardDefinition { - currency: "ADA".to_string(), - value: 100, - }); - - let json = serde_json::to_value(reward_definition).unwrap(); - assert_eq!( - json, - json!( - { - "currency": "ADA", - "value": 100 - } - ) - ); - } - - #[test] - fn voter_group_json_test() { - let voter_group = SerdeType(VoterGroup { - group: Some(VoterGroupId("group".to_string())), - voting_token: Some("token".to_string()), - }); - - let json = serde_json::to_value(voter_group).unwrap(); - assert_eq!( - json, - json!( - { - "group": "group", - "voting_token": "token" - } - ) - ); - } - - #[test] - fn objective_details_json_test() { - let objective_details = SerdeType(ObjectiveDetails { - groups: vec![VoterGroup { - group: Some(VoterGroupId("group".to_string())), - voting_token: Some("token".to_string()), - }], - reward: Some(RewardDefinition { - currency: "ADA".to_string(), - value: 100, - }), - supplemental: None, - }); - - let json = serde_json::to_value(objective_details).unwrap(); - assert_eq!( - json, - json!( - { - "groups": [ - { - "group": "group", - "voting_token": "token" - } - ], - "reward": { - "currency": "ADA", - "value": 100 - } - } - ) - ); - } - - #[test] - fn objective_json_test() { - let objective = SerdeType(Objective { - summary: ObjectiveSummary { - id: ObjectiveId(1), - - objective_type: ObjectiveType { - id: "catalyst-native".to_string(), - description: "catalyst native type".to_string(), - }, - title: "objective 1".to_string(), - description: "description 1".to_string(), - deleted: false, - }, - details: ObjectiveDetails { - groups: vec![VoterGroup { - group: Some(VoterGroupId("group".to_string())), - voting_token: Some("token".to_string()), - }], - reward: Some(RewardDefinition { - currency: "ADA".to_string(), - value: 100, - }), - supplemental: None, - }, - }); - - let json = serde_json::to_value(objective).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "type": { - "id": "catalyst-native", - "description": "catalyst native type", - }, - "title": "objective 1", - "description": "description 1", - "deleted": false, - "groups": [ - { - "group": "group", - "voting_token": "token" - } - ], - "reward": { - "currency": "ADA", - "value": 100 - } - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/proposal.rs b/catalyst-gateway/bin/src/legacy_service/types/proposal.rs deleted file mode 100644 index b6a9d9d8346..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/proposal.rs +++ /dev/null @@ -1,284 +0,0 @@ -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; -use serde_json::Value; - -use super::SerdeType; -use crate::event_db::types::proposal::{ - Proposal, ProposalDetails, ProposalId, ProposalSummary, ProposerDetails, -}; - -impl Serialize for SerdeType<&ProposalId> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - Ok(ProposalId(i32::deserialize(deserializer)?).into()) - } -} - -impl Serialize for SerdeType<&ProposalSummary> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ProposalSummarySerde<'a> { - id: SerdeType<&'a ProposalId>, - title: &'a String, - summary: &'a String, - deleted: bool, - } - ProposalSummarySerde { - id: SerdeType(&self.id), - title: &self.title, - summary: &self.summary, - deleted: self.deleted, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ProposerDetails> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ProposerDetailsSerde<'a> { - name: &'a String, - email: &'a String, - url: &'a String, - payment_key: &'a String, - } - ProposerDetailsSerde { - name: &self.name, - email: &self.email, - url: &self.url, - payment_key: &self.payment_key, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&ProposalDetails> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ProposalDetailsSerde<'a> { - funds: i64, - url: &'a String, - files: &'a String, - proposer: Vec>, - #[serde(skip_serializing_if = "Option::is_none")] - supplemental: &'a Option, - } - ProposalDetailsSerde { - funds: self.funds, - url: &self.url, - files: &self.files, - proposer: self.proposer.iter().map(SerdeType).collect(), - supplemental: &self.supplemental, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Proposal> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - pub(crate) struct ProposalSerde<'a> { - #[serde(flatten)] - summary: SerdeType<&'a ProposalSummary>, - #[serde(flatten)] - details: SerdeType<&'a ProposalDetails>, - } - - let val = ProposalSerde { - summary: SerdeType(&self.summary), - details: SerdeType(&self.details), - }; - val.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn proposal_id_json_test() { - let proposal_id = SerdeType(ProposalId(1)); - - let json = serde_json::to_value(&proposal_id).unwrap(); - assert_eq!(json, json!(1)); - - let expected: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(expected, proposal_id); - } - - #[test] - fn proposal_summary_json_test() { - let proposal_summary = SerdeType(ProposalSummary { - id: ProposalId(1), - title: "title".to_string(), - summary: "summary".to_string(), - deleted: false, - }); - - let json = serde_json::to_value(proposal_summary).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "title": "title", - "summary": "summary", - "deleted": false, - } - ) - ); - } - - #[test] - fn proposer_details_json_test() { - let proposer_details = SerdeType(ProposerDetails { - name: "proposer name".to_string(), - email: "proposer email".to_string(), - url: "proposer url".to_string(), - payment_key: "proposer payment key".to_string(), - }); - - let json = serde_json::to_value(proposer_details).unwrap(); - assert_eq!( - json, - json!( - { - "name": "proposer name", - "email": "proposer email", - "url": "proposer url", - "payment_key": "proposer payment key", - } - ) - ); - } - - #[test] - fn proposal_details_json_test() { - let proposal_details = SerdeType(ProposalDetails { - funds: 1, - url: "url".to_string(), - files: "files".to_string(), - proposer: vec![], - supplemental: Some(json!({})), - }); - - let json = serde_json::to_value(proposal_details).unwrap(); - assert_eq!( - json, - json!( - { - "funds": 1, - "url": "url", - "files": "files", - "proposer": [], - "supplemental": {} - } - ) - ); - - let proposal_details = SerdeType(ProposalDetails { - funds: 1, - url: "url".to_string(), - files: "files".to_string(), - proposer: vec![], - supplemental: None, - }); - - let json = serde_json::to_value(proposal_details).unwrap(); - assert_eq!( - json, - json!( - { - "funds": 1, - "url": "url", - "files": "files", - "proposer": [], - } - ) - ); - } - - #[test] - fn proposal_json_test() { - let proposal = SerdeType(Proposal { - summary: ProposalSummary { - id: ProposalId(1), - title: "title".to_string(), - summary: "summary".to_string(), - deleted: false, - }, - details: ProposalDetails { - funds: 1, - url: "url".to_string(), - files: "files".to_string(), - proposer: vec![], - supplemental: None, - }, - }); - - let json = serde_json::to_value(proposal).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "title": "title", - "summary": "summary", - "deleted": false, - "funds": 1, - "url": "url", - "files": "files", - "proposer": [], - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/registration.rs b/catalyst-gateway/bin/src/legacy_service/types/registration.rs deleted file mode 100644 index 584db8ccc7c..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/registration.rs +++ /dev/null @@ -1,342 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(deprecated)] - -use chrono::{DateTime, Utc}; -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; - -use super::{serialize_datetime_as_rfc3339, SerdeType}; -use crate::event_db::types::registration::{ - Delegation, Delegator, RewardAddress, Voter, VoterGroupId, VoterInfo, -}; - -impl Serialize for SerdeType<&VoterGroupId> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - self.0 .0.serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - Ok(VoterGroupId(String::deserialize(deserializer)?).into()) - } -} - -impl Serialize for SerdeType<&VoterInfo> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VoterInfoSerde<'a> { - voting_power: i64, - voting_group: SerdeType<&'a VoterGroupId>, - delegations_power: i64, - delegations_count: i64, - voting_power_saturation: f64, - #[serde(skip_serializing_if = "Option::is_none")] - delegator_addresses: &'a Option>, - } - VoterInfoSerde { - voting_power: self.voting_power, - voting_group: SerdeType(&self.voting_group), - delegations_power: self.delegations_power, - delegations_count: self.delegations_count, - voting_power_saturation: self.voting_power_saturation, - delegator_addresses: &self.delegator_addresses, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Voter> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VoterSerde<'a> { - voter_info: SerdeType<&'a VoterInfo>, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - as_at: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - last_updated: &'a DateTime, - #[serde(rename = "final")] - is_final: bool, - } - VoterSerde { - voter_info: SerdeType(&self.voter_info), - as_at: &self.as_at, - last_updated: &self.last_updated, - is_final: self.is_final, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Delegation> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct DelegationSerde<'a> { - voting_key: &'a String, - group: SerdeType<&'a VoterGroupId>, - weight: i32, - value: i64, - } - DelegationSerde { - voting_key: &self.voting_key, - group: SerdeType(&self.group), - weight: self.weight, - value: self.value, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&RewardAddress> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct RewardAddressSerde<'a> { - reward_address: &'a str, - reward_payable: bool, - } - RewardAddressSerde { - reward_address: self.reward_address(), - reward_payable: self.reward_payable(), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Delegator> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct DelegatorSerde<'a> { - delegations: Vec>, - #[serde(flatten)] - reward_address: SerdeType<&'a RewardAddress>, - raw_power: i64, - total_power: i64, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - as_at: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - last_updated: &'a DateTime, - #[serde(rename = "final")] - is_final: bool, - } - DelegatorSerde { - delegations: self.delegations.iter().map(SerdeType).collect(), - reward_address: SerdeType(&self.reward_address), - raw_power: self.raw_power, - total_power: self.total_power, - as_at: &self.as_at, - last_updated: &self.last_updated, - is_final: self.is_final, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use chrono::{DateTime, NaiveDateTime, Utc}; - use serde_json::json; - - use super::*; - use crate::event_db::types::registration::RewardAddress; - - #[test] - fn voter_group_id_json_test() { - let voter_group_id = SerdeType(VoterGroupId("rep".to_string())); - - let json = serde_json::to_value(&voter_group_id).unwrap(); - assert_eq!(json, json!("rep")); - - let expected: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(expected, voter_group_id); - } - - #[test] - fn voter_info_json_test() { - let voter_info = SerdeType(VoterInfo { - voting_power: 100, - voting_group: VoterGroupId("group".to_string()), - delegations_power: 100, - delegations_count: 1, - voting_power_saturation: 1.0, - delegator_addresses: Some(vec!["stake_public_key_1".to_string()]), - }); - - let json = serde_json::to_value(voter_info).unwrap(); - assert_eq!( - json, - json!( - { - "voting_power": 100, - "voting_group": "group", - "delegations_power": 100, - "delegations_count": 1, - "voting_power_saturation": 1.0, - "delegator_addresses": ["stake_public_key_1"] - } - ) - ); - - let voter_info = SerdeType(VoterInfo { - voting_power: 100, - voting_group: VoterGroupId("group".to_string()), - delegations_power: 100, - delegations_count: 1, - voting_power_saturation: 1.0, - delegator_addresses: None, - }); - - let json = serde_json::to_value(voter_info).unwrap(); - assert_eq!( - json, - json!( - { - "voting_power": 100, - "voting_group": "group", - "delegations_power": 100, - "delegations_count": 1, - "voting_power_saturation": 1.0, - } - ) - ); - } - - #[test] - fn voter_json_test() { - let voter = SerdeType(Voter { - voter_info: VoterInfo { - voting_power: 100, - voting_group: VoterGroupId("group".to_string()), - delegations_power: 100, - delegations_count: 1, - voting_power_saturation: 1.0, - delegator_addresses: None, - }, - as_at: DateTime::from_utc(NaiveDateTime::default(), Utc), - last_updated: DateTime::from_utc(NaiveDateTime::default(), Utc), - is_final: true, - }); - - let json = serde_json::to_value(voter).unwrap(); - assert_eq!( - json, - json!( - { - "voter_info": { - "voting_power": 100, - "voting_group": "group", - "delegations_power": 100, - "delegations_count": 1, - "voting_power_saturation": 1.0, - }, - "as_at": "1970-01-01T00:00:00+00:00", - "last_updated": "1970-01-01T00:00:00+00:00", - "final": true - } - ) - ); - } - - #[test] - fn delegation_json_test() { - let delegation = SerdeType(Delegation { - voting_key: "stake_public_key_1".to_string(), - group: VoterGroupId("group".to_string()), - weight: 100, - value: 100, - }); - - let json = serde_json::to_value(delegation).unwrap(); - assert_eq!( - json, - json!( - { - "voting_key": "stake_public_key_1", - "group": "group", - "weight": 100, - "value": 100, - } - ) - ); - } - - #[test] - fn delegator_json_test() { - let delegator = SerdeType(Delegator { - delegations: vec![], - reward_address: RewardAddress::new("stake_public_key_1".to_string()), - raw_power: 100, - total_power: 100, - as_at: DateTime::from_utc(NaiveDateTime::default(), Utc), - last_updated: DateTime::from_utc(NaiveDateTime::default(), Utc), - is_final: true, - }); - - let json = serde_json::to_value(delegator).unwrap(); - assert_eq!( - json, - json!( - { - "delegations": [], - "reward_address": "stake_public_key_1", - "reward_payable": false, - "raw_power": 100, - "total_power": 100, - "as_at": "1970-01-01T00:00:00+00:00", - "last_updated": "1970-01-01T00:00:00+00:00", - "final": true - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/review.rs b/catalyst-gateway/bin/src/legacy_service/types/review.rs deleted file mode 100644 index 04ab7f1d175..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/review.rs +++ /dev/null @@ -1,212 +0,0 @@ -use serde::{ser::Serializer, Serialize}; -use serde_json::Value; - -use super::SerdeType; -use crate::event_db::types::review::{AdvisorReview, Rating, ReviewType}; - -impl Serialize for SerdeType<&ReviewType> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ReviewTypeSerde<'a> { - id: i32, - name: &'a String, - #[serde(skip_serializing_if = "Option::is_none")] - description: &'a Option, - min: i32, - max: i32, - map: &'a Vec, - #[serde(skip_serializing_if = "Option::is_none")] - note: Option, - #[serde(skip_serializing_if = "Option::is_none")] - group: &'a Option, - } - ReviewTypeSerde { - id: self.id, - name: &self.name, - description: &self.description, - min: self.min, - max: self.max, - map: &self.map, - note: self.note, - group: &self.group, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Rating> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct RatingSerde<'a> { - review_type: i32, - score: i32, - #[serde(skip_serializing_if = "Option::is_none")] - note: &'a Option, - } - RatingSerde { - review_type: self.review_type, - score: self.score, - note: &self.note, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&AdvisorReview> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct AdvisorReviewSerde<'a> { - assessor: &'a String, - ratings: Vec>, - } - AdvisorReviewSerde { - assessor: &self.assessor, - ratings: self.ratings.iter().map(SerdeType).collect(), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn review_type_json_test() { - let review_type = SerdeType(ReviewType { - id: 1, - name: "name".to_string(), - description: Some("description".to_string()), - min: 1, - max: 2, - note: Some(true), - map: vec![], - group: Some("group".to_string()), - }); - - let json = serde_json::to_value(review_type).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "name": "name", - "description": "description", - "min": 1, - "max": 2, - "note": true, - "map": [], - "group": "group", - } - ) - ); - - let review_type = SerdeType(ReviewType { - id: 1, - name: "name".to_string(), - description: None, - min: 1, - max: 2, - note: None, - map: vec![], - group: None, - }); - - let json = serde_json::to_value(review_type).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "name": "name", - "min": 1, - "max": 2, - "map": [], - } - ) - ); - } - - #[test] - fn rating_json_test() { - let rating = SerdeType(Rating { - review_type: 1, - score: 1, - note: Some("note".to_string()), - }); - - let json = serde_json::to_value(rating).unwrap(); - assert_eq!( - json, - json!( - { - "review_type": 1, - "score": 1, - "note": "note", - } - ) - ); - - let rating = SerdeType(Rating { - review_type: 1, - score: 1, - note: None, - }); - - let json = serde_json::to_value(rating).unwrap(); - assert_eq!( - json, - json!( - { - "review_type": 1, - "score": 1, - } - ) - ); - } - - #[test] - fn advisor_review_json_test() { - let advisor_review = SerdeType(AdvisorReview { - assessor: "alice".to_string(), - ratings: vec![], - }); - - let json = serde_json::to_value(advisor_review).unwrap(); - assert_eq!( - json, - json!( - { - "assessor": "alice", - "ratings": [], - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/search.rs b/catalyst-gateway/bin/src/legacy_service/types/search.rs deleted file mode 100644 index d2032f7dae6..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/search.rs +++ /dev/null @@ -1,302 +0,0 @@ -use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; - -use super::SerdeType; -use crate::event_db::types::search::{ - SearchColumn, SearchConstraint, SearchOrderBy, SearchQuery, SearchResult, SearchTable, - ValueResults, -}; - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - #[derive(Deserialize)] - #[serde(rename_all = "kebab-case")] - enum SearchTableSerde { - Events, - Objectives, - Proposals, - } - match SearchTableSerde::deserialize(deserializer)? { - SearchTableSerde::Events => Ok(SerdeType(SearchTable::Events)), - SearchTableSerde::Objectives => Ok(SerdeType(SearchTable::Objectives)), - SearchTableSerde::Proposals => Ok(SerdeType(SearchTable::Proposals)), - } - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - #[derive(Deserialize)] - #[serde(rename_all = "kebab-case")] - enum SearchColumnSerde { - Title, - Type, - Description, - Author, - Funds, - } - match SearchColumnSerde::deserialize(deserializer)? { - SearchColumnSerde::Title => Ok(SerdeType(SearchColumn::Title)), - SearchColumnSerde::Type => Ok(SerdeType(SearchColumn::Type)), - SearchColumnSerde::Description => Ok(SerdeType(SearchColumn::Description)), - SearchColumnSerde::Author => Ok(SerdeType(SearchColumn::Author)), - SearchColumnSerde::Funds => Ok(SerdeType(SearchColumn::Funds)), - } - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - #[derive(Deserialize)] - struct SearchConstraintSerde { - column: SerdeType, - search: String, - } - let SearchConstraintSerde { column, search } = - SearchConstraintSerde::deserialize(deserializer)?; - Ok(SerdeType(SearchConstraint { - column: column.0, - search, - })) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - #[derive(Deserialize)] - struct SearchOrderBySerde { - pub(crate) column: SerdeType, - #[serde(default)] - pub(crate) descending: bool, - } - let SearchOrderBySerde { column, descending } = - SearchOrderBySerde::deserialize(deserializer)?; - Ok(SerdeType(SearchOrderBy { - column: column.0, - descending, - })) - } -} - -impl<'de> Deserialize<'de> for SerdeType { - fn deserialize(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> { - #[derive(Deserialize)] - struct SearchQuerySerde { - pub(crate) table: SerdeType, - #[serde(default)] - pub(crate) filter: Vec>, - #[serde(default)] - pub(crate) order_by: Vec>, - } - let SearchQuerySerde { - table, - filter, - order_by, - } = SearchQuerySerde::deserialize(deserializer)?; - Ok(SerdeType(SearchQuery { - table: table.0, - filter: filter.into_iter().map(|val| val.0).collect(), - order_by: order_by.into_iter().map(|val| val.0).collect(), - })) - } -} - -impl Serialize for SerdeType<&ValueResults> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - match self.0 { - ValueResults::Events(events) => { - events - .iter() - .map(SerdeType) - .collect::>() - .serialize(serializer) - }, - ValueResults::Objectives(events) => { - events - .iter() - .map(SerdeType) - .collect::>() - .serialize(serializer) - }, - ValueResults::Proposals(events) => { - events - .iter() - .map(SerdeType) - .collect::>() - .serialize(serializer) - }, - } - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&SearchResult> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct SearchResultSerde<'a> { - total: i64, - #[serde(skip_serializing_if = "Option::is_none")] - results: Option>, - } - SearchResultSerde { - total: self.total, - results: self.results.as_ref().map(SerdeType), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn search_table_json_test() { - let json = json!("events"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchTable::Events)); - - let json = json!("objectives"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchTable::Objectives)); - - let json = json!("proposals"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchTable::Proposals)); - } - - #[test] - fn search_column_json_test() { - let json = json!("title"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchColumn::Title)); - - let json = json!("type"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchColumn::Type)); - - let json = json!("description"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchColumn::Description)); - - let json = json!("author"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchColumn::Author)); - - let json = json!("funds"); - let search_table: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!(search_table, SerdeType(SearchColumn::Funds)); - } - - #[test] - fn search_constraint_json_test() { - let json = json!({ - "column": "title", - "search": "search 1" - }); - let search_constraint: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!( - search_constraint, - SerdeType(SearchConstraint { - column: SearchColumn::Title, - search: "search 1".to_string() - }) - ); - } - - #[test] - fn search_order_by_json_test() { - let json = json!({ - "column": "title", - "descending": true - }); - let search_order_by: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!( - search_order_by, - SerdeType(SearchOrderBy { - column: SearchColumn::Title, - descending: true, - }) - ); - - let json = json!({ - "column": "title", - }); - let search_order_by: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!( - search_order_by, - SerdeType(SearchOrderBy { - column: SearchColumn::Title, - descending: false, - }) - ); - } - - #[test] - fn search_query_json_test() { - let json = json!({ - "table": "events", - "filter": [ - { - "column": "title", - "search": "search 1" - } - ], - "order_by": [ - { - "column": "title", - "descending": true - } - ] - }); - let search_query: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!( - search_query, - SerdeType(SearchQuery { - table: SearchTable::Events, - filter: vec![SearchConstraint { - column: SearchColumn::Title, - search: "search 1".to_string() - }], - order_by: vec![SearchOrderBy { - column: SearchColumn::Title, - descending: true - }] - }) - ); - - let json = json!({ - "table": "events", - }); - let search_query: SerdeType = serde_json::from_value(json).unwrap(); - assert_eq!( - search_query, - SerdeType(SearchQuery { - table: SearchTable::Events, - filter: vec![], - order_by: vec![] - }) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/challenge.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/challenge.rs deleted file mode 100644 index 7684ae955e0..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/challenge.rs +++ /dev/null @@ -1,123 +0,0 @@ -use serde::{ser::Serializer, Serialize}; - -use super::super::SerdeType; -use crate::event_db::types::vit_ss::challenge::{Challenge, ChallengeHighlights}; - -impl Serialize for SerdeType<&ChallengeHighlights> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ChallengeHighlightsSerde<'a> { - sponsor: &'a String, - } - ChallengeHighlightsSerde { - sponsor: &self.sponsor, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Challenge> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct ChallengeSerde<'a> { - internal_id: i32, - id: i32, - challenge_type: &'a String, - title: &'a String, - description: &'a String, - rewards_total: i64, - proposers_rewards: i64, - fund_id: i32, - challenge_url: &'a String, - highlights: Option>, - } - ChallengeSerde { - internal_id: self.internal_id, - id: self.id, - challenge_type: &self.challenge_type, - title: &self.title, - description: &self.description, - rewards_total: self.rewards_total, - proposers_rewards: self.proposers_rewards, - fund_id: self.fund_id, - challenge_url: &self.challenge_url, - highlights: self.highlights.as_ref().map(SerdeType), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn challenge_highlights_json_test() { - let highlights = SerdeType(ChallengeHighlights { - sponsor: "sponsor 1".to_string(), - }); - - let json = serde_json::to_value(highlights).unwrap(); - assert_eq!( - json, - json!( - { - "sponsor": "sponsor 1", - } - ) - ); - } - - #[test] - fn challenge_json_test() { - let challenge = SerdeType(Challenge { - internal_id: 1, - id: 1, - challenge_type: "catalyst-simple".to_string(), - title: "title 1".to_string(), - description: "description 1".to_string(), - rewards_total: 1, - proposers_rewards: 1, - fund_id: 1, - challenge_url: "url 1".to_string(), - highlights: None, - }); - - let json = serde_json::to_value(challenge).unwrap(); - assert_eq!( - json, - json!( - { - "internal_id": 1, - "id": 1, - "challenge_type": "catalyst-simple", - "title": "title 1", - "description": "description 1", - "rewards_total": 1, - "proposers_rewards": 1, - "fund_id": 1, - "challenge_url": "url 1", - "highlights": null - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/fund.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/fund.rs deleted file mode 100644 index d653ca66d53..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/fund.rs +++ /dev/null @@ -1,395 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(deprecated)] - -use chrono::{DateTime, Utc}; -use serde::{ser::Serializer, Serialize}; - -use super::super::{serialize_datetime_as_rfc3339, SerdeType}; -use crate::event_db::types::vit_ss::{ - challenge::Challenge, - fund::{Fund, FundNextInfo, FundStageDates, FundWithNext}, - goal::Goal, - group::Group, - vote_plan::Voteplan, -}; - -impl Serialize for SerdeType<&FundStageDates> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct FundStageDatesSerde<'a> { - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - insight_sharing_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - proposal_submission_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - refine_proposals_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - finalize_proposals_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - proposal_assessment_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - assessment_qa_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - snapshot_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - voting_start: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - voting_end: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - tallying_end: &'a DateTime, - } - FundStageDatesSerde { - insight_sharing_start: &self.insight_sharing_start, - proposal_submission_start: &self.proposal_submission_start, - refine_proposals_start: &self.refine_proposals_start, - finalize_proposals_start: &self.finalize_proposals_start, - proposal_assessment_start: &self.proposal_assessment_start, - assessment_qa_start: &self.assessment_qa_start, - snapshot_start: &self.snapshot_start, - voting_start: &self.voting_start, - voting_end: &self.voting_end, - tallying_end: &self.tallying_end, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&Fund> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct FundSerde<'a> { - id: i32, - fund_name: &'a String, - fund_goal: &'a String, - voting_power_threshold: i64, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - fund_start_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - fund_end_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - next_fund_start_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - registration_snapshot_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - next_registration_snapshot_time: &'a DateTime, - chain_vote_plans: Vec>, - challenges: Vec>, - #[serde(flatten)] - stage_dates: SerdeType<&'a FundStageDates>, - goals: Vec>, - results_url: &'a String, - survey_url: &'a String, - groups: Vec>, - } - FundSerde { - id: self.id, - fund_name: &self.fund_name, - fund_goal: &self.fund_goal, - voting_power_threshold: self.voting_power_threshold, - fund_start_time: &self.fund_start_time, - fund_end_time: &self.fund_end_time, - next_fund_start_time: &self.next_fund_start_time, - registration_snapshot_time: &self.registration_snapshot_time, - next_registration_snapshot_time: &self.next_registration_snapshot_time, - chain_vote_plans: self.chain_vote_plans.iter().map(SerdeType).collect(), - challenges: self.challenges.iter().map(SerdeType).collect(), - stage_dates: SerdeType(&self.stage_dates), - goals: self.goals.iter().map(SerdeType).collect(), - results_url: &self.results_url, - survey_url: &self.survey_url, - groups: self.groups.iter().map(SerdeType).collect(), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&FundNextInfo> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct FundNextInfoSerde<'a> { - id: i32, - fund_name: &'a String, - #[serde(flatten)] - stage_dates: SerdeType<&'a FundStageDates>, - } - FundNextInfoSerde { - id: self.id, - fund_name: &self.fund_name, - stage_dates: SerdeType(&self.stage_dates), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -impl Serialize for SerdeType<&FundWithNext> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct FundWithNextSerde<'a> { - #[serde(flatten)] - fund: SerdeType<&'a Fund>, - #[serde(skip_serializing_if = "Option::is_none")] - next: Option>, - } - FundWithNextSerde { - fund: SerdeType(&self.fund), - next: self.next.as_ref().map(SerdeType), - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use chrono::{DateTime, NaiveDateTime, Utc}; - use serde_json::json; - - use super::*; - - #[test] - fn fund_stage_dates_json_test() { - let fund_stage_dates = SerdeType(FundStageDates { - insight_sharing_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_submission_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - refine_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - finalize_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_assessment_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - assessment_qa_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - snapshot_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - tallying_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - }); - - let json = serde_json::to_value(fund_stage_dates).unwrap(); - assert_eq!( - json, - json!( - { - "insight_sharing_start": "1970-01-01T00:00:00+00:00", - "proposal_submission_start": "1970-01-01T00:00:00+00:00", - "refine_proposals_start": "1970-01-01T00:00:00+00:00", - "finalize_proposals_start": "1970-01-01T00:00:00+00:00", - "proposal_assessment_start": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "snapshot_start": "1970-01-01T00:00:00+00:00", - "voting_start": "1970-01-01T00:00:00+00:00", - "voting_end": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - } - ) - ); - } - - #[test] - fn fund_json_test() { - let fund = SerdeType(Fund { - id: 1, - fund_name: "test".to_string(), - fund_goal: "test".to_string(), - voting_power_threshold: 1, - fund_start_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - fund_end_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - next_fund_start_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - registration_snapshot_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - next_registration_snapshot_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - chain_vote_plans: vec![], - challenges: vec![], - stage_dates: FundStageDates { - insight_sharing_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_submission_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - refine_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - finalize_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_assessment_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - assessment_qa_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - snapshot_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - tallying_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - }, - goals: vec![], - results_url: "test".to_string(), - survey_url: "test".to_string(), - groups: vec![], - }); - - let json = serde_json::to_value(fund).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "fund_name": "test", - "fund_goal": "test", - "voting_power_threshold": 1, - "fund_start_time": "1970-01-01T00:00:00+00:00", - "fund_end_time": "1970-01-01T00:00:00+00:00", - "next_fund_start_time": "1970-01-01T00:00:00+00:00", - "registration_snapshot_time": "1970-01-01T00:00:00+00:00", - "next_registration_snapshot_time": "1970-01-01T00:00:00+00:00", - "chain_vote_plans": [], - "challenges": [], - "insight_sharing_start": "1970-01-01T00:00:00+00:00", - "proposal_submission_start": "1970-01-01T00:00:00+00:00", - "refine_proposals_start": "1970-01-01T00:00:00+00:00", - "finalize_proposals_start": "1970-01-01T00:00:00+00:00", - "proposal_assessment_start": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "snapshot_start": "1970-01-01T00:00:00+00:00", - "voting_start": "1970-01-01T00:00:00+00:00", - "voting_end": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - "goals": [], - "results_url": "test", - "survey_url": "test", - "groups": [] - } - ) - ); - } - - #[test] - fn fund_next_info_json_test() { - let fund_next_info = SerdeType(FundNextInfo { - id: 1, - fund_name: "test".to_string(), - stage_dates: FundStageDates { - insight_sharing_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_submission_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - refine_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - finalize_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_assessment_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - assessment_qa_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - snapshot_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - tallying_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - }, - }); - - let json = serde_json::to_value(fund_next_info).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "fund_name": "test", - "insight_sharing_start": "1970-01-01T00:00:00+00:00", - "proposal_submission_start": "1970-01-01T00:00:00+00:00", - "refine_proposals_start": "1970-01-01T00:00:00+00:00", - "finalize_proposals_start": "1970-01-01T00:00:00+00:00", - "proposal_assessment_start": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "snapshot_start": "1970-01-01T00:00:00+00:00", - "voting_start": "1970-01-01T00:00:00+00:00", - "voting_end": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - } - ) - ); - } - - #[test] - fn fund_with_next_json_test() { - let fund_with_next = SerdeType(FundWithNext { - fund: Fund { - id: 1, - fund_name: "test".to_string(), - fund_goal: "test".to_string(), - voting_power_threshold: 1, - fund_start_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - fund_end_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - next_fund_start_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - registration_snapshot_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - next_registration_snapshot_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - chain_vote_plans: vec![], - challenges: vec![], - stage_dates: FundStageDates { - insight_sharing_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_submission_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - refine_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - finalize_proposals_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - proposal_assessment_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - assessment_qa_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - snapshot_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_start: DateTime::from_utc(NaiveDateTime::default(), Utc), - voting_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - tallying_end: DateTime::from_utc(NaiveDateTime::default(), Utc), - }, - goals: vec![], - results_url: "test".to_string(), - survey_url: "test".to_string(), - groups: vec![], - }, - next: None, - }); - - let json = serde_json::to_value(fund_with_next).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "fund_name": "test", - "fund_goal": "test", - "voting_power_threshold": 1, - "fund_start_time": "1970-01-01T00:00:00+00:00", - "fund_end_time": "1970-01-01T00:00:00+00:00", - "next_fund_start_time": "1970-01-01T00:00:00+00:00", - "registration_snapshot_time": "1970-01-01T00:00:00+00:00", - "next_registration_snapshot_time": "1970-01-01T00:00:00+00:00", - "chain_vote_plans": [], - "challenges": [], - "insight_sharing_start": "1970-01-01T00:00:00+00:00", - "proposal_submission_start": "1970-01-01T00:00:00+00:00", - "refine_proposals_start": "1970-01-01T00:00:00+00:00", - "finalize_proposals_start": "1970-01-01T00:00:00+00:00", - "proposal_assessment_start": "1970-01-01T00:00:00+00:00", - "assessment_qa_start": "1970-01-01T00:00:00+00:00", - "snapshot_start": "1970-01-01T00:00:00+00:00", - "voting_start": "1970-01-01T00:00:00+00:00", - "voting_end": "1970-01-01T00:00:00+00:00", - "tallying_end": "1970-01-01T00:00:00+00:00", - "goals": [], - "results_url": "test", - "survey_url": "test", - "groups": [] - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/goal.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/goal.rs deleted file mode 100644 index 32c13c4bb38..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/goal.rs +++ /dev/null @@ -1,57 +0,0 @@ -use serde::{ser::Serializer, Serialize}; - -use super::super::SerdeType; -use crate::event_db::types::vit_ss::goal::Goal; - -impl Serialize for SerdeType<&Goal> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct GoalSerde<'a> { - id: i32, - goal_name: &'a String, - fund_id: i32, - } - GoalSerde { - id: self.id, - goal_name: &self.goal_name, - fund_id: self.fund_id, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn goal_json_test() { - let goal = SerdeType(Goal { - id: 1, - goal_name: "goal_name 1".to_string(), - fund_id: 1, - }); - - let json = serde_json::to_value(goal).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "goal_name": "goal_name 1", - "fund_id": 1 - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/group.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/group.rs deleted file mode 100644 index 9b206bb735b..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/group.rs +++ /dev/null @@ -1,57 +0,0 @@ -use serde::{ser::Serializer, Serialize}; - -use super::super::SerdeType; -use crate::event_db::types::vit_ss::group::Group; - -impl Serialize for SerdeType<&Group> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct GroupSerde<'a> { - fund_id: i32, - token_identifier: &'a String, - group_id: &'a String, - } - GroupSerde { - fund_id: self.fund_id, - token_identifier: &self.token_identifier, - group_id: &self.group_id, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn group_json_test() { - let group = SerdeType(Group { - fund_id: 1, - token_identifier: "token_identifier 1".to_string(), - group_id: "group_id 1".to_string(), - }); - - let json = serde_json::to_value(group).unwrap(); - assert_eq!( - json, - json!( - { - "fund_id": 1, - "token_identifier": "token_identifier 1", - "group_id": "group_id 1" - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/mod.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/mod.rs deleted file mode 100644 index a2ec6cf730a..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub(crate) mod challenge; -pub(crate) mod fund; -pub(crate) mod goal; -pub(crate) mod group; -pub(crate) mod vote_plan; diff --git a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/vote_plan.rs b/catalyst-gateway/bin/src/legacy_service/types/vit_ss/vote_plan.rs deleted file mode 100644 index 2214e1cb4b4..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/vit_ss/vote_plan.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(deprecated)] - -use chrono::{DateTime, Utc}; -use serde::{ser::Serializer, Serialize}; - -use super::super::{serialize_datetime_as_rfc3339, SerdeType}; -use crate::event_db::types::vit_ss::vote_plan::Voteplan; - -impl Serialize for SerdeType<&Voteplan> { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VoteplanSerde<'a> { - id: i32, - chain_voteplan_id: &'a String, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - chain_vote_start_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - chain_vote_end_time: &'a DateTime, - #[serde(serialize_with = "serialize_datetime_as_rfc3339")] - chain_committee_end_time: &'a DateTime, - chain_voteplan_payload: &'a String, - chain_vote_encryption_key: &'a String, - fund_id: i32, - token_identifier: &'a String, - } - VoteplanSerde { - id: self.id, - chain_voteplan_id: &self.chain_voteplan_id, - chain_vote_start_time: &self.chain_vote_start_time, - chain_vote_end_time: &self.chain_vote_end_time, - chain_committee_end_time: &self.chain_committee_end_time, - chain_voteplan_payload: &self.chain_voteplan_payload, - chain_vote_encryption_key: &self.chain_vote_encryption_key, - fund_id: self.fund_id, - token_identifier: &self.token_identifier, - } - .serialize(serializer) - } -} - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - SerdeType(&self.0).serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use chrono::NaiveDateTime; - use serde_json::json; - - use super::*; - - #[test] - fn voteplan_json_test() { - let voteplan = SerdeType(Voteplan { - id: 1, - chain_voteplan_id: "chain_voteplan_id 1".to_string(), - chain_vote_start_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - chain_vote_end_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - chain_committee_end_time: DateTime::from_utc(NaiveDateTime::default(), Utc), - chain_voteplan_payload: "chain_voteplan_payload 1".to_string(), - chain_vote_encryption_key: "chain_vote_encryption_key 1".to_string(), - fund_id: 1, - token_identifier: "token_identifier 1".to_string(), - }); - - let json = serde_json::to_value(voteplan).unwrap(); - assert_eq!( - json, - json!( - { - "id": 1, - "chain_voteplan_id": "chain_voteplan_id 1", - "chain_vote_start_time": "1970-01-01T00:00:00+00:00", - "chain_vote_end_time": "1970-01-01T00:00:00+00:00", - "chain_committee_end_time": "1970-01-01T00:00:00+00:00", - "chain_voteplan_payload": "chain_voteplan_payload 1", - "chain_vote_encryption_key": "chain_vote_encryption_key 1", - "fund_id": 1, - "token_identifier": "token_identifier 1", - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/types/voting_status.rs b/catalyst-gateway/bin/src/legacy_service/types/voting_status.rs deleted file mode 100644 index 778a9544e6f..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/types/voting_status.rs +++ /dev/null @@ -1,69 +0,0 @@ -use serde::{ser::Serializer, Serialize}; - -use super::SerdeType; -use crate::event_db::types::{objective::ObjectiveId, voting_status::VotingStatus}; - -impl Serialize for SerdeType { - fn serialize(&self, serializer: S) -> Result - where S: Serializer { - #[derive(Serialize)] - struct VotingStatusSerde<'a> { - objective_id: SerdeType<&'a ObjectiveId>, - open: bool, - #[serde(skip_serializing_if = "Option::is_none")] - settings: Option<&'a String>, - } - VotingStatusSerde { - objective_id: SerdeType(&self.objective_id), - open: self.open, - settings: self.settings.as_ref(), - } - .serialize(serializer) - } -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - use crate::event_db::types::objective::ObjectiveId; - - #[test] - fn voting_status_json_test() { - let voting_status = SerdeType(VotingStatus { - objective_id: ObjectiveId(1), - open: false, - settings: None, - }); - - let json = serde_json::to_value(voting_status).unwrap(); - assert_eq!( - json, - json!( - { - "objective_id": 1, - "open": false, - } - ) - ); - - let voting_status = SerdeType(VotingStatus { - objective_id: ObjectiveId(1), - open: true, - settings: Some("some settings".to_string()), - }); - - let json = serde_json::to_value(voting_status).unwrap(); - assert_eq!( - json, - json!( - { - "objective_id": 1, - "open": true, - "settings": "some settings", - } - ) - ); - } -} diff --git a/catalyst-gateway/bin/src/legacy_service/v0/fund.rs b/catalyst-gateway/bin/src/legacy_service/v0/fund.rs deleted file mode 100644 index 918941618f8..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v0/fund.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(clippy::too_many_lines)] - -use std::sync::Arc; - -use axum::{routing::get, Router}; - -use crate::{ - event_db::types::vit_ss::fund::FundWithNext, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn fund(state: Arc) -> Router { - Router::new().route( - "/fund", - get(|| async { handle_result(fund_exec(state).await) }), - ) -} - -async fn fund_exec(state: Arc) -> Result, Error> { - tracing::debug!("fund_query",); - - let fund = state.event_db.get_fund().await?.into(); - Ok(fund) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn fund_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri("/api/v0/fund".to_string()) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "id": 4, -// "fund_name": "Test Fund 4", -// "fund_goal": "Test Fund 4 description", -// "voting_power_threshold": 1, -// "fund_start_time": "2022-05-01T12:00:00+00:00", -// "fund_end_time": "2024-06-01T12:00:00+00:00", -// "next_fund_start_time": "1970-01-01T00:00:00+00:00", -// "registration_snapshot_time": "2022-03-31T12:00:00+00:00", -// "next_registration_snapshot_time": "1970-01-01T00:00:00+00:00", -// "chain_vote_plans": [ -// { -// "id": 5, -// "chain_voteplan_id": "1", -// "chain_vote_start_time": "2022-05-01T12:00:00+00:00", -// "chain_vote_end_time": "2024-06-01T12:00:00+00:00", -// "chain_committee_end_time": "2024-07-01T12:00:00+00:00", -// "chain_voteplan_payload": "public", -// "chain_vote_encryption_key": "", -// "fund_id": 4, -// "token_identifier": "voting token 3", -// }, -// { -// "id": 6, -// "chain_voteplan_id": "2", -// "chain_vote_start_time": "2022-05-01T12:00:00+00:00", -// "chain_vote_end_time": "2024-06-01T12:00:00+00:00", -// "chain_committee_end_time": "2024-07-01T12:00:00+00:00", -// "chain_voteplan_payload": "public", -// "chain_vote_encryption_key": "", -// "fund_id": 4, -// "token_identifier": "", -// } -// ], -// "challenges": [ -// { -// "internal_id": 3, -// "id": 3, -// "challenge_type": "catalyst-simple", -// "title": "title 3", -// "description": "description 3", -// "rewards_total": 100, -// "proposers_rewards": 100, -// "challenge_url": "objective 3 url", -// "fund_id": 4, -// "highlights": { -// "sponsor": "objective 3 sponsor" -// }, -// }, -// { -// "internal_id": 4, -// "id": 4, -// "challenge_type": "catalyst-native", -// "title": "title 4", -// "description": "description 4", -// "rewards_total": 0, -// "proposers_rewards": 0, -// "challenge_url": "", -// "fund_id": 4, -// "highlights": null, -// } -// ], -// "insight_sharing_start": "2022-03-01T12:00:00+00:00", -// "proposal_submission_start": "2022-03-01T12:00:00+00:00", -// "refine_proposals_start": "2022-03-01T12:00:00+00:00", -// "finalize_proposals_start": "2022-03-01T12:00:00+00:00", -// "proposal_assessment_start": "2022-03-01T12:00:00+00:00", -// "assessment_qa_start": "2022-03-01T12:00:00+00:00", -// "snapshot_start": "2022-03-31T12:00:00+00:00", -// "voting_start": "2022-05-01T12:00:00+00:00", -// "voting_end": "2024-06-01T12:00:00+00:00", -// "tallying_end": "2024-07-01T12:00:00+00:00", -// "goals": [ -// { -// "id": 13, -// "goal_name": "goal 13", -// "fund_id": 4 -// }, -// { -// "id": 14, -// "goal_name": "goal 14", -// "fund_id": 4 -// }, -// { -// "id": 15, -// "goal_name": "goal 15", -// "fund_id": 4 -// }, -// { -// "id": 16, -// "goal_name": "goal 16", -// "fund_id": 4 -// } -// ], -// "groups": [ -// { -// "group_id": "direct", -// "token_identifier": "voting token 3", -// "fund_id": 4, -// } -// ], -// "survey_url": "", -// "results_url": "", -// "next": { -// "id": 5, -// "fund_name": "Test Fund 5", -// "insight_sharing_start": "1970-01-01T00:00:00+00:00", -// "proposal_submission_start": "1970-01-01T00:00:00+00:00", -// "refine_proposals_start": "1970-01-01T00:00:00+00:00", -// "finalize_proposals_start": "1970-01-01T00:00:00+00:00", -// "proposal_assessment_start": "1970-01-01T00:00:00+00:00", -// "assessment_qa_start": "1970-01-01T00:00:00+00:00", -// "snapshot_start": "1970-01-01T00:00:00+00:00", -// "voting_start": "1970-01-01T00:00:00+00:00", -// "voting_end": "1970-01-01T00:00:00+00:00", -// "tallying_end": "1970-01-01T00:00:00+00:00", -// } -// } -// ), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v0/mod.rs b/catalyst-gateway/bin/src/legacy_service/v0/mod.rs deleted file mode 100644 index 6a98b3859fe..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v0/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -use std::sync::Arc; - -use axum::Router; - -use crate::state::State; - -mod fund; - -pub(crate) fn v0(state: Arc) -> Router { - let fund = fund::fund(state); - - Router::new().nest("/v0", fund) -} diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/ballots.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/ballots.rs deleted file mode 100644 index cdb80f86e91..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/ballots.rs +++ /dev/null @@ -1,128 +0,0 @@ -use std::sync::Arc; - -use axum::{extract::Path, routing::get, Router}; - -use crate::{ - event_db::types::{ballot::ObjectiveBallots, event::EventId}, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn ballots(state: Arc) -> Router { - Router::new().route( - "/ballots", - get(move |path| async { handle_result(ballots_exec(path, state).await) }), - ) -} - -async fn ballots_exec( - Path(SerdeType(event)): Path>, state: Arc, -) -> Result>, Error> { - tracing::debug!("ballots_query, event: {0}", event.0,); - - let ballot = state - .event_db - .get_event_ballots(event) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(ballot) -} -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn ballots_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/ballots", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "objective_id": 1, -// "ballots": [ -// { -// "proposal_id": 10, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [ -// { -// "chain_proposal_index": 10, -// "group": "direct", -// "ballot_type": "public", -// "chain_voteplan_id": "1", -// }, -// { -// "chain_proposal_index": 12, -// "group": "rep", -// "ballot_type": "public", -// "chain_voteplan_id": "2", -// } -// ] -// } -// }, -// { -// "proposal_id": 20, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [ -// { -// "chain_proposal_index": 11, -// "group": "direct", -// "ballot_type": "public", -// "chain_voteplan_id": "1", -// }, -// { -// "chain_proposal_index": 13, -// "group": "rep", -// "ballot_type": "public", -// "chain_voteplan_id": "2", -// } -// ] -// } -// }, -// { -// "proposal_id": 30, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [] -// } -// } -// ] -// } -// ]), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/mod.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/mod.rs deleted file mode 100644 index 5cdc9e1d634..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/mod.rs +++ /dev/null @@ -1,340 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(deprecated, clippy::too_many_lines)] - -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; - -use super::LimitOffset; -use crate::{ - event_db::types::event::{Event, EventId, EventSummary}, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -mod ballots; -mod objective; - -pub(crate) fn event(state: Arc) -> Router { - let objective = objective::objective(state.clone()); - let ballots = ballots::ballots(state.clone()); - - Router::new() - .nest( - "/event/:event", - Router::new() - .route( - "/", - get({ - let state = state.clone(); - move |path| async { handle_result(event_exec(path, state).await) } - }), - ) - .merge(objective) - .merge(ballots), - ) - .route( - "/events", - get(move |query| async { handle_result(events_exec(query, state).await) }), - ) -} - -async fn event_exec( - Path(SerdeType(event)): Path>, state: Arc, -) -> Result, Error> { - tracing::debug!("event_exec, event: {0}", event.0); - - let event = state.event_db.get_event(event).await?.into(); - Ok(event) -} - -async fn events_exec( - lim_ofs: Query, state: Arc, -) -> Result>, Error> { - tracing::debug!( - "events_query, limit: {0:?}, offset: {1:?}", - lim_ofs.limit, - lim_ofs.offset - ); - - let events = state - .event_db - .get_events(lim_ofs.limit, lim_ofs.offset) - .await? - .into_iter() - .map(SerdeType) - .collect::>(); - Ok(events) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn event_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true, -// "voting_power": { -// "alg": "threshold_staked_ADA", -// "min_ada": 1, -// "max_pct": 100.0 -// }, -// "registration": { -// "deadline": "2020-03-31T12:00:00+00:00", -// "taken": "2020-03-31T12:00:00+00:00", -// }, -// "schedule": { -// "insight_sharing": "2020-03-01T12:00:00+00:00", -// "proposal_submission": "2020-03-01T12:00:00+00:00", -// "refine_proposals": "2020-03-01T12:00:00+00:00", -// "finalize_proposals": "2020-03-01T12:00:00+00:00", -// "proposal_assessment": "2020-03-01T12:00:00+00:00", -// "assessment_qa_start": "2020-03-01T12:00:00+00:00", -// "voting": "2020-05-01T12:00:00+00:00", -// "tallying": "2020-06-01T12:00:00+00:00", -// "tallying_end": "2020-07-01T12:00:00+00:00", -// }, -// "goals": [ -// { -// "idx": 1, -// "name": "goal 1" -// }, -// { -// "idx": 2, -// "name": "goal 2" -// }, -// { -// "idx": 3, -// "name": "goal 3" -// }, -// { -// "idx": 4, -// "name": "goal 4" -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}", 100)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// -// #[tokio::test] -// async fn events_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri("/api/v1/events".to_string()) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 0, -// "name": "Test Fund", -// "starts": "1970-01-01T00:00:00+00:00", -// "ends": "1970-01-01T00:00:00+00:00", -// "final": true -// }, -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 2, -// "name": "Test Fund 2", -// "starts": "2021-05-01T12:00:00+00:00", -// "ends": "2021-06-01T12:00:00+00:00", -// "reg_checked": "2021-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 3, -// "name": "Test Fund 3", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2022-06-01T12:00:00+00:00", -// "reg_checked": "2022-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// { -// "id": 5, -// "name": "Test Fund 5", -// "final": false -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/events?offset={0}", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 2, -// "name": "Test Fund 2", -// "starts": "2021-05-01T12:00:00+00:00", -// "ends": "2021-06-01T12:00:00+00:00", -// "reg_checked": "2021-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 3, -// "name": "Test Fund 3", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2022-06-01T12:00:00+00:00", -// "reg_checked": "2022-03-31T12:00:00+00:00", -// "final": true, -// }, -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// { -// "id": 5, -// "name": "Test Fund 5", -// "final": false -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/events?limit={0}", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 0, -// "name": "Test Fund", -// "starts": "1970-01-01T00:00:00+00:00", -// "ends": "1970-01-01T00:00:00+00:00", -// "final": true -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/events?limit={0}&offset={1}", 1, 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true, -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/events?offset={0}", 10)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([]) -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/ballots.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/ballots.rs deleted file mode 100644 index 72133645a07..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/ballots.rs +++ /dev/null @@ -1,134 +0,0 @@ -use std::sync::Arc; - -use axum::{extract::Path, routing::get, Router}; - -use crate::{ - event_db::types::{ballot::ProposalBallot, event::EventId, objective::ObjectiveId}, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn ballots(state: Arc) -> Router { - Router::new().route( - "/ballots", - get(move |path| async { handle_result(ballots_exec(path, state).await) }), - ) -} - -async fn ballots_exec( - Path((SerdeType(event), SerdeType(objective))): Path<( - SerdeType, - SerdeType, - )>, - state: Arc, -) -> Result>, Error> { - tracing::debug!( - "ballots_query, event: {0}, objective: {1}", - event.0, - objective.0, - ); - - let ballot = state - .event_db - .get_objective_ballots(event, objective) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(ballot) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn ballots_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objective/{1}/ballots", 1, 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "proposal_id": 10, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [ -// { -// "chain_proposal_index": 10, -// "group": "direct", -// "ballot_type": "public", -// "chain_voteplan_id": "1", -// }, -// { -// "chain_proposal_index": 12, -// "group": "rep", -// "ballot_type": "public", -// "chain_voteplan_id": "2", -// } -// ] -// } -// }, -// { -// "proposal_id": 20, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [ -// { -// "chain_proposal_index": 11, -// "group": "direct", -// "ballot_type": "public", -// "chain_voteplan_id": "1", -// }, -// { -// "chain_proposal_index": 13, -// "group": "rep", -// "ballot_type": "public", -// "chain_voteplan_id": "2", -// } -// ] -// } -// }, -// { -// "proposal_id": 30, -// "ballot": { -// "choices": ["yes", "no"], -// "voteplans": [] -// } -// } -// ] -// ), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/mod.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/mod.rs deleted file mode 100644 index b6606f7ad85..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/mod.rs +++ /dev/null @@ -1,418 +0,0 @@ -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; - -use crate::{ - event_db::types::{event::EventId, objective::Objective, voting_status::VotingStatus}, - legacy_service::{handle_result, types::SerdeType, v1::LimitOffset}, - service::Error, - state::State, -}; - -mod ballots; -mod proposal; -mod review_type; - -pub(crate) fn objective(state: Arc) -> Router { - let proposal = proposal::proposal(state.clone()); - let review_type = review_type::review_type(state.clone()); - let ballots = ballots::ballots(state.clone()); - - Router::new() - .nest( - "/objective/:objective", - proposal.merge(review_type).merge(ballots), - ) - .route("/objectives", { - let state = state.clone(); - get(move |path, query| { - async { handle_result(objectives_exec(path, query, state).await) } - }) - }) - .route( - "/objectives/voting_status", - get(move |path, query| { - async { handle_result(objectives_voting_statuses_exec(path, query, state).await) } - }), - ) -} - -async fn objectives_exec( - Path(SerdeType(event)): Path>, lim_ofs: Query, - state: Arc, -) -> Result>, Error> { - tracing::debug!("objectives_query, event: {0}", event.0); - - let objectives = state - .event_db - .get_objectives(event, lim_ofs.limit, lim_ofs.offset) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(objectives) -} - -// TODO: -// mocked data, will be replaced when we will add this into event-db -fn mocked_voting_status_data() -> (bool, Option) { - use chrono::{Local, Timelike}; - - let settings = serde_json::json!( - { - "purpose": 0, - "ver": 0, - "fees": - { - "constant": 10, - "coefficient": 2, - "certificate": 100 - }, - "discrimination": "production", - "block0_initial_hash": - { - "hash": "baf6b54817cf2a3e865f432c3922d28ac5be641e66662c66d445f141e409183e" - }, - "block0_date": 1_586_637_936, - "slot_duration": 20, - "time_era": - { - "epoch_start": 0, - "slot_start": 0, - "slots_per_epoch": 180 - }, - "transaction_max_expiry_epochs":1 - } - ); - - // Result based on the local time and it changes every 10 minutes - if Local::now().minute() / 10 % 2 == 0 { - (true, Some(settings.to_string())) - } else { - (false, None) - } -} - -async fn objectives_voting_statuses_exec( - Path(SerdeType(event)): Path>, lim_ofs: Query, - state: Arc, -) -> Result>, Error> { - tracing::debug!("objectives_voting_statuses_query, event: {0}", event.0); - - let objectives = state - .event_db - .get_objectives(event, lim_ofs.limit, lim_ofs.offset) - .await?; - - let data = mocked_voting_status_data(); - - let voting_statuses: Vec<_> = objectives - .into_iter() - .map(|objective| { - VotingStatus { - objective_id: objective.summary.id, - open: data.0, - settings: data.1.clone(), - } - .into() - }) - .collect(); - Ok(voting_statuses) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn objectives_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objectives", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 1", -// "description": "description 1", -// "deleted": false, -// "groups": [ -// { -// "group": "direct", -// "voting_token": "voting token 1" -// }, -// { -// "group": "rep", -// "voting_token": "voting token 2" -// } -// ], -// "reward": { -// "currency": "ADA", -// "value": 100 -// }, -// "supplemental": { -// "url":"objective 1 url", -// "sponsor": "objective 1 sponsor", -// "video": "objective 1 video" -// } -// }, -// { -// "id": 2, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 2", -// "description": "description 2", -// "deleted": false, -// "groups": [], -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objectives?limit={1}", 1, 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 1", -// "description": "description 1", -// "deleted": false, -// "groups": [ -// { -// "group": "direct", -// "voting_token": "voting token 1" -// }, -// { -// "group": "rep", -// "voting_token": "voting token 2" -// } -// ], -// "reward": { -// "currency": "ADA", -// "value": 100 -// }, -// "supplemental": { -// "url":"objective 1 url", -// "sponsor": "objective 1 sponsor", -// "video": "objective 1 video" -// } -// }, -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objectives?offset={1}", 1, 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 2, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 2", -// "description": "description 2", -// "deleted": false, -// "groups": [], -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objectives?limit={1}&offset={2}", -// 1, 1, 2 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([]) -// ); -// } -// -// #[tokio::test] -// async fn objectives_voting_status_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let data = mocked_voting_status_data(); -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objectives/voting_status", 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// if let Some(settings) = data.1.clone() { -// serde_json::json!( -// [ -// { -// "objective_id": 1, -// "open": data.0, -// "settings": settings, -// }, -// { -// "objective_id": 2, -// "open": data.0, -// "settings": settings, -// } -// ] -// ) -// } else { -// serde_json::json!( -// [ -// { -// "objective_id": 1, -// "open": data.0, -// }, -// { -// "objective_id": 2, -// "open": data.0, -// } -// ] -// ) -// }, -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objectives/voting_status?limit={1}", -// 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// if let Some(settings) = data.1.clone() { -// serde_json::json!( -// [ -// { -// "objective_id": 1, -// "open": data.0, -// "settings": settings, -// } -// ] -// ) -// } else { -// serde_json::json!( -// [ -// { -// "objective_id": 1, -// "open": data.0, -// } -// ] -// ) -// }, -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objectives/voting_status?offset={1}", -// 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// if let Some(settings) = data.1.clone() { -// serde_json::json!( -// [ -// { -// "objective_id": 2, -// "open": data.0, -// "settings": settings, -// } -// ] -// ) -// } else { -// serde_json::json!( -// [ -// { -// "objective_id": 2, -// "open": data.0, -// } -// ] -// ) -// }, -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objectives/voting_status?limit={1}&offset={2}", -// 1, 1, 2 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([]) -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/ballot.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/ballot.rs deleted file mode 100644 index 8ce5db752db..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/ballot.rs +++ /dev/null @@ -1,117 +0,0 @@ -use std::sync::Arc; - -use axum::{extract::Path, routing::get, Router}; - -use crate::{ - event_db::types::{ - ballot::Ballot, event::EventId, objective::ObjectiveId, proposal::ProposalId, - }, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn ballot(state: Arc) -> Router { - Router::new().route( - "/ballot", - get(move |path| async { handle_result(ballot_exec(path, state).await) }), - ) -} - -async fn ballot_exec( - Path((SerdeType(event), SerdeType(objective), SerdeType(proposal))): Path<( - SerdeType, - SerdeType, - SerdeType, - )>, - state: Arc, -) -> Result, Error> { - tracing::debug!( - "ballot_query, event: {0}, objective: {1}, proposal: {2}", - event.0, - objective.0, - proposal.0, - ); - - let ballot = state - .event_db - .get_ballot(event, objective, proposal) - .await? - .into(); - Ok(ballot) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn ballot_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/ballot", -// 1, 1, 10 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "choices": ["yes", "no"], -// "voteplans": [ -// { -// "chain_proposal_index": 10, -// "group": "direct", -// "ballot_type": "public", -// "chain_voteplan_id": "1", -// }, -// { -// "chain_proposal_index": 12, -// "group": "rep", -// "ballot_type": "public", -// "chain_voteplan_id": "2", -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/ballot", -// 3, 3, 3 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/mod.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/mod.rs deleted file mode 100644 index 5b3ae2c7581..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/mod.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; - -use crate::{ - event_db::types::{ - event::EventId, - objective::ObjectiveId, - proposal::{Proposal, ProposalId, ProposalSummary}, - }, - legacy_service::{handle_result, types::SerdeType, v1::LimitOffset}, - service::Error, - state::State, -}; - -mod ballot; -mod review; - -pub(crate) fn proposal(state: Arc) -> Router { - let review = review::review(state.clone()); - let ballot = ballot::ballot(state.clone()); - - Router::new() - .nest( - "/proposal/:proposal", - Router::new() - .route( - "/", - get({ - let state = state.clone(); - move |path| async { handle_result(proposal_exec(path, state).await) } - }), - ) - .merge(review) - .merge(ballot), - ) - .route( - "/proposals", - get(move |path, query| { - async { handle_result(proposals_exec(path, query, state).await) } - }), - ) -} - -async fn proposals_exec( - Path((SerdeType(event), SerdeType(objective))): Path<( - SerdeType, - SerdeType, - )>, - lim_ofs: Query, state: Arc, -) -> Result>, Error> { - tracing::debug!( - "proposals_query, event:{0} objective: {1}", - event.0, - objective.0 - ); - - let proposals = state - .event_db - .get_proposals(event, objective, lim_ofs.limit, lim_ofs.offset) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(proposals) -} - -async fn proposal_exec( - Path((SerdeType(event), SerdeType(objective), SerdeType(proposal))): Path<( - SerdeType, - SerdeType, - SerdeType, - )>, - state: Arc, -) -> Result, Error> { - tracing::debug!( - "proposal_query, event:{0} objective: {1}, proposal: {2}", - event.0, - objective.0, - proposal.0, - ); - - let proposal = state - .event_db - .get_proposal(event, objective, proposal) - .await? - .into(); - Ok(proposal) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn proposal_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}", -// 1, 1, 10 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false, -// "funds": 100, -// "url": "url.xyz", -// "files": "files.xyz", -// "proposer": [ -// { -// "name": "alice", -// "email": "alice@io", -// "url": "alice.prop.xyz", -// "payment_key": "b7a3c12dc0c8c748ab07525b701122b88bd78f600c76342d27f25e5f92444cde" -// } -// ], -// "supplemental": { -// "brief": "Brief explanation of a proposal", -// "goal": "The goal of the proposal is addressed to meet", -// "importance": "The importance of the proposal", -// } -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}", -// 3, 3, 3 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// -// #[tokio::test] -// async fn proposals_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/event/{0}/objective/{1}/proposals", 1, 1)) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false -// }, -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// { -// "id": 30, -// "title": "title 3", -// "summary": "summary 3", -// "deleted": false -// } -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposals?limit={2}", -// 1, 1, 2 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false -// }, -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposals?offset={2}", -// 1, 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// { -// "id": 30, -// "title": "title 3", -// "summary": "summary 3", -// "deleted": false -// } -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposals?offset={2}&limit={3}", -// 1, 1, 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// ]), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/review.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/review.rs deleted file mode 100644 index b3dbb9ae96f..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/proposal/review.rs +++ /dev/null @@ -1,206 +0,0 @@ -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; - -use crate::{ - event_db::types::{ - event::EventId, objective::ObjectiveId, proposal::ProposalId, review::AdvisorReview, - }, - legacy_service::{handle_result, types::SerdeType, v1::LimitOffset}, - service::Error, - state::State, -}; - -pub(crate) fn review(state: Arc) -> Router { - Router::new().route( - "/reviews", - get(move |path, query| async { handle_result(reviews_exec(path, query, state).await) }), - ) -} - -async fn reviews_exec( - Path((SerdeType(event), SerdeType(objective), SerdeType(proposal))): Path<( - SerdeType, - SerdeType, - SerdeType, - )>, - lim_ofs: Query, state: Arc, -) -> Result>, Error> { - tracing::debug!( - "reviews_query, event:{0} objective: {1}, proposal: {2}", - event.0, - objective.0, - proposal.0, - ); - - let reviews = state - .event_db - .get_reviews(event, objective, proposal, lim_ofs.limit, lim_ofs.offset) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(reviews) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn reviews_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/reviews", -// 1, 1, 10 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "assessor": "assessor 1", -// "ratings": [ -// { -// "review_type": 1, -// "score": 10, -// "note": "note 1" -// }, -// { -// "review_type": 2, -// "score": 15, -// "note": "note 2" -// }, -// { -// "review_type": 5, -// "score": 20, -// "note": "note 3" -// } -// ] -// }, -// { -// "assessor": "assessor 2", -// "ratings": [] -// }, -// { -// "assessor": "assessor 3", -// "ratings": [] -// } -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/reviews?limit={3}", -// 1, 1, 10, 2 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "assessor": "assessor 1", -// "ratings": [ -// { -// "review_type": 1, -// "score": 10, -// "note": "note 1" -// }, -// { -// "review_type": 2, -// "score": 15, -// "note": "note 2" -// }, -// { -// "review_type": 5, -// "score": 20, -// "note": "note 3" -// } -// ] -// }, -// { -// "assessor": "assessor 2", -// "ratings": [] -// }, -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/reviews?offset={3}", -// 1, 1, 10, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "assessor": "assessor 2", -// "ratings": [] -// }, -// { -// "assessor": "assessor 3", -// "ratings": [] -// } -// ]), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/proposal/{2}/reviews?limit={3}&offset={4}", -// 1, 1, 10, 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!([ -// { -// "assessor": "assessor 2", -// "ratings": [] -// }, -// ]), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/review_type.rs b/catalyst-gateway/bin/src/legacy_service/v1/event/objective/review_type.rs deleted file mode 100644 index 3a8b753d4d2..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/event/objective/review_type.rs +++ /dev/null @@ -1,233 +0,0 @@ -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; - -use crate::{ - event_db::types::{event::EventId, objective::ObjectiveId, review::ReviewType}, - legacy_service::{handle_result, types::SerdeType, v1::LimitOffset}, - service::Error, - state::State, -}; - -pub(crate) fn review_type(state: Arc) -> Router { - Router::new().route( - "/review_types", - get(move |path, query| { - async { handle_result(review_types_exec(path, query, state).await) } - }), - ) -} - -async fn review_types_exec( - Path((SerdeType(event), SerdeType(objective))): Path<( - SerdeType, - SerdeType, - )>, - lim_ofs: Query, state: Arc, -) -> Result>, Error> { - tracing::debug!( - "review_types_query, event:{0} objective: {1}", - event.0, - objective.0, - ); - - let reviews = state - .event_db - .get_review_types(event, objective, lim_ofs.limit, lim_ofs.offset) - .await? - .into_iter() - .map(SerdeType) - .collect(); - Ok(reviews) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn review_types_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/review_types", -// 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "name": "impact", -// "description": "Impact Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "group": "review_group 1", -// }, -// { -// "id": 2, -// "name": "feasibility", -// "description": "Feasibility Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "note": true, -// "group": "review_group 2" -// }, -// { -// "id": 5, -// "name": "vpa_ranking", -// "description": "VPA Ranking of the review", -// "min": 0, -// "max": 3, -// "map": [ -// {"name": "Excellent", "desc": "Excellent Review"}, -// {"name": "Good", "desc": "Could be improved."}, -// {"name": "FilteredOut", "desc": "Exclude this review"}, -// {"name": "NA", "desc": "Not Applicable"} -// ], -// "note": false, -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/review_types?limit={2}", -// 1, 1, 2 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 1, -// "name": "impact", -// "description": "Impact Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "group": "review_group 1", -// }, -// { -// "id": 2, -// "name": "feasibility", -// "description": "Feasibility Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "note": true, -// "group": "review_group 2" -// }, -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/review_types?offset={2}", -// 1, 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 2, -// "name": "feasibility", -// "description": "Feasibility Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "note": true, -// "group": "review_group 2" -// }, -// { -// "id": 5, -// "name": "vpa_ranking", -// "description": "VPA Ranking of the review", -// "min": 0, -// "max": 3, -// "map": [ -// {"name": "Excellent", "desc": "Excellent Review"}, -// {"name": "Good", "desc": "Could be improved."}, -// {"name": "FilteredOut", "desc": "Exclude this review"}, -// {"name": "NA", "desc": "Not Applicable"} -// ], -// "note": false, -// } -// ] -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/event/{0}/objective/{1}/review_types?limit={2}&offset={3}", -// 1, 1, 1, 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// [ -// { -// "id": 2, -// "name": "feasibility", -// "description": "Feasibility Rating", -// "min": 0, -// "max": 5, -// "map": [], -// "note": true, -// "group": "review_group 2" -// }, -// ] -// ), -// ); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/mod.rs b/catalyst-gateway/bin/src/legacy_service/v1/mod.rs deleted file mode 100644 index bbf52ff5268..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::sync::Arc; - -use axum::Router; -use serde::Deserialize; - -use crate::state::State; - -mod event; -mod registration; -mod search; - -#[derive(Deserialize)] -struct LimitOffset { - limit: Option, - offset: Option, -} - -pub(crate) fn v1(state: Arc) -> Router { - let registration = registration::registration(state.clone()); - let event = event::event(state.clone()); - let search = search::search(state); - - let router = registration.merge(event).merge(search); - - Router::new().nest("/v1", router) -} diff --git a/catalyst-gateway/bin/src/legacy_service/v1/registration.rs b/catalyst-gateway/bin/src/legacy_service/v1/registration.rs deleted file mode 100644 index 4a3f8bd8a59..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/registration.rs +++ /dev/null @@ -1,358 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(clippy::too_many_lines)] - -use std::sync::Arc; - -use axum::{ - extract::{Path, Query}, - routing::get, - Router, -}; -use serde::Deserialize; - -use crate::{ - event_db::types::{ - event::EventId, - registration::{Delegator, Voter}, - }, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn registration(state: Arc) -> Router { - Router::new() - .route( - "/registration/voter/:voting_key", - get({ - let state = state.clone(); - move |path, query| async { handle_result(voter_exec(path, query, state).await) } - }), - ) - .route( - "/registration/delegations/:stake_public_key", - get({ - move |path, query| { - async { handle_result(delegations_exec(path, query, state).await) } - } - }), - ) -} - -#[derive(Deserialize)] -struct VotersQuery { - event_id: Option>, - with_delegators: Option, -} - -async fn voter_exec( - Path(voting_key): Path, - Query(VotersQuery { - event_id, - with_delegators, - }): Query, - state: Arc, -) -> Result, Error> { - tracing::debug!( - "voter_query: voting_key: {0}, event_id: {1:?}", - voting_key, - &event_id - ); - - let voter = state - .event_db - .get_voter( - &event_id.map(|val| val.0), - voting_key, - with_delegators.unwrap_or(false), - ) - .await? - .into(); - Ok(voter) -} - -#[derive(Deserialize)] -struct DelegationsQuery { - event_id: Option>, -} - -async fn delegations_exec( - Path(stake_public_key): Path, - Query(DelegationsQuery { event_id }): Query, state: Arc, -) -> Result, Error> { - tracing::debug!( - "delegator_query: stake_public_key: {0}, eid: {1:?}", - stake_public_key, - &event_id - ); - - let delegator = state - .event_db - .get_delegator(&event_id.map(|val| val.0), stake_public_key) - .await? - .into(); - Ok(delegator) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn voter_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!("/api/v1/registration/voter/{0}", "voting_key_1")) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "voter_info": { -// "voting_power": 250, -// "voting_group": "rep", -// "delegations_power": 250, -// "delegations_count": 2, -// "voting_power_saturation": 0.625, -// }, -// "as_at": "2022-03-31T12:00:00+00:00", -// "last_updated": "2022-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/voter/{0}?with_delegators=true", -// "voting_key_1" -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "voter_info": { -// "voting_power": 250, -// "voting_group": "rep", -// "delegations_power": 250, -// "delegations_count": 2, -// "voting_power_saturation": 0.625, -// "delegator_addresses": ["stake_public_key_1", "stake_public_key_2"] -// }, -// "as_at": "2022-03-31T12:00:00+00:00", -// "last_updated": "2022-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/voter/{0}?event_id={1}", -// "voting_key_1", 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "voter_info": { -// "voting_power": 250, -// "voting_group": "rep", -// "delegations_power": 250, -// "delegations_count": 2, -// "voting_power_saturation": 0.625, -// }, -// "as_at": "2020-03-31T12:00:00+00:00", -// "last_updated": "2020-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/voter/{0}?event_id={1}&with_delegators=true", -// "voting_key_1", 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "voter_info": { -// "voting_power": 250, -// "voting_group": "rep", -// "delegations_power": 250, -// "delegations_count": 2, -// "voting_power_saturation": 0.625, -// "delegator_addresses": ["stake_public_key_1", "stake_public_key_2"] -// }, -// "as_at": "2020-03-31T12:00:00+00:00", -// "last_updated": "2020-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!("/api/v1/registration/voter/{0}", "voting_key")) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/voter/{0}?event_id={1}", -// "voting_key", 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// -// #[tokio::test] -// async fn delegations_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/delegations/{0}", -// "stake_public_key_1" -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "delegations": [ -// { -// "voting_key": "voting_key_1", -// "group": "rep", -// "weight": 1, -// "value": 140, -// }, -// { -// "voting_key": "voting_key_2", -// "group": "rep", -// "weight": 1, -// "value": 100, -// }, -// ], -// "reward_address": "addrr_reward_address_1", -// "reward_payable": true, -// "raw_power": 240, -// "total_power": 1000, -// "as_at": "2022-03-31T12:00:00+00:00", -// "last_updated": "2022-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/delegations/{0}?event_id={1}", -// "stake_public_key_1", 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "delegations": [ -// { -// "voting_key": "voting_key_1", -// "group": "rep", -// "weight": 1, -// "value": 140, -// }, -// { -// "voting_key": "voting_key_2", -// "group": "rep", -// "weight": 1, -// "value": 100, -// }, -// ], -// "reward_address": "addrr_reward_address_1", -// "reward_payable": true, -// "raw_power": 240, -// "total_power": 1000, -// "as_at": "2020-03-31T12:00:00+00:00", -// "last_updated": "2020-03-31T12:00:00+00:00", -// "final": true -// } -// ), -// ); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/delegations/{0}", -// "stake_public_key" -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// -// let request = Request::builder() -// .uri(format!( -// "/api/v1/registration/delegations/{0}?event_id={1}", -// "stake_public_key", 1 -// )) -// .body(Body::empty()) -// .unwrap(); -// let response = app.oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// } diff --git a/catalyst-gateway/bin/src/legacy_service/v1/search.rs b/catalyst-gateway/bin/src/legacy_service/v1/search.rs deleted file mode 100644 index 1ac4efdabf6..00000000000 --- a/catalyst-gateway/bin/src/legacy_service/v1/search.rs +++ /dev/null @@ -1,1001 +0,0 @@ -//! Obsoleted code -//! -//! Because this code is legacy and being obsoleted, we allow certain lints to be used -//! which would not be permitted if this code was not obsoleted. -#![allow(clippy::too_many_lines)] - -use std::sync::Arc; - -use axum::{extract::Query, routing::post, Json, Router}; -use serde::Deserialize; - -use crate::{ - event_db::types::search::{SearchQuery, SearchResult}, - legacy_service::{handle_result, types::SerdeType}, - service::Error, - state::State, -}; - -pub(crate) fn search(state: Arc) -> Router { - Router::new().route( - "/search", - post(move |query, body| async { handle_result(search_exec(query, body, state).await) }), - ) -} - -/// Cannot use serde flattening, look this issue -#[derive(Deserialize)] -struct SearchParam { - #[serde(default)] - total: bool, - limit: Option, - offset: Option, -} - -async fn search_exec( - search_param: Query, Json(SerdeType(search_query)): Json>, - state: Arc, -) -> Result, Error> { - tracing::debug!("search_query",); - - let res = state - .event_db - .search( - search_query, - search_param.total, - search_param.limit, - search_param.offset, - ) - .await? - .into(); - Ok(res) -} - -// Need to setup and run a test event db instance -// To do it you can use the following commands: -// Prepare docker images -// ``` -// earthly ./containers/event-db-migrations+docker --data=test -// ``` -// Run event-db container -// ``` -// docker-compose -f src/event-db/docker-compose.yml up migrations -// ``` -// Also need establish `EVENT_DB_URL` env variable with the following value -// ``` -// EVENT_DB_URL = "postgres://catalyst-event-dev:CHANGE_ME@localhost/CatalystEventDev" -// ``` -// [readme](https://github.com/input-output-hk/catalyst-core/tree/main/src/event-db/Readme.md) -// -// #[cfg(test)] -// mod tests { -// use axum::{ -// body::Body, -// http::{header, Method, Request, StatusCode}, -// }; -// use tower::ServiceExt; -// -// use super::*; -// use crate::legacy_service::{app, tests::response_body_to_json}; -// -// #[tokio::test] -// async fn search_events_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!({ -// "total": 6, -// "results": [ -// { -// "id": 0, -// "name": "Test Fund", -// "starts": "1970-01-01T00:00:00+00:00", -// "ends": "1970-01-01T00:00:00+00:00", -// "final": true -// }, -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 2, -// "name": "Test Fund 2", -// "starts": "2021-05-01T12:00:00+00:00", -// "ends": "2021-06-01T12:00:00+00:00", -// "reg_checked": "2021-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 3, -// "name": "Test Fund 3", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2022-06-01T12:00:00+00:00", -// "reg_checked": "2022-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// { -// "id": 5, -// "name": "Test Fund 5", -// "final": false -// } -// ] -// }), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search?total=true".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!({ -// "total": 6, -// }), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!({ -// "total": 6, -// "results": [ -// { -// "id": 5, -// "name": "Test Fund 5", -// "final": false -// }, -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// { -// "id": 3, -// "name": "Test Fund 3", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2022-06-01T12:00:00+00:00", -// "reg_checked": "2022-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 2, -// "name": "Test Fund 2", -// "starts": "2021-05-01T12:00:00+00:00", -// "ends": "2021-06-01T12:00:00+00:00", -// "reg_checked": "2021-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 0, -// "name": "Test Fund", -// "starts": "1970-01-01T00:00:00+00:00", -// "ends": "1970-01-01T00:00:00+00:00", -// "final": true -// } -// ] -// }), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?limit={0}", 2)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 2, -// "results": [ -// { -// "id": 5, -// "name": "Test Fund 5", -// "final": false -// }, -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?offset={0}", 2)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 4, -// "results": [ -// { -// "id": 3, -// "name": "Test Fund 3", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2022-06-01T12:00:00+00:00", -// "reg_checked": "2022-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 2, -// "name": "Test Fund 2", -// "starts": "2021-05-01T12:00:00+00:00", -// "ends": "2021-06-01T12:00:00+00:00", -// "reg_checked": "2021-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 1, -// "name": "Test Fund 1", -// "starts": "2020-05-01T12:00:00+00:00", -// "ends": "2020-06-01T12:00:00+00:00", -// "reg_checked": "2020-03-31T12:00:00+00:00", -// "final": true -// }, -// { -// "id": 0, -// "name": "Test Fund", -// "starts": "1970-01-01T00:00:00+00:00", -// "ends": "1970-01-01T00:00:00+00:00", -// "final": true -// }, -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?limit={0}&offset={1}", 1, 1)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "description", -// "search": "Fund" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 1, -// "results": [ -// { -// "id": 4, -// "name": "Test Fund 4", -// "starts": "2022-05-01T12:00:00+00:00", -// "ends": "2024-06-01T12:00:00+00:00", -// "final": false -// }, -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "events", -// "filter": [{ -// "column": "funds", -// "search": "Fund 4" -// }], -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// -// #[tokio::test] -// async fn search_objectives_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "description", -// "search": "description" -// }], -// "order_by": [{ -// "column": "description", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 4, -// "results": [ -// { -// "id": 1, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 1", -// "description": "description 1", -// "deleted": false, -// }, -// { -// "id": 2, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 2", -// "description": "description 2", -// "deleted": false, -// }, -// { -// "id": 3, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 3", -// "description": "description 3", -// "deleted": false, -// }, -// { -// "id": 4, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 4", -// "description": "description 4", -// "deleted": false, -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search?total=true".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "description", -// "search": "description" -// }], -// "order_by": [{ -// "column": "description", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 4, -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "description", -// "search": "description" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 4, -// "results": [ -// { -// "id": 4, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 4", -// "description": "description 4", -// "deleted": false, -// }, -// { -// "id": 3, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 3", -// "description": "description 3", -// "deleted": false, -// }, -// { -// "id": 2, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 2", -// "description": "description 2", -// "deleted": false, -// }, -// { -// "id": 1, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 1", -// "description": "description 1", -// "deleted": false, -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?limit={0}", 1)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "description", -// "search": "description" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 1, -// "results": [ -// { -// "id": 4, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 4", -// "description": "description 4", -// "deleted": false, -// }, -// ] -// -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?offset={0}", 1)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "description", -// "search": "description" -// }], -// "order_by": [{ -// "column": "description", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 3, -// "results": [ -// { -// "id": 3, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 3", -// "description": "description 3", -// "deleted": false, -// }, -// { -// "id": 2, -// "type": { -// "id": "catalyst-native", -// "description": "??" -// }, -// "title": "title 2", -// "description": "description 2", -// "deleted": false, -// }, -// { -// "id": 1, -// "type": { -// "id": "catalyst-simple", -// "description": "A Simple choice" -// }, -// "title": "title 1", -// "description": "description 1", -// "deleted": false, -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "objectives", -// "filter": [{ -// "column": "funds", -// "search": "description 1" -// }], -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// -// #[tokio::test] -// async fn search_proposals_test() { -// let state = Arc::new(State::new(None).await.unwrap()); -// let app = app(state); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 3, -// "results": [ -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false, -// }, -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false, -// }, -// { -// "id": 30, -// "title": "title 3", -// "summary": "summary 3", -// "deleted": false, -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search?total=true".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 3, -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 3, -// "results": [ -// { -// "id": 30, -// "title": "title 3", -// "summary": "summary 3", -// "deleted": false -// }, -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?limit={0}", 2)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 2, -// "results": [ -// { -// "id": 30, -// "title": "title 3", -// "summary": "summary 3", -// "deleted": false -// }, -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?offset={0}", 1)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 2, -// "results": [ -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// }, -// { -// "id": 10, -// "title": "title 1", -// "summary": "summary 1", -// "deleted": false -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri(format!("/api/v1/search?limit={0}&offset={1}", 1, 1)) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "title", -// "search": "title" -// }], -// "order_by": [{ -// "column": "title", -// "descending": true, -// }] -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::OK); -// assert_eq!( -// response_body_to_json(response).await.unwrap(), -// serde_json::json!( -// { -// "total": 1, -// "results": [ -// { -// "id": 20, -// "title": "title 2", -// "summary": "summary 2", -// "deleted": false -// } -// ] -// } -// ), -// ); -// -// let request = Request::builder() -// .method(Method::POST) -// .uri("/api/v1/search".to_string()) -// .header(header::CONTENT_TYPE, "application/json") -// .body(Body::from( -// serde_json::json!({ -// "table": "proposals", -// "filter": [{ -// "column": "description", -// "search": "description 1" -// }], -// }) -// .to_string(), -// )) -// .unwrap(); -// let response = app.clone().oneshot(request).await.unwrap(); -// assert_eq!(response.status(), StatusCode::NOT_FOUND); -// } -// } diff --git a/catalyst-gateway/bin/src/main.rs b/catalyst-gateway/bin/src/main.rs index 50e257e9f5c..675d55c859e 100644 --- a/catalyst-gateway/bin/src/main.rs +++ b/catalyst-gateway/bin/src/main.rs @@ -3,7 +3,6 @@ use clap::Parser; mod cli; mod event_db; -mod legacy_service; mod logger; mod service; mod settings; diff --git a/catalyst-gateway/bin/src/service/mod.rs b/catalyst-gateway/bin/src/service/mod.rs index cf888c842d9..7c432365f73 100644 --- a/catalyst-gateway/bin/src/service/mod.rs +++ b/catalyst-gateway/bin/src/service/mod.rs @@ -1,10 +1,7 @@ //! Main entrypoint to the service use std::{net::SocketAddr, sync::Arc}; -use serde::Serialize; -use tokio::try_join; - -use crate::{legacy_service, state::State}; +use crate::state::State; // These Modules contain endpoints mod api; @@ -20,9 +17,6 @@ pub(crate) use poem_service::get_app_docs; /// Service level errors #[derive(thiserror::Error, Debug)] pub(crate) enum Error { - /// Cannot run the service - #[error("Cannot run service, error: {0}")] - CannotRunService(String), /// An error with the EventDB #[error(transparent)] EventDb(#[from] crate::event_db::error::Error), @@ -31,29 +25,13 @@ pub(crate) enum Error { Io(#[from] std::io::Error), } -/// Error message -#[derive(Serialize, Debug)] -pub(crate) struct ErrorMessage { - /// Error message - error: String, -} - -impl ErrorMessage { - /// Create a new [`ErrorMessage`] with the specified error string. - pub(crate) fn new(error: String) -> Self { - Self { error } - } -} - -/// # Run all web services. +/// # Run Catalyst Gateway Service. /// -/// This will currently run both a Axum based Web API, and a Poem based API. -/// This is only for migration until all endpoints are provided by the Poem service. +/// Runs the Poem based API. /// /// ## Arguments /// /// `service_addr`: &`SocketAddr` - the address to listen on -/// `metrics_addr`: &`Option` - the address to listen on for metrics /// `state`: `Arc` - the state /// /// ## Errors @@ -62,16 +40,5 @@ impl ErrorMessage { /// `Error::EventDbError` - cannot connect to the event db /// `Error::IoError` - An IO error has occurred. pub(crate) async fn run(service_addr: &SocketAddr, state: Arc) -> Result<(), Error> { - // Create service addresses to be used during poem migration. - // Service address is same as official address but +1 to the port. - let mut legacy_service = *service_addr; - legacy_service.set_port(legacy_service.port() + 1); - - // This can be simplified to an .await when axum is finally removed. - try_join!( - legacy_service::run(&legacy_service, state.clone()), - poem_service::run(service_addr, state), - )?; - - Ok(()) + poem_service::run(service_addr, state).await } diff --git a/catalyst-gateway/bin/src/service/poem_service.rs b/catalyst-gateway/bin/src/service/poem_service.rs index f6ac1b0934f..4426f9954c6 100644 --- a/catalyst-gateway/bin/src/service/poem_service.rs +++ b/catalyst-gateway/bin/src/service/poem_service.rs @@ -18,10 +18,7 @@ use crate::{ docs::{docs, favicon}, utilities::{ catch_panic::{set_panic_hook, ServicePanicHandler}, - middleware::{ - chain_axum::ChainAxum, - tracing_mw::{init_prometheus, Tracing}, - }, + middleware::tracing_mw::{init_prometheus, Tracing}, }, Error, }, @@ -48,7 +45,6 @@ fn mk_app(hosts: Vec, base_route: Option, state: &Arc) -> .nest("/metrics", PrometheusExporter::new(prometheus_registry)) .nest("/favicon.ico", favicon()) .with(Cors::new()) - .with(ChainAxum::new()) // TODO: Remove this once all endpoints are ported. .with(Compression::new().with_quality(CompressionLevel::Fastest)) .with(CatchPanic::new().with_handler(ServicePanicHandler)) .with(Tracing) diff --git a/catalyst-gateway/bin/src/service/utilities/middleware/chain_axum.rs b/catalyst-gateway/bin/src/service/utilities/middleware/chain_axum.rs deleted file mode 100644 index c0cd7fbcd8a..00000000000 --- a/catalyst-gateway/bin/src/service/utilities/middleware/chain_axum.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! Custom middleware to catch any unimplemented endpoints and then pass them to the -//! legacy axum implementation. -//! -//! Allows us to have 1 API and seamlessly migrate unconverted requests. -//! //! This whole module is deprecated, so don;t worry if its not documented how we would -//! like. -#![allow(clippy::missing_docs_in_private_items)] - -use std::sync::Arc; - -use bytes::Bytes; -use hyper::{HeaderMap, StatusCode, Version}; -use poem::{ - async_trait, error::NotFoundError, Endpoint, IntoResponse, Middleware, Request, Response, - Result, -}; -use tower::ServiceExt; - -use crate::{legacy_service, service::common::responses::resp_5xx::server_error, state::State}; - -/// Middleware to chain call Axum if endpoint is not found. -pub(crate) struct ChainAxum; - -impl ChainAxum { - /// Create new `ChainAxum` middleware with any value. - pub(crate) fn new() -> Self { - ChainAxum {} - } -} - -impl Middleware for ChainAxum -where E: Endpoint -{ - type Output = ChainAxumEndpoint; - - fn transform(&self, ep: E) -> Self::Output { - ChainAxumEndpoint { inner: ep } - } -} - -/// Endpoint for `ChainAxum` middleware. -#[allow(clippy::module_name_repetitions)] -pub(crate) struct ChainAxumEndpoint { - inner: E, -} - -struct AxumResponse { - version: Version, - status: StatusCode, - headers: HeaderMap, - body: Bytes, -} - -impl AxumResponse { - fn new(version: Version, status: StatusCode, headers: HeaderMap, body: Bytes) -> Self { - AxumResponse { - version, - status, - headers, - body, - } - } -} - -impl IntoResponse for AxumResponse { - fn into_response(self) -> Response { - let mut resp = Response::builder() - .status(self.status) - .version(self.version); - - for (h, v) in &self.headers { - resp = resp.header(h, v); - } - - resp.body(self.body) - } -} - -#[async_trait] -impl Endpoint for ChainAxumEndpoint -where E: Endpoint -{ - type Output = Response; - - async fn call(&self, req: Request) -> Result { - // Need to copy all the request parts because its consumed by the `call`. - let (parts, body) = req.into_parts(); - let method = parts.method.clone(); - let uri = parts.uri.clone(); - let version = parts.version; - let headers = parts.headers.clone(); - let state: &Arc = parts - .extensions - .get() - .ok_or(server_error!("Cannot acquire state"))?; - let state = state.clone(); - let body = body.into_bytes().await.unwrap_or_else(|_| Bytes::new()); - let body_copy = body.clone(); - - let req = Request::from_parts(parts, poem::Body::from(body)); - - match self.inner.call(req).await { - Ok(response) => Ok(response.into_response()), - Err(err) => { - // Only if the error is a 404 (Not found) then try and chain to axum, handler. - if err.is::() { - // Build an app instance to run the endpoint. - let app = legacy_service::app(state); - - let mut request = axum::http::Request::builder() - .method(method) - .uri(uri) - .version(version); - - // Add all the headers from the request. - for (h, v) in &headers { - request = request.header(h, v); - } - - // Add the body. - let request = request - .body(body_copy.into()) - .map_err(|_| server_error!("Cannot build request body"))?; - - // Call the endpoint - #[allow(clippy::expect_used)] // The result here is infallible. - let response = app.oneshot(request).await.expect("This is infallible."); - let version = response.version(); - let status = response.status(); - let headers = response.headers().clone(); - let body = hyper::body::to_bytes(response.into_body()) - .await - .unwrap_or_else(|_| Bytes::new()); - - let axum_response = AxumResponse::new(version, status, headers, body); - - Ok(axum_response.into_response()) - } else { - Err(err) - } - }, - } - } -} - -#[cfg(test)] -mod tests { - // use super::*; - - #[tokio::test] - async fn test_axum_chain() { - //#[handler(internal)] - // async fn index(req: &Request) { - // assert_eq!(req.extensions().get::(), Some(&100)); - //} - - // let cli = TestClient::new(index.with(ChainAxum::new(100i32))); - // cli.get("/").send().await.assert_status_is_ok(); - } -} diff --git a/catalyst-gateway/bin/src/service/utilities/middleware/mod.rs b/catalyst-gateway/bin/src/service/utilities/middleware/mod.rs index dc76347046f..01b7f96939d 100644 --- a/catalyst-gateway/bin/src/service/utilities/middleware/mod.rs +++ b/catalyst-gateway/bin/src/service/utilities/middleware/mod.rs @@ -1,4 +1,3 @@ //! Custom POEM Middleware for this service. -pub(crate) mod chain_axum; pub(crate) mod tracing_mw;